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

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!