3

I'm dealing with a legacy application that uses a custom protocol to cipher communication. Random AES keys are generated in legacy Java app like this:

keygen = KeyGenerator.getInstance("AES");
keygen.init(128);
keygen.generateKey().getEncoded();

I've been looking for solutions on crypto with no luck. How can I generate this key on nodejs?

Orhan Obut
  • 8,756
  • 5
  • 32
  • 42
Eugenio Cuevas
  • 10,858
  • 3
  • 29
  • 51

1 Answers1

1

That code probably does not do as much as you think. It simply generates 16 (128 / 8) secure random bytes, then wraps a key object around it. So with nodejs, you simply generate 16 bytes and feed the algorithm the raw key data.

If you want to use the generated key, then make sure you create a binary encoded string or buffer from the bytes returned by the getEncoded() method. You could use hexadecimal encoding/decoding if you require the key to be a textual string somewhere in the process.

See randomBytes() and createCipheriv() for information.

AES keys are just cryptographically strong random bytes, DES (parity bits) and RSA (prime number calculation) keys are not.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
  • Cryptographic keys are more than just random bytes. See http://docs.oracle.com/javase/7/docs/api/java/security/SecureRandom.html – Jonathan Rosenne Jan 26 '14 at 20:58
  • @JonathanRosenne: How is that *more* than random? – President James K. Polk Jan 26 '14 at 21:12
  • @JonathanRosenne OK, made that "cryptographically strong", although I already put "secure random" in the first paragraph... – Maarten Bodewes Jan 26 '14 at 22:02
  • @MaartenBodewes May I ask what is the equivalent `kgen.init(KEY_SIZE, SecureRandom.getInstance("SHA1PRNG"));` part in Node.js, since `randomBytes()` only supports bytes size as parameter. – kenshinji Aug 16 '18 at 04:36
  • @kenshinjo you may want to read this [answer](https://stackoverflow.com/a/43033592/4265714) – miradham Aug 16 '18 at 04:52
  • @kenshinji Generally, `SecureRandom.getInstance("SHA1PRNG"))` should **not** be used in Java code; you use either `new SecureRandom()` or - for additional protection of long term keys - `SecureRandom.getInstanceStrong()`. However, in the end you'll just get a random generator. Just use the normal `randomBytes` or any other crypto secure random number generator. – Maarten Bodewes Aug 16 '18 at 12:10