[英]JAVA AES ECB Encryption to Golang migration
我嘗試將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);
}
我嘗試了像密碼學GIST或
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)
不會引發任何錯誤,並返回一個字符串。 但是,該字符串與加密數據之間的距離並不很遠。 很感謝任何形式的幫助! 謝謝!
Java默認使用PKCS5算法添加一個填充。 在您的Go代碼中,您必須使用以下方式刪除該填充(在返回解密值之前):
func pkcs5UnPadding(src []byte) []byte {
length := len(src)
if length%64 == 0 {
return src
}
unpadding := int(src[length-1])
return src[:(length - unpadding)]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.