I am trying to encrypt a value server side and then decrypt from the browser side. This is the Java code I'm using to encrypt, which is working correctly:
package aes;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class AesEncryption {
private static SecretKeySpec secretKey;
private static byte[] key;
public static void setKey(String myKey) {
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public static String encrypt(String strToEncrypt, String secret) {
try {
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
}
catch (Exception e)
{
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}
I then have a JavaScript method I call to decrypt the encrypted value:
aesDecrypt(encryptedValue) {
console.log("TESTING ENCRYPTED VALUE : " , encryptedValue)
var bytes = CryptoJS.AES.decrypt(encryptedValue, secretAesKey, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
})
console.log("TESTING BYTES : " , bytes)
var originalValue = bytes.toString(CryptoJS.enc.Utf8);
console.log("TESTING ORIGINAL VALUE : " , originalValue)
return originalValue
}
When logging each step of the decryption, when trying to print the original value, it's just blank. I know that the encryptedValue has to be converted back to bytes in the same way that it was originally encrypted and then has to be encoded with UTF-8 to get back to the original string. What else could I be missing that is causing this?
myKey.getBytes("UTF-8");is in 99% of all occurrences a bug and a security issue because a String is never directly used as a key in cryptography. If you have a password use a key derivation function that has password as input and a 128bit/256bit key key as output.myKey.getBytes("UTF-8");issue. I have never really worked with encryption so am just trying to get a basic baseline code working first.