Domanda

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
È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top