Golang迁移的JAVA AES ECB加密

时间:2018-06-11 11:42:08

标签: java go encryption aes ecb

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

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

1 个答案:

答案 0 :(得分:2)

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)]
}