将AES-128加密的NSData转换为NSString

时间:2016-11-09 10:28:13

标签: objective-c nsstring aes nsdata

我正在尝试将AES-128加密的NSData转换为NSString,如下所示。但是,当我尝试解密相同的加密字符串时,它会给出一个输出nil。

NSString* testString = @"TestTest";
NSString* secretKey = @"asdfsadf";

NSData *reqStringData = [testString dataUsingEncoding:NSUTF8StringEncoding];

NSData *encryptedData = [reqStringData AES128EncryptedDataWithKey:secretKey];
NSString * encryptedString = [[NSString alloc] initWithData:encryptedData encoding:kCFStringEncodingUTF8];

NSData *decryptedData = [[encryptedString dataUsingEncoding:kCFStringEncodingUTF8] AES128DecryptedDataWithKey:secretKey];
NSString * decryptedString = [[NSString alloc] initWithBytes:[decryptedData bytes] length:[decryptedData length] encoding:kCFStringEncodingUTF8];

NSLog(@"%@", decryptedString);

我使用的AES功能是

- (NSData *)AES128DecryptedDataWithKey:(NSString *)key
{
    return [self AES128DecryptedDataWithKey:key iv:nil];
}

- (NSData *)AES128Operation:(CCOperation)operation key:(NSString *)key iv:(NSString *)iv
{
    char keyPtr[kCCKeySizeAES128 + 1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

    char ivPtr[kCCBlockSizeAES128 + 1];
    bzero(ivPtr, sizeof(ivPtr));

    if (iv) {
        [iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
    }

    NSUInteger dataLength = [self length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);

    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(operation,
                                      kCCAlgorithmAES128,
                                      kCCOptionPKCS7Padding | kCCOptionECBMode,
                                      keyPtr,
                                      kCCBlockSizeAES128,
                                      ivPtr,
                                      [self bytes],
                                      dataLength,
                                      buffer,
                                      bufferSize,
                                      &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    }

    free(buffer);
    return nil;
}

任何人都可以在我出错的地方帮助我吗?

0 个答案:

没有答案