Reputation: 899
I am trying to encode using a static key say as an example: "B3FFCA612CD0C3D9050A4DE3588E2830F26BEF6D7E1CEC77DD2F22FAFC038D33" in AES and ECB mode. when i try this with openssl, I successfully get a result with no issues but when I code it in groovy or java:
Invalid AES key length: 64 bytes
when I researched this, the issue occurs because the key length can be 32 bytes at most, now I am confused because the API i am sending these encrpions to, completely works with the 64 byte key i am sending but fails with the 32 byte one. openssl encodes this too with the 64 byte key I provide as below:
openssl enc -aes-256-ecb -e -in infile.txt -a -A -K B3FFCA612CD0C3D9050A4DE3588E2830F26BEF6D7E1CEC77DD2F22FAFC038D33 -iv 0 -p
I want to be able to do the same but in groovy/java.
I am not sure what I am missing, I would really apprecaite your help on this please!
here is my code:
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.SecretKeyFactory;
import javax.crypto.SecretKey;
import javax.crypto.Cipher;
import java.security.spec.KeySpec;
import javax.crypto.spec.PBEKeySpec;
class AESCrypt {
// encrypt
def encrypt (def plainText, def secret) {
def cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
// converty string secret to SecretKeySpec
byte[] decodedKey = Base64.getDecoder().decode(secret);
SecretKeySpec key= new SecretKeySpec(decodedKey , 0, decodedKey.length,
"AES");
cipher.init(Cipher.ENCRYPT_MODE, key)
return cipher.doFinal(plainText.getBytes("UTF-8")).encodeBase64().toString()
}
}
//Main
for( int i = 0; i < dataContext.getDataCount(); i++ ) {
InputStream is = dataContext.getStream(i);
Properties props = dataContext.getProperties(i);
def c = new AESCrypt()
def secret =
"B3FFCA612CD0C3D9050A4DE3588E2830F26BEF6D7E1CEC77DD2F22FAFC038D33"
//get plaintext of payload
Scanner s = new Scanner(is).useDelimiter("\\A");
String plainPayload = s.hasNext() ? s.next() : "";
//encrypt plaintext of payload
def encryptedPayload = c.encrypt(plainPayload, secret)
println encryptedPayload + "\n"
}
Upvotes: 0
Views: 12139
Reputation: 141678
openssl encodes this too with the 64 byte key I provide as below.
It's not a 64-byte key. It's a 32-byte key that's been hexadecimal encoded, which results in 64 letters.
You are trying to base64 decode your secret, which is not the same as hexadecimal.
I'm not a Java or Groovy expert, but may be able to use decodeHex()
on your string to hex decode it instead of base64 decode it.
Upvotes: 8