Search code examples
javascriptobjective-cencryptionencodingcryptojs

Javascript AES encryption doesn't match iOS AES encryption


I am encrypting an NSString in iOS like this which encodes and decodes fine:

NSString *stringtoEncrypt = @"This string is to be encrypted";
NSString *key = @"12345678901234567890123456789012";

// Encode
NSData *plain = [stringtoEncrypt dataUsingEncoding:NSUTF8StringEncoding];
NSData *cipher = [plain AES256EncryptWithKey:key];

NSString *cipherBase64 = [cipher base64EncodedString];
NSLog(@"ciphered base64: %@", cipherBase64);

// Decode
NSData *decipheredData = [cipherBase64 base64DecodedData];
NSString *decoded = [[NSString alloc] initWithData:[decipheredData AES256DecryptWithKey:key] encoding:NSUTF8StringEncoding];
NSLog(@"%@", decoded);

NSData extension:

- (NSData *)AES256EncryptWithKey:(NSString *)key
{
    // 'key' should be 32 bytes for AES256, will be null-padded otherwise
    char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
    bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)

    // fetch key data
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

    NSUInteger dataLength = [self length];

    //See the doc: For block ciphers, the output size will always be less than or
    //equal to the input size plus the size of one block.
    //That's why we need to add the size of one block here
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);

    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
                                          keyPtr, kCCKeySizeAES256,
                                          NULL /* initialization vector (optional) */,
                                          [self bytes], dataLength, /* input */
                                          buffer, bufferSize, /* output */
                                          &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        //the returned NSData takes ownership of the buffer and will free it on deallocation
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    }

    free(buffer); //free the buffer;
    return nil;
}

I can successfully pass the resulting Base64 string to Node.js and have it decode the message. What I also need, is the same encoding method written in Javascript. Here is what I have so far:

<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js"></script>
...
var text = "This string is to be encrypted";
var key = "12345678901234567890123456789012";
var iv  = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00';
var encrypted = CryptoJS.AES.encrypt(text, key, {iv: iv});
console.log("Base64 encoded: " + window.btoa(encrypted.ciphertext));

However the resulting Base64 string does not match the one generated by iOS. Any ideas?


Solution

  • CryptoJS uses a password-based encryption compatible with OpenSSL when you pass a string as a key. Since you already have a full key and IV, you need to convert them into CryptoJS' native type which is a WordArray:

    var key = CryptoJS.enc.Utf8.parse("12345678901234567890123456789012");
    var iv  = CryptoJS.lib.WordArray.create([0, 0, 0, 0]); // each number is a word of 32 bit
    

    By calling btoa() on a WordArray object, you're forcing it to the stringified. The default hex-encoding is used for this. Afterwards btoa() encodes this hex-encoded string into Bas64 which bloats it even more.

    You can directly encode a WordArray into Base64:

    encrypted.ciphertext.toString(CryptoJS.enc.Base64)