帮我加密AES/CBC/PKCS7Padding
?
以下是我解密AES/CBC/PKCS7
的代码。
它正在工作,但是当我加密一些字符串并从我自己解密它是错误的。下面我添加代码来加密和解密AES / CBC / PKCS7Padding。
- (NSData *)AES256Encrypt:(id)key
{
NSString *iv = @"FEDCBA9876543210";
NSData *keyPtr = [key copy];
size_t dataLength = [self length];
NSData *ivPtr = [iv dataUsingEncoding:NSUTF8StringEncoding];
//NSData *encrypted = [self subdataWithRange:NSMakeRange(0, [self length])];
//size_t bufferSize = dataLength + kCCBlockSizeAES128;
//void* buffer = malloc(bufferSize);
NSMutableData *ret = [NSMutableData dataWithLength:dataLength + kCCBlockSizeAES128];
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
[keyPtr bytes], kCCKeySizeAES256,
[ivPtr bytes],
[self bytes], dataLength,
[ret mutableBytes], [ret length],
&numBytesDecrypted);
NSLog(@"Err : %d",cryptStatus);
NSLog(@"DataLength : %d, num : %d", (int)dataLength, (int)numBytesDecrypted);
if (cryptStatus == kCCSuccess)
return ret;
return nil;
}
- (NSData *)AES256Decrypt:(id)key
{
NSData *keyPtr = [key copy];
size_t dataLength = [self length] - kCCBlockSizeAES128;
NSData *ivPtr = [self subdataWithRange:NSMakeRange(0, kCCBlockSizeAES128)];
NSData *encrypted = [self subdataWithRange:NSMakeRange(kCCBlockSizeAES128, dataLength)];
NSMutableData *ret = [NSMutableData dataWithLength:dataLength + kCCBlockSizeAES128];
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
[keyPtr bytes], kCCKeySizeAES256,
[ivPtr bytes], /* initialization vector (optional) */
[encrypted bytes], dataLength, /* input */
[ret mutableBytes], [ret length], /* output */
&numBytesDecrypted);
NSLog(@"Err : %d",cryptStatus);
NSLog(@"DataLength : %d, num : %d", (int)dataLength, (int)numBytesDecrypted);
if (cryptStatus == kCCSuccess)
return ret;
return nil;
}
我的字符串:"abcd"
从Python加密= "fl6h8iBeXGO03ZIKzpDMwMaNc7Y1PsRc/s6XJKPCxKNyrYResv3oO1/bkbofmY7y8e2wOe2sIpk="