0

I have a encryption/decryption functionality in java code and wanted to write the same logic using the crypto node-js library. What's the equivalent of these Java codes ?

Java code :


 String iv = "Some random string";
 AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv.getBytes());

What I tried :

const iv = "Some random string"
var ivSpec = new Buffer.from(iv);

Java code :
String key = "Some random key";
SecretKeySpec newKey = new SecretKeySpec(key.getBytes(), "AES");

What I tried :

const key = "Some random key"
var newKey = new Buffer.from(key);

Java code :

String message = "Some message"
Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
byte[] bytes = cipher.doFinal(textBytes.getBytes());

In java code it is using "AES/CFB/NoPadding" and I found equivalent in node js crypto i.e "aes-256-cfb" so I used it.

var crypto = require('crypto');

var cipher = crypto.createCipheriv('aes-256-cfb', newKey, ivSpec);
cipher.update(message, 'utf8');
cipher.final();

Is that correct ? Where I am doin it wrong cause there is no output of cipher.final(). Thanks in advance.

Madhav mishra
  • 313
  • 4
  • 20
  • *...Is that correct?...* Have you compared the results of the two codes? Depending on the mode, `final()` takes padding into account or generates/checks an authentication tag. Although both are irrelevant for CFB (and `final()` returns nothing), it's more robust to concatenate the results of the `update()` and `final()` calls (e.g. with respect to a change of the mode). – Topaco Feb 22 '23 at 13:39
  • Could you add some resources to go deeper into this? Thanks – Madhav mishra Feb 23 '23 at 12:47
  • See the *crypto* documentation. For more details see the [source code](https://github.com/nodejs/node/blob/main/src/crypto/crypto_cipher.cc#L889). Note that *crypto* is just an OpenSSL wrapper, `final()` essentially calls the OpenSSL functions `EVP_CipherFinal_ex()` and `EVP_CIPHER_CTX_ctrl()`. See their OpenSSL documentation for more details. – Topaco Feb 23 '23 at 16:36

0 Answers0