openssl equivalent for AES256EncryptWithKey method

妖精的绣舞 提交于 2019-12-11 02:21:18

问题


How to get the same result as the following objective-c encrypting method with the command line openssl ?

- (NSData *)AES256EncryptWithKey:(NSString *)key {
    NSData *returnData = nil;

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

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

    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                          kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding | kCCOptionECBMode,
                                          keyPtr,
                                          kCCBlockSizeAES128,
                                          NULL,
                                          [self bytes],
                                          dataLength,
                                          buffer,
                                          bufferSize,
                                          &numBytesEncrypted);

    if (cryptStatus == kCCSuccess) {
        returnData  = [[NSData alloc] initWithBytes:buffer length:numBytesEncrypted];
    }

    free(buffer);

    return returnData;
}

I tried the following ones (with and without -nosalt), but unsuccessfully:

openssl aes-256-ecb -nosalt -in original.txt -out encrypted.txt
openssl aes-128-ecb -nosalt -in original.txt -out encrypted.txt

回答1:


While it may be possible, you shouldn't. This ObjC encryption code is very broken. It's creating the key incorrectly, which is why you're having trouble with OpenSSL (which also creates keys poorly, but better, and in a different way). If you want an ObjC encryption module compatible with OpenSSL, see RNCryptor which is designed to handle this problem. If possible, I'd avoid OpenSSL, but there isn't currently a simple commandline replacement that I recommend.

See the docs for RNCryptor for why this ObjC code is broken, and also the problems with OpenSSl's aes encryption routines.



来源:https://stackoverflow.com/questions/12231033/openssl-equivalent-for-aes256encryptwithkey-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!