4

I'm experiencing an odd issue using NodeJS crypto and the crypto.randomBtyes function. I've detected strange behaviorthat seems to have only recently appeared in my NodeJS / Typescript 3.2 application.

The error makes sense in its own right: Invalid key length at Cipheriv.createCipherBase (internal/crypto/cipher.js:79:18)

Upon inspecting the key length returned, it is doubling the requested number of bytes. I stated this as "odd" in that it was working previously (as of Thursday/Friday last week (3/7/2019 - 3/8/2019) but as of this morning the new behavior was detected. However, I haven't run any updates since so hopefully I'm missing something obvious. I could change my key size to be half of what I want, however, I wanted to see if I'm overlooking something simple before I implement a hack.

Here is a fairly basic example of my crypto implementation.

import crypto = require('crypto');

export class Encryption {
    static GenerateRandomBytesToHex(size: number): string {
        return crypto.randomBytes(size).toString('hex');
    }
}

However when calling:

let cipherKey = Encryption.GenerateRandomBytesToHex(32);

It is returning a 64 character string rather than a 32 character string.

Example: c8a8437677fcfab679f92c8470ffc34b932f5aaa3296c09f652d2becfe1db8b2 (64 characters in length)

This is an implementation of the concepts outlined in this article: http://vancelucas.com/blog/stronger-encryption-and-decryption-in-node-js/

Any help would be greatly appreciated.

Chason Arthur
  • 519
  • 1
  • 11
  • 22

1 Answers1

10

GenerateRandomBytesToHex function returns you a hash that is X Byte long inside of a String where each Byte is displayed in hexadecimal value.

The hexidecimal value of the number 42 is 0x2A. You can see that one Byte (from 0 to 254) is displayed using 2 character in hexadecimal. So it's normal that 32 Byte get displayed as 64 character.


Exemple : https://codebeautify.org/string-hex-converter

enter image description here

Orelsanpls
  • 22,456
  • 6
  • 42
  • 69
  • 1
    Thank you for the quick response. I knew it had to be something glaringly obvious. I was counting the character length of my initialization vectors as a benchmark, but since those are 16 bytes, which would get doubled to 32 when toString('hex') is called, that gave me enough of a red herring to go brain dead. Answer makes perfect since and should have caught it! Thanks again friend! – Chason Arthur Mar 11 '19 at 15:32