我尝试将 AES 解密的 Java 实现移植到 Golang。我需要使用 Golang 解密以前由 JAVA 代码加密的数据。但到目前为止,我没有运气解密它。
Java代码是:
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);
}
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)
不抛出错误,并返回一个字符串。但是这个字符串并不接近加密数据。很感谢任何形式的帮助!谢谢!