Search code examples
javascriptioscryptojspbkdf2

PBKDF2 hashing in javascript and iOS generating different keys


This is a question related to the post: https://groups.google.com/forum/#!topic/crypto-js/t_HeWo5QhLk

I have tried to solution mentioned in the post but still cannot figure out the problem with my code:

using Crypto.js

var key= CryptoJS.PBKDF2("gf8uny", "2mnfpLsa+5I=", { keySize: 256/32, iterations: 1000 });
console.log(key.toString());
console.log(btoa(key.toString()));
//OUTPUT: MDBkN2E5MWZkZjAzYTk5MWVkMzI0OTE1YWM4OTNmMDhkOTlmY2E0NTRmN2M0MTY5YTFhYzc2M2M1ZjMzZTY0Zg==

using CommonCrypto in iOS:

NSMutableData *webKey = [NSMutableData dataWithLength:64];
NSData *salt = [@"2mnfpLsa+5I=" dataUsingEncoding:NSUTF8StringEncoding];
NSString* password = @"gf8uny";
CCKeyDerivationPBKDF(kCCPBKDF2, password.UTF8String, password.length, salt.bytes,salt.length, kCCPRFHmacAlgSHA1, 1000, webKey.mutableBytes, webKey.length);

NSString* skey = [webKey base64EncodedStringWithOptions:0];
NSLog(@"key %@",skey);
//OUTPUT: ANepH98DqZHtMkkVrIk/CNmfykVPfEFpoax2PF8z5k+jrwa0yTNt0tQedQ4bxqV/T0gXbsyKHiVx8DuJdlkufA==

The output string in both codes is base64 encoded.

Can anyone point out what is wrong with this code?

Thanks!


Solution

  • The reason that the output looks different is that the input to Base64 is different; the reason for that is that in the JavsScript code, you've called

    key.toString()
    

    So, in JavaScript, you have base64-encoded the 64-character string

    "00d7a91fdf03a991ed324915ac893f08d99fca454f7c4169a1ac763c5f33e64f"
    

    And jn Objective-C, you have base64-encoded the raw 32-byte sequence

    0x00 0xd7 0xa9 0x1f 0xdf ... 0xe6 0x4f
    

    In both cases, your PBKDF2 code has come up with the same key. You have just encoded the key differently in each case.

    You can get CryptoJS to create the same Base64 output by serializing the key directly, like this:

    key.toString(CryptoJS.enc.Base64)
    

    (See https://code.google.com/p/crypto-js/#The_Hasher_Output for the documentation. You may have to include another script file for this output format to be available)