Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AES256 encryption get different result between node.js and objective-c

1.Node.js

    var crypto = require('crypto');
    var key = "my password";
    var text = "text to encrypt";  
    var cipher = crypto.createCipher('aes-256-cbc',key);  
    var crypted =cipher.update(text,'utf8','base64');
    crypted+=cipher.final('base64');

Result: ZeYCYOrR/w7qSAZVYht8+Q==

2.Objective-C

{
    NSString *key = @"my password";
    NSString *text = @"text to encrypt";
    NSData *plain = [secret dataUsingEncoding:NSUTF8StringEncoding];
    NSData *cipher = [plain AES256EncryptWithKey:key];
    NSLog(@"%@\n", [cipher base64Encoding] );
}

Result: raFGdTWYvSPWpkgtF9LJIg==

[AES256EncryptWithKey:] is HERE

like image 965
Mil0R3 Avatar asked Nov 12 '22 18:11

Mil0R3


1 Answers

The problem is that node.js crypto.createCipher internally uses a key derivation function EVP_BytesToKey() to generate the AES key and iv from the key = "my password". Thus the actual AES keys are different for node.js and Common Crypto.

The answer is to use crypto.createCipheriv(algorithm, key, iv) in place of crypto.createCipher(algorithm, password).

From the node.js documentation:

In line with OpenSSL's recommendation to use pbkdf2 instead of EVP_BytesToKey it is recommended you derive a key and iv yourself with crypto.pbkdf2 and to then use createCipheriv() to create the cipher stream.

like image 165
zaph Avatar answered Nov 15 '22 06:11

zaph