Skip to content

Instantly share code, notes, and snippets.

@kennydude
Created July 14, 2012 14:31
Show Gist options
  • Save kennydude/3111592 to your computer and use it in GitHub Desktop.
Save kennydude/3111592 to your computer and use it in GitHub Desktop.
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
@aliciafraguasrubio
Copy link

Thank you!

@neeraj87
Copy link

neeraj87 commented Sep 7, 2017

That was amazing. Thanks a ton.

@goldyraj
Copy link

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
Copy link

I've this error

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

@zaw-hlaing-bwar
Copy link

@monossido
use this one instead

var decipher = crypto.createDecipher('aes-128-ecb', key);
return decipher.update(encrypted, 'base64', 'utf8') + decipher.final('utf8');

@krajkumard
Copy link

Hi,
I have a similar problem this is my java code
Cipher c = Cipher.getInstance("Rijndael");
SecretKeySpec k = new SecretKeySpec(ENCRYPTION_KEY, "Rijndael");
c.init(Cipher.ENCRYPT_MODE, k);
byte[] encryptedData = c.doFinal(value.toString().getBytes());

I need nodejs script to decrypt the same.

@aseemrastogi
Copy link

Hi - in NodeJS code which 'crypto' library is being used?

var decipher = crypto.createDecipher('aes-128-ecb', encryption_key);

@ridvann
Copy link

ridvann commented Mar 13, 2019

Hi,
I have a similar problem, I couldn't fully convert the Java Code below into NodeJs.

Java Code:

                int ivLen = 8;
                byte[] keyiv = new byte[ivLen];
                for(int i=0 ; i<ivLen ; i++) {
                                keyiv[i] = input[i];
                }
                
                int dataLen = input.length-ivLen;
                byte[] data = new byte[dataLen];
                for (int i=0 ; i<dataLen ; i++) {
                                data[i] = input[i+ivLen];
                }
                
                Key deskey = null;
                DESedeKeySpec spec = new DESedeKeySpec(Base64.decodeBase64(decryptionKey));
                SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
                deskey = keyfactory.generateSecret(spec);

                Cipher cipher = Cipher.getInstance("TripleDES/CBC/NoPadding");
                IvParameterSpec ips = new IvParameterSpec(keyiv);
                cipher.init(Cipher.DECRYPT_MODE, deskey, ips);

                byte[] bout = cipher.doFinal(data);
                
                return Base64.decodeBase64(bout);

NodeJs / Javascript:

    var bufferKey = new Buffer(keyInfo,'base64');
    var alg = "des-ede3-cbc";
    var autoPad = false;

    var ivLen = 8;

    var keyiv = new ArrayBuffer(ivLen); //byte[] keyiv = new byte[ivLen];

    for(var i=0 ; i<ivLen ; i++) {
        keyiv[i] = input[i];
    }

    var dataLen = input.length-ivLen; //int dataLen = input.length-ivLen;
    var data = new ArrayBuffer(dataLen); //byte[] data = new byte[dataLen];

    for (var i=0 ; i<dataLen ; i++) {
        data[i] = input[i+ivLen];
    }

    //decrypt
    var decipher = crypto.createDecipheriv(alg, bufferKey, keyiv);
    decipher.setAutoPadding(autoPad);
    var txt = decipher.update(data, 'base64', 'utf8');
    txt += decipher.final('utf8');
    console.log(alg, txt);

    callback(null, txt);

I am getting an error "IV must be a buffer".

Does anyone have a comment?

Thanks

@gmahota
Copy link

gmahota commented May 13, 2019

Hi everyone,
Can You help me to convert this code to node js.

private static String getBearerToken(String apiKey, String publicKey) {
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
Cipher cipher = Cipher.getInstance("RSA");
byte[] encodedPublicKey = Base64.decodeBase64(publicKey);
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
PublicKey pk = keyFactory.generatePublic(publicKeySpec);
cipher.init(Cipher.ENCRYPT_MODE, pk);
byte[] encryptedApiKey = Base64.encodeBase64(cipher.doFinal(apiKey.getBytes("UTF-8")));
return new String(encryptedApiKey, "UTF-8");
} catch (Exception e) {
System.out.println(e.getMessage());
}

    return null;
} 

@mituso89
Copy link

Hi everyone. I have a code in java
private Cipher createDesCipher(final KeyDES keyDes, final String key) throws Exception {
final String des = keyDes.getDesKey(key);
if (des == null) {
KeyUtils.logger.error("\u4f7f\u7528\u4e86\u8fc7\u671f\u7684Key,keyDes.getDesKey(key)==null key=" + key + " keyDEs=" + keyDes.toString());
return null;
}
final Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding", (Provider)new BouncyCastleProvider());
final DESKeySpec desKeySpec = new DESKeySpec(des.getBytes("UTF-8"));
final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES", (Provider)new BouncyCastleProvider());
final SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
final IvParameterSpec iv = new IvParameterSpec(des.getBytes("UTF-8"));
if (keyDes.isEncryptMode()) {
cipher.init(1, secretKey, iv);
}
else {
cipher.init(2, secretKey, iv);
}
return cipher;
}

I want to convert it to nodejs. Please suggestion for me. Thanh you so much

@sandrapavankumar
Copy link

I have an error saying to create a class ENCRYPTION_KEY, please help here.
byte[] thedigest = md.digest(ENCRYPTION_KEY.getBytes("UTF-8"));

And Base64.DEFAULTis not recognizing if anyone got this work please help
String query = Base64.encodeToString(cipherText, Base64.DEFAULT);

@kennydude
Copy link
Author

I have an error saying to create a class ENCRYPTION_KEY, please help here.
byte[] thedigest = md.digest(ENCRYPTION_KEY.getBytes("UTF-8"));

And Base64.DEFAULTis not recognizing if anyone got this work please help
String query = Base64.encodeToString(cipherText, Base64.DEFAULT);

ENCRYPTION_KEY is a constant, not a class. You can tell by the fact it used .getBytes(..), a method found on a String object.

If I remember, this works against Android at the time (a long time ago now). So this could have changed (you're following 7 year old code! Surely there's a StackOverflow answer that's newer!)

@sandrapavankumar
Copy link

I have an error saying to create a class ENCRYPTION_KEY, please help here.
byte[] thedigest = md.digest(ENCRYPTION_KEY.getBytes("UTF-8"));
And Base64.DEFAULTis not recognizing if anyone got this work please help
String query = Base64.encodeToString(cipherText, Base64.DEFAULT);

ENCRYPTION_KEY is a constant, not a class. You can tell by the fact it used .getBytes(..), a method found on a String object.

If I remember, this works against Android at the time (a long time ago now). So this could have changed (you're following 7 year old code! Surely there's a StackOverflow answer that's newer!)

Thanks Kenny Its working good, for decryption I have an error at chunks.push(decipher.final('binary'));
internal/crypto/cipher.js:164
const ret = this._handle.final();
^

Error: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length
at Decipher.final (internal/crypto/cipher.js:164:28)

Any suggestions please.

@ssuriyayuvan
Copy link

@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');
};

createCipher is now deprecated.

@sarithakaredla
Copy link

    byte[] ivWrap = {0, 2, 4, 6, 2, 9, 5, 1, 4, 1, 5, 9, 2, 7, 1, 0};
    ivWrapSpec = new IvParameterSpec(ivWrap);
            byte[] key = (Key).getBytes("UTF-8");

	MessageDigest sha = MessageDigest.getInstance("SHA-256");
	key = sha.digest(key);
	SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");

can some one please give me node js code for above java code

@mubasharmwm
Copy link

Any example of encrypting at Node and decrypting at .Net or Java using BouncyCastle??

@codewithshehraz
Copy link

Java Encryption Code(https://repl.it/@ShehrazKhan/Encrypt-in-Java-Decrypt-in-Nodejs)

public static String encrypt(String Data, String secret) throws Exception {
        Key key = generateKey(secret);
        Cipher c = Cipher.getInstance(ALGO);
        c.init(Cipher.ENCRYPT_MODE, key);
        byte[] encVal = c.doFinal(Data.getBytes());
        String encryptedValue = Base64.getEncoder().encodeToString(encVal);
        return encryptedValue;
    }

Node Js(https://codesandbox.io/s/decrypt-aes-in-node-encrypted-in-java-vph6w)

var encryptedBase64Key = "aXRzaG91bGRiZTE2Y2hhcg==";
   var parsedBase64Key = CryptoJS.enc.Base64.parse(encryptedBase64Key);
   var encryptedCipherText = "wbsl6Tegfc7mexCHUYPS+dON3BWfgU+tD1nkiHiZ4LyrHlUXlWsfeInWMDaZO39z"; // or encryptedData;
   var decryptedData = CryptoJS.AES.decrypt(
     encryptedCipherText,
     parsedBase64Key,
     {
       mode: CryptoJS.mode.ECB,
       padding: CryptoJS.pad.Pkcs7
     }
   );
   // console.log( “DecryptedData = “ + decryptedData );
   // this is the decrypted data as a string
   var decryptedText = decryptedData.toString(CryptoJS.enc.Utf8);
   setDecryptedCipherText(decryptedText);
   console.log("DecryptedText = " + decryptedText);

@farhan-ct
Copy link

I've this error

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

@monossido use this one instead

var decipher = crypto.createDecipher('aes-128-ecb', key); return decipher.update(encrypted, 'base64', 'utf8') + decipher. Final('utf8');

I am getting this error

Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment