问题
Plain text : Encrypt and decrypt text with AES algorithm
Key (256) : testsecret
Result (https://aesencryption.net/) : iFhSyFY3yYoO2G6GVGkdhZJjD+h0Pxv5fQnO3xIarzuGQSkIxlrpSprC5bC3gJ2U
i use small code in object to decrypt this this text :
(NSData*)AES256DecryptWithKey:(NSString*)key { // 'key' should be 32 bytes for AES256, will be null-padded otherwise char keyPtr[kCCKeySizeAES256 + 1]; // room for terminator (unused) bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
// fetch key data [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
//See the doc: For block ciphers, the output size will always be less than or //equal to the input size plus the size of one block. //That's why we need to add the size of one block here size_t bufferSize = dataLength + kCCBlockSizeAES128; void* buffer = malloc(bufferSize);
size_t numBytesDecrypted = 0; // char iv[kCCBlockSizeAES128 + 1]; bzero(iv, sizeof(iv)) ; CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES, kCCOptionPKCS7Padding , keyPtr, kCCKeySizeAES256, NULL /* initialization vector (optional) /, [self bytes], dataLength, / input / buffer, bufferSize, / output */ &numBytesDecrypted);
if (cryptStatus == kCCSuccess) { //the returned NSData takes ownership of the buffer and will free it on deallocation return [NSMutableData dataWithBytesNoCopy:buffer length:numBytesDecrypted]; }
free(buffer); //free the buffer; return nil; }
Result : t\PFLFC\^X\^C^\^^\^RWQV\^\ypt text with AES algorithm
Seem it alway wrong first 16bit block. Can u help me. what i'm wrong when encrypt ?
回答1:
Try to use AESCrypt-ObjC instead of Cryptlib Library.
Installation
Add this line to your class:
#import "AESCrypt.h"
Usage
NSString *message = @"top secret message";
NSString *password = @"p4ssw0rd";
Encrypting
NSString *encryptedData = [AESCrypt encrypt:message password:password];
Decrypting
NSString *message = [AESCrypt decrypt:encryptedData password:password];
Hope this will help.
Also, you can see this answer: https://stackoverflow.com/a/51767050/5167909
回答2:
Your CCCryptorStatus parameters in osstatus : should look like this
cryptStatus = CCCrypt( kCCDecrypt, kCCAlgorithmAES128,kCCOptionECBMode + kCCOptionPKCS7Padding, keyPtr, kCCKeySizeAES256 NULL,[self bytes], dataLength, buffer, bufferSize, &numBytesEncrypted );
,
However you length of the key is less than 16 bytes. At least make sure that your secret key should be of 16 bytes.
来源:https://stackoverflow.com/questions/52055075/how-to-decrypt-aes-256-https-aesencryption-net-ios