Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use id-aes256-GCM with Node.JS crypto? "TypeError: DecipherFinal fail"

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...

like image 871
Heinzi Avatar asked Jun 29 '12 09:06

Heinzi


1 Answers

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)

like image 71
David R. Avatar answered Sep 19 '22 20:09

David R.