繁体   English   中英

Java中的AES-128加密

[英]AES-128 encryption in Java

我试图用密钥(以字节为单位)加密一些以字节为单位的纯文本。 但是,我得到的输出不是我期望的。

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 我从这里使用明文和密钥

您的代码中有两件事是不正确的。

  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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM