首页 > 解决方案 > JAVA AES ECB 加密到 Golang 迁移

问题描述

我尝试将 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);
}

我尝试了 Cryptography 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)

不抛出错误,并返回一个字符串。但是这个字符串并不接近加密数据。很感谢任何形式的帮助!谢谢!

标签: javagoencryptionaesecb

解决方案


默认情况下,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)]
}

推荐阅读