如何在iOS中使用AES256解密字符串

时间:2017-09-15 06:10:20

标签: ios objective-c string

我加密了字符串"我是一个好孩子"用密钥" 1234",我想解密它。这是我的代码,但它最终输出" NULL"但不是"我是一个好孩子"。我怎样才能得到正确的结果?

NSString *content = @"VvHjCwHUjIgZOiYlncPWEoX/UInS7ZNbC4sy8ESa/fM=";

NSData *contentData = [content dataUsingEncoding:NSUTF8StringEncoding];
NSUInteger dataLength = contentData.length;

NSString *key = @"1234";

char keyPtr[kCCKeySizeAES256+1];
bzero(keyPtr, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128,
                                      kCCOptionPKCS7Padding,
                                      keyPtr, kCCKeySizeAES256,
                                      NULL,
                                      contentData.bytes, dataLength,
                                      buffer, bufferSize,
                                      &numBytesDecrypted);
if (cryptStatus == kCCSuccess) {
    NSData *result = [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
    if(result) {
        NSString * string = [[NSString alloc]initWithData:result encoding:NSUTF8StringEncoding];
        NSLog(@"%@",string);
    }
}else {
    free(buffer);
}

1 个答案:

答案 0 :(得分:0)

您的数据看起来像是base64编码的。你应该像这样解码它:

NSData *contentData = [[NSData alloc] initWithBase64EncodedString:content options:0];