gpt4 book ai didi

java - Java 中的 AES-128 加密

转载 作者:行者123 更新时间:2023-11-30 01:59:52 25 4
gpt4 key购买 nike

我尝试使用以字节为单位的 key 加密一些以字节为单位的明文。但是,我得到的输出并不是我所期望的。

public class AES {


public static byte[] encrypt(byte[] plainText, byte[] key) {
try {
Cipher cipher = Cipher.getInstance("AES");
SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] cipherText = cipher.doFinal(plainText);
return cipherText;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

public static String byteToHex(byte[] hash) {

StringBuilder sb = new StringBuilder(hash.length * 2);
for (byte b : hash) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}


public static void main(String args[]) {

byte plaintext[] = {0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x58,0x63,(byte)0xaa,(byte)0xbb,(byte)0xcc,(byte)0xdd,(byte)0xee,(byte)0xff};
byte key[] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f};


byte[] encrypted = encrypt(plaintext, key);
System.out.println("Encrypted String : " + byteToHex(encrypted));

}
}

我得到的输出是:814064943fe05668da1f3d2269a4ee22954f64f2e4e86e9eee82d20216684899,而我期待69c4e0d86a7b0430d8cdb78070b4c55a。我正在使用 here 中的明文和 key

最佳答案

您的代码中有两处不正确。

  1. 您使用 PKCS5 填充,而原始示例未使用任何填充。

  2. 您错误地复制了纯文本。

所以:

Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");

...

byte plaintext[] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88,
(byte) 0x99, (byte) 0xaa, (byte) 0xbb, (byte) 0xcc, (byte) 0xdd, (byte) 0xee, (byte) 0xff };

结果:

Encrypted String : 69c4e0d86a7b0430d8cdb78070b4c55a

关于java - Java 中的 AES-128 加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53234103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com