0

I have java encryption function code as

public String encrypt(String Data, String keySet) throws Exception {
    byte[] keyByte = keySet.getBytes();
    Key key = generateKey(keyByte);

    Cipher c = Cipher.getInstance("AES");

    c.init(Cipher.ENCRYPT_MODE, key); //2
    byte[] encVal = c.doFinal(Data.getBytes()); //1
    byte[] encryptedByteValue = new Base64().encode(encVal); //3
    String encryptedValue = new String(encryptedByteValue); //4
    return encryptedValue;
}

private static Key generateKey(byte[] keyByte) throws Exception {
    Key key = new SecretKeySpec(keyByte, "AES");
    return key;
}

Now I am trying to implement the same in NodeJs using crypto module code is: -

//buf is string data that i want to encrypt

function makeEncrypt(buf, callback) {
    var enckey = "encryptionkey";
    var cipher = crypto.createCipher(algorithm, enckey)
    var crypted = cipher.update(buf, 'utf8', 'base64')
    crypted += cipher.final('base64');

    console.log("encrypted data is : " + crypted.toString());
    callback(null, crypted);
}

But the encrypted data returned by both functions is different what I am doing wrong? if anyone can help!! thanks in advance.

7
  • Your node.js code is incomplete. Commented Jul 14, 2017 at 16:00
  • 1
    General advice: Always use a fully qualified Cipher string. Cipher.getInstance("AES"); may result in different ciphers depending on the default security provider. It most likely results in "AES/ECB/PKCS5Padding", but it doesn't have to be. If it changes, you'll lose compatibility between different JVMs. For reference: Java default Crypto/AES behavior Commented Jul 14, 2017 at 16:00
  • 1
    Never use ECB mode. It's deterministic and therefore not semantically secure. You should at the very least use a randomized mode like CBC or CTR. It is better to authenticate your ciphertexts so that attacks like a padding oracle attack are not possible. This can be done with authenticated modes like GCM or EAX, or with an encrypt-then-MAC scheme. Commented Jul 14, 2017 at 16:00
  • crypto.createCipher takes a password and not a key. If you want to supply a key, use crypto.createCipheriv Commented Jul 14, 2017 at 16:01
  • @Artjom B. I cannot make changes in java code as it is already implemented I only need to convert the above code to nodejs and the output should be same. and cypto.createCipheriv requires a random iv each time while encrypting but in java code we are not using any random key or anything like that so i think the output will never match. Commented Jul 15, 2017 at 6:33

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.