Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Encrypt from Java and decrypt on Node.js
// Encrypt where jo is input, and query is output and ENCRPYTION_KEy is key
byte[] input = jo.toString().getBytes("utf-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(ENCRYPTION_KEY.getBytes("UTF-8"));
SecretKeySpec skc = new SecretKeySpec(thedigest, "AES/ECB/PKCS5Padding");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skc);
byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
ctLength += cipher.doFinal(cipherText, ctLength);
String query = Base64.encodeToString(cipherText, Base64.DEFAULT);
var decipher = crypto.createDecipher('aes-128-ecb', encryption_key);
chunks = []
chunks.push( decipher.update( new Buffer(fullBuffer, "base64").toString("binary")) );
chunks.push( decipher.final('binary') );
var txt = chunks.join("");
txt = new Buffer(txt, "binary").toString("utf-8");
// where encryption_key = key, fullBuffer is the input and txt is output
@jibbo

This comment has been minimized.

Show comment
Hide comment
@jibbo

jibbo Apr 16, 2013

Very useful, thank you!

jibbo commented Apr 16, 2013

Very useful, thank you!

@raimckenzie

This comment has been minimized.

Show comment
Hide comment
@raimckenzie

raimckenzie Mar 28, 2014

After some minor tweaking this worked perfectly for me!
Thank you very much!

After some minor tweaking this worked perfectly for me!
Thank you very much!

@Blink1982

This comment has been minimized.

Show comment
Hide comment
@Blink1982

Blink1982 Jun 26, 2014

Getting a ... on the java side

Exception in thread "main" java.security.InvalidKeyException: Wrong algorithm: AES or Rijndael required
at com.sun.crypto.provider.SunJCE_c.a(DashoA13_..)
at com.sun.crypto.provider.SunJCE_g.a(DashoA13_..)
at com.sun.crypto.provider.SunJCE_f.a(DashoA13_..)
at com.sun.crypto.provider.SunJCE_f.a(DashoA13_..)
at com.sun.crypto.provider.AESCipher.engineInit(DashoA13_..)
at javax.crypto.Cipher.a(DashoA13_..)
at javax.crypto.Cipher.a(DashoA13_..)
at javax.crypto.Cipher.init(DashoA13_..)
at javax.crypto.Cipher.init(DashoA13*..)
at ci.ThirdCipher.main(ThirdCipher.java:31)

Getting a ... on the java side

Exception in thread "main" java.security.InvalidKeyException: Wrong algorithm: AES or Rijndael required
at com.sun.crypto.provider.SunJCE_c.a(DashoA13_..)
at com.sun.crypto.provider.SunJCE_g.a(DashoA13_..)
at com.sun.crypto.provider.SunJCE_f.a(DashoA13_..)
at com.sun.crypto.provider.SunJCE_f.a(DashoA13_..)
at com.sun.crypto.provider.AESCipher.engineInit(DashoA13_..)
at javax.crypto.Cipher.a(DashoA13_..)
at javax.crypto.Cipher.a(DashoA13_..)
at javax.crypto.Cipher.init(DashoA13_..)
at javax.crypto.Cipher.init(DashoA13*..)
at ci.ThirdCipher.main(ThirdCipher.java:31)

@jabbaugh

This comment has been minimized.

Show comment
Hide comment
@jabbaugh

jabbaugh Aug 15, 2014

Thanks for posting. You just saved me a lot of time. The only change I made was:
SecretKeySpec skc = new SecretKeySpec(thedigest, "AES/ECB/PKCS5Padding");
to
SecretKeySpec skc = new SecretKeySpec(thedigest, "AES");

Thanks for posting. You just saved me a lot of time. The only change I made was:
SecretKeySpec skc = new SecretKeySpec(thedigest, "AES/ECB/PKCS5Padding");
to
SecretKeySpec skc = new SecretKeySpec(thedigest, "AES");

@girish3

This comment has been minimized.

Show comment
Hide comment
@girish3

girish3 Sep 18, 2014

I used it in my Android code....Thanks dude

girish3 commented Sep 18, 2014

I used it in my Android code....Thanks dude

@ligerzero459

This comment has been minimized.

Show comment
Hide comment
@ligerzero459

ligerzero459 Aug 15, 2015

Super helpful. Thanks a ton for posting this

Super helpful. Thanks a ton for posting this

@shashank-komuroju

This comment has been minimized.

Show comment
Hide comment
@shashank-komuroju

shashank-komuroju Sep 26, 2015

I used "sha-1" for message digest. how should the node equivalent code be changed.

I used "sha-1" for message digest. how should the node equivalent code be changed.

@ricky07

This comment has been minimized.

Show comment
Hide comment
@ricky07

ricky07 Oct 21, 2015

Can you please help me to write same encryption for Java script.

ricky07 commented Oct 21, 2015

Can you please help me to write same encryption for Java script.

@plainOldCode

This comment has been minimized.

Show comment
Hide comment
@plainOldCode

plainOldCode Dec 3, 2015

@ricky07 try this

var encrypt = function(data, key) {
var cipher = crypto.createCipher('aes-128-ecb', key);
return cipher.update(data, 'utf8', 'base64') + cipher.final('base64');
};

var decrypt = function(data, key) {
var decipher = crypto.createDecipher('aes-128-ecb', key);
return decipher.update(data, 'base64', 'utf8') + decipher.final('utf8');
};

@ricky07 try this

var encrypt = function(data, key) {
var cipher = crypto.createCipher('aes-128-ecb', key);
return cipher.update(data, 'utf8', 'base64') + cipher.final('base64');
};

var decrypt = function(data, key) {
var decipher = crypto.createDecipher('aes-128-ecb', key);
return decipher.update(data, 'base64', 'utf8') + decipher.final('utf8');
};

@mancdevcarl

This comment has been minimized.

Show comment
Hide comment
@mancdevcarl

mancdevcarl Dec 5, 2015

can someone please show me the code to DECRYPT on android (using the same spec as encrypting outlined above)

can someone please show me the code to DECRYPT on android (using the same spec as encrypting outlined above)

@nascimentodiego

This comment has been minimized.

Show comment
Hide comment
@nascimentodiego

nascimentodiego Jan 21, 2016

Hi man, great code.
What is license to use ?

Hi man, great code.
What is license to use ?

@siddo420

This comment has been minimized.

Show comment
Hide comment
@siddo420

siddo420 Feb 2, 2016

can you also write an example on how to encrypt using Javascript (Node.js)?

I am trying to encrypt secure token. See https://developers.google.com/recaptcha/docs/secure_token?hl=en

siddo420 commented Feb 2, 2016

can you also write an example on how to encrypt using Javascript (Node.js)?

I am trying to encrypt secure token. See https://developers.google.com/recaptcha/docs/secure_token?hl=en

@xexi

This comment has been minimized.

Show comment
Hide comment
@xexi

xexi Aug 8, 2016

work like a charm 👍

xexi commented Aug 8, 2016

work like a charm 👍

@tuananh

This comment has been minimized.

Show comment
Hide comment
@tuananh

tuananh Apr 12, 2017

@kennydude

Can anyone help me how to convert this java snippet to nodejs equivalent?

byte[] key = nonce.getBytes("UTF-8");
MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
key = messageDigest.digest(key);
key = Arrays.copyOf(key, 16);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
Cipher ecipherSymmetric = Cipher.getInstance("AES");
ecipherSymmetric.init(Cipher.ENCRYPT_MODE, secretKeySpec);

tuananh commented Apr 12, 2017

@kennydude

Can anyone help me how to convert this java snippet to nodejs equivalent?

byte[] key = nonce.getBytes("UTF-8");
MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
key = messageDigest.digest(key);
key = Arrays.copyOf(key, 16);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
Cipher ecipherSymmetric = Cipher.getInstance("AES");
ecipherSymmetric.init(Cipher.ENCRYPT_MODE, secretKeySpec);
@LuizGC

This comment has been minimized.

Show comment
Hide comment
@LuizGC

LuizGC May 17, 2017

Very nice, @kennydude. This tip helps me a lot.l

LuizGC commented May 17, 2017

Very nice, @kennydude. This tip helps me a lot.l

@aliciafraguasrubio

This comment has been minimized.

Show comment
Hide comment

Thank you!

@neeraj87

This comment has been minimized.

Show comment
Hide comment
@neeraj87

neeraj87 Sep 7, 2017

That was amazing. Thanks a ton.

neeraj87 commented Sep 7, 2017

That was amazing. Thanks a ton.

@goldyraj

This comment has been minimized.

Show comment
Hide comment
@goldyraj

goldyraj Nov 24, 2017

public static String encrypt(byte[] plaintext) throws Exception, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {

    PublicKey key = readPublicKey(publicKeyUrl1);
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    System.out.println("file content: " + key);//44
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] encryptedByte = cipher.doFinal(plaintext);
    String encodedString = new String(java.util.Base64.getEncoder().encode(encryptedByte));
    return encodedString;
}                please convert node js code 
public static String encrypt(byte[] plaintext) throws Exception, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {

    PublicKey key = readPublicKey(publicKeyUrl1);
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    System.out.println("file content: " + key);//44
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] encryptedByte = cipher.doFinal(plaintext);
    String encodedString = new String(java.util.Base64.getEncoder().encode(encryptedByte));
    return encodedString;
}                please convert node js code 
@monossido

This comment has been minimized.

Show comment
Hide comment
@monossido

monossido Apr 20, 2018

I've this error

Error: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length

I've this error

Error: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment