在Java和Golang中使用AES加密时,结果不匹配。

huangapple 未分类评论78阅读模式
英文:

Mismatch in result when encrypting in AES for Java and Golang

问题

我正在使用以下Java代码来使用简单的AES算法生成密文:

public String encrypt(String message, String key) {
    skeySpec = new SecretKeySpec(HexUtil.HexfromString(key), "AES");
    cipher = Cipher.getInstance("AES");
    cipher.init(1, skeySpec);

    byte encstr[] = cipher.doFinal(message.getBytes());
    return HexUtil.HextoString(encstr);
}

而HexfromString函数如下:

public static byte[] HexfromString(String s) {
    int i = s.length();
    byte[] byte0 = new byte[(i + 1) / 2];
    int j = 0;
    int k = 0;
    if (i % 2 == 1) byte0[k++] = (byte) HexfromDigit(s.charAt(j++));

    while (j < i) {
         int v1 = HexfromDigit(s.charAt(j++)) << 4;
         int v2 = HexfromDigit(s.charAt(j++));
         byte0[k++] = (byte) (v1 | v2);
    }
    return byte0;
}

我在Golang中编写了以下代码来模拟上述结果:

func EncryptAES(secretKey string, plaintext string) string {
    key := hex.DecodeString(secretKey)
	c, err := aes.NewCipher(key)
	CheckError(err)

	out := make([]byte, len(plaintext))
	c.Encrypt(out, []byte(plaintext))
	return hex.EncodeToString(out)
}

但问题是,hex.DecodeString()返回的[]byte密钥是无符号整数,而在Java中,结果是有符号整数。显然,即使每个输入都相同,加密文本的结果也是不同的。

英文:

I'm using this code in Java to generate the cipher text using simple AES algorithm:

public String encrypt(String message, String key) {
    skeySpec = new SecretKeySpec(HexUtil.HexfromString(key), &quot;AES&quot;);
    cipher = Cipher.getInstance(&quot;AES&quot;);
    cipher.init(1, skeySpec);

    byte encstr[] = cipher.doFinal(message.getBytes());
    return HexUtil.HextoString(encstr);
}

And the function HexfromString is:

public static byte[] HexfromString(String s) {
    int i = s.length();
    byte[] byte0 = new byte[(i + 1) / 2];
    int j = 0;
    int k = 0;
    if (i % 2 == 1) byte0[k++] = (byte) HexfromDigit(s.charAt(j++));

    while (j &lt; i) {
         int v1 = HexfromDigit(s.charAt(j++)) &lt;&lt; 4;
         int v2 = HexfromDigit(s.charAt(j++));
         byte0[k++] = (byte) (v1 | v2);
    }
    return byte0;
}

I wrote the following code in Golang to mimic the above result.

func EncryptAES(secretKey string, plaintext string) string {
    key := hex.DecodeString(secretKey)
	c, err := aes.NewCipher(key)
	CheckError(err)

	out := make([]byte, len(plaintext))
	c.Encrypt(out, []byte(plaintext))
	return hex.EncodeToString(out)
}

But the issue is that the []bytes key returned from hex.DecodeString() is in unsigned Int where as in Java, the result is in signed Int. And obviously, the encrypted text results are also different, even though every input is same.

huangapple
  • 本文由 发表于 2022年9月5日 21:36:58
  • 转载请务必保留本文链接:https://java.coder-hub.com/73610262.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定