Reputation: 37
I try to port a Java implementation of AES decryption to Golang. I need to decrypt data that is previously encrypted by the JAVA code using Golang. But so far I have no luck decrypting it.
The Java code is:
private static byte[] pad(final String password) {
String key;
for (key = password; key.length() < 16; key = String.valueOf(key) + key) {}
return key.substring(0, 16).getBytes();
}
public static String encrypt(String password, String message) throws Exception
{
SecretKeySpec skeySpec = new SecretKeySpec(pad(password), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(1, skeySpec);
byte[] encrypted = cipher.doFinal(message.getBytes());
return Hex.encodeHexString(encrypted);
}
public static String decrypt(String password, String message)
throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(pad(password), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(1, skeySpec);
cipher.init(2, skeySpec);
byte[] original = cipher.doFinal(Hex.decodeHex(message.toCharArray()));
return new String(original);
}
I tried implementations like Cryptography GIST or
func decrypt(passphrase, data []byte) []byte {
cipher, err := aes.NewCipher([]byte(passphrase))
if err != nil {
panic(err)
}
decrypted := make([]byte, len(data))
size := 16
for bs, be := 0, size; bs < len(data); bs, be = bs+size, be+size {
cipher.Decrypt(decrypted[bs:be], data[bs:be])
}
return decrypted
}
hx, _ := hex.DecodeString(hexString)
res := decrypt([]byte(password), hx)
No error is thrown, and a string is returned. But this string is not anywhere close to the encrypted data. Any help is very much appreciated! Thanks!
Upvotes: 2
Views: 890
Reputation: 1542
Java adds a padding by default with the PKCS5 algorithm. In your Go code, you have to remove that padding with something like this (before returning the decrypted value):
func pkcs5UnPadding(src []byte) []byte {
length := len(src)
if length%64 == 0 {
return src
}
unpadding := int(src[length-1])
return src[:(length - unpadding)]
}
Upvotes: 3