3

EDIT: The issue can be simplified to this: The following Node.js code give an "Invalid IV length" Error. Why? What should the IV be?

const crypto = require('crypto')
const decipher = crypto.createDecipheriv('aes-128-gcm', crypto.randomBytes(16), crypto.randomBytes(16))

I'm using AES in GCM mode to encrypt some data, but I'm using two different languages and libraries for encryption and decryption and they seem to have different vocabularies about what I need.

I'm encrypting with a Python library (Crypto). The encrypt_and_digest method takes a 128 bit key and a message and returns a 128 bit nonce, 128 bit tag, and a ciphertext.

(Encryption code taken from this example)

I'm decrypting with the default Node.js crypto library. That library expects a session key, a tag, and an IV. When I pass the nonce from the Python library as the IV, it gives me an “invalid iv size” error. Examples of the Node library seem to use a 12-character string as an IV.

My decryption code looks like this (taken from here):

var decipher = crypto.createDecipheriv(algorithm, password, nonce)
decipher.setAuthTag(encrypted.tag);
var dec = decipher.update(encrypted.content, 'hex', 'utf8')

What is the difference between IV and nonce for this scheme? How should I resolve this? Thanks!

QuinnFreedman
  • 2,242
  • 2
  • 25
  • 42

1 Answers1

10

It turns out the nonce for GCM should be 12 bytes long. I'm not sure why the python library defaults to auto-generating a 16-byte nonce, but you can generate your own and specify it manually in the AES constructor, so thats what I did. The whole system works perfectly now

QuinnFreedman
  • 2,242
  • 2
  • 25
  • 42
  • 7
    Some background: 12 bytes (or rather 96 bits) is the recommended default in the NIST specification of GCM (the 38D document, if I'm not mistaken). The other sizes require additional operations and may be slightly less secure. So NIST suggests always using 96 bits especially *to remain compatible with other implementations*. – Maarten Bodewes May 16 '17 at 22:03