doutangshuan6473 2018-06-11 11:42
浏览 175

JAVA AES ECB加密到Golang迁移

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!

  • 写回答

1条回答 默认 最新

  • douguio0185 2019-05-27 13:57
    关注

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

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容