ghbutton / react-native-simple-crypto

A simpler React-Native crypto library
https://www.npmjs.com/package/react-native-simple-crypto
MIT License
42 stars 25 forks source link

Error with PBKDF2.hash #14

Closed mougis closed 4 years ago

mougis commented 4 years ago

I am facing an error with this code:

const password = "secret text";
const salt = RNSimpleCrypto.utils.randomBytes(8);
const iterations = 4096;
const keyInBytes = 32;
const hash = "SHA1";
const passwordKey = await RNSimpleCrypto.PBKDF2.hash(
    password,
    salt,
    iterations,
        keyInBytes,
        hash
    );
console.log("PBKDF2 passwordKey:", passwordKey);

The log of the error is :

[Error: invalid hex:{length=32,bytes='a hex value'}]

doruxan commented 4 years ago

I get that with code below

  const secretKeyBuffer = RNSimpleCrypto.utils.convertBase64ToArrayBuffer(APIKey)
    const signatureBuffer = RNSimpleCrypto.utils.convertUtf8ToArrayBuffer(signatureRawData)

    const signatureArrayBuffer = await RNSimpleCrypto.HMAC.hmac256(signatureBuffer, secretKeyBuffer);

    const signatureBase64 = RNSimpleCrypto.utils.convertArrayBufferToBase64(
        signatureArrayBuffer
    )
mamelmahdy commented 4 years ago

I think the problem is similar to what I had when calling HMAC.hmac256. With iOS13+, the format for NSData hex values has changed to the format {length:32, bytes='hex value'}. I believe it has something to do with calling description within the native hmac algorithm.

I got around this issue by editing the Hmac.m file at this path /react-native-simple-crypto/ios/RCTCrypto/lib/Hmac.m to grab the bytes value and convert to string. The new function is...

+ (NSString *) hmac256: (NSString *)input key: (NSString *)key {
    NSData *keyData = [Shared fromHex:key];
    NSData* inputData = [Shared fromHex:input];
    void* buffer = malloc(CC_SHA256_DIGEST_LENGTH);
    CCHmac(kCCHmacAlgSHA256, [keyData bytes], [keyData length], [inputData bytes], [inputData length], buffer);
    NSData *nsdata = [NSData dataWithBytesNoCopy:buffer length:CC_SHA256_DIGEST_LENGTH freeWhenDone:YES];

// Added convert to hex string
    NSUInteger capacity = nsdata.length * 2;
    NSMutableString *sbuf = [NSMutableString stringWithCapacity:capacity];
    const unsigned char *buf = nsdata.bytes;
    NSInteger i;
    for (i=0; i<nsdata.length; ++i) {
      [sbuf appendFormat:@"%02X", (NSUInteger)buf[i]];
    }

    return [Shared toHex:sbuf];
}
ghbutton commented 4 years ago

Could you try with the latest version?

ghbutton commented 4 years ago

Going to close, please reopen if there is still an issue