17
votes

I want to encrypt some data in Node.js using an authenticated encryption scheme like AES-GCM.

If I run the following sample code

app.get("/test", function(req,res)  {
  var key = "12345678901234567890123456789012";
  var iv = "123456789012"; 
  var cipher = crypto.createCipheriv("id-aes256-GCM",key.toString("binary"),iv.toString("binary"));
  var decipher = crypto.createDecipheriv("id-aes256-GCM",key.toString("binary"),iv.toString("binary"));

  console.log(decipher.update(cipher.update("bla")));
  console.log(decipher.update(cipher.final()));
  console.log(decipher.final());
});

I don't get a console output but the error message "TypeError: DecipherFinal fail". If I use cipher AES-256-CTR instead of "id-aes256-GCM", this code works fine and prints "bla" on the console.

What am I doing wrong?

edit:

Further investigating shows, that cipher.update("bla") returns "â" (single character...strange) and cipher.final() returns an empty string. I think this can't be a correct ciphertext which should at least have the size of the plaintext...

1
What is the size of the returned ciphertext of cipher.update("bla") and cipher.final() ? - Maarten Bodewes
I edited the question to answer it - Heinzi
Sorry for the misunderstanding - I meant that I answered YOUR question with the edit. Unfortunatelly I don't have access to a pc with the id-aes256-GCM encryption scheme for the next 3 weeks, so I'll test your suggestion cipher.update("bla","binary","hex") then. - Heinzi
As far as I can tell, this is an issue with OpenSSL. Issuing echo -n "bla" | openssl enc -e -id-aes256-GCM -nosalt -a -out t.out followed by openssl enc -d -id-aes256-GCM -nosalt -a -in t.out yields the error bad decrypt. Maybe a bug in OpenSSL? - fuzic
GCM requires extra parameters, which NodeJS can possibly not give to OpenSSL. See this thread/link: mail-archive.com/[email protected]/msg68932.html - StevenLooman

1 Answers

6
votes

GCM mode in OpenSSL works fine. It has been tested with other implementations as well. I know for a fact that the PolarSSL SSL library has its own GCM implementation for AES and PolarSSL can work fine with OpenSSL in return.

The GCM mode of encryption for AES requires specific GCM-related parameters. The current NodeJS API cannot provide these values to OpenSSL. And as such the calls fail, but not with clean errors. (This is more of an OpenSSL issue than a NodeJS issue).

(StevenLoomen points the reason out in the comments as well, but I'd like an answer for everybody to see)