Java使用AES加密和解密

前言:

高级加密标准(英语:Advanced Encryption Standard,缩写:AES),是一种区块加密标准。这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。

AES的基本要求是,采用对称分组密码体制,密钥长度的最少支持为128、192、256,分组长度128位,算法应易于各种硬件和软件实现。1998年NIST开始AES第一轮分析、测试和征集,共产生了15个候选算法。1999年3月完成了第二轮AES2的分析、测试。2000年10月2日美国政府正式宣布选中比利时密码学家Joan Daemen 和 Vincent Rijmen 提出的一种密码算法RIJNDAEL 作为 AES.

那么为什么原来的DES会被取代呢,,原因就在于其使用56位密钥,比较容易被破解。而AES可以使用128、192、和256位密钥,并且用128位分组加密和解密数据,相对来说安全很多。完善的加密算法在理论上是无法破解的,除非使用穷尽法。使用穷尽法破解密钥长度在128位以上的加密数据是不现实的,仅存在理论上的可能性。统计显示,即使使用目前世界上运算速度最快的计算机,穷尽128位密钥也要花上几十亿年的时间,更不用说去破解采用256位密钥长度的AES算法了。

 

正文:

AES加密

 /**
     * @Author with-her
     * @Date 2018/9/5 11:11
     * @Param [content, password]
     * @return byte[]
     * @Description:  AES加密字符串
     **/
    public static byte[] Encrypt(String content, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");// 创建AES的Key生产者
            kgen.init(128, new SecureRandom(password.getBytes()));// 利用用户密码作为随机数初始化出 128位的key生产者
                                                                     //SecureRandom是生成安全随机数序列,password.getBytes()是种子,只要种子相同,序列就一样,所以解密只要有password就行
            SecretKey secretKey = kgen.generateKey();// 根据用户密码,生成一个密钥
            byte[] enCodeFormat = secretKey.getEncoded();// 返回基本编码格式的密钥,如果此密钥不支持编码,则返回null
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");// 转换为AES专用密钥

            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化为加密模式的密码器
            byte[] result = cipher.doFinal(byteContent);// 加密

            return result;

        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

AES解密:

 /**
     * @Author with-her
     * @Date 2018/9/5 11:37
     * @Param [content, password]
     * @return byte[]
     * @Description: 解密
     **/
    public static byte[] decrypt(byte[] content, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");// 创建AES的Key生产者
            kgen.init(128, new SecureRandom(password.getBytes()));
            SecretKey secretKey = kgen.generateKey();// 根据用户密码,生成一个密钥
            byte[] enCodeFormat = secretKey.getEncoded();// 返回基本编码格式的密钥
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");// 转换为AES专用密钥

            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, key);// 初始化为解密模式的密码器
            byte[] result = cipher.doFinal(content);
            return result; // 明文

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

测试:

 public static void main(String[] args) {
        String content = "美女,约吗?";
        String password = "123";
        System.out.println("加密之前:" + content);

        // 加密
        byte[] encrypt = AesTest.encrypt(content, password);
        System.out.println("加密后的内容:" + new String(encrypt));
        
        // 解密
        byte[] decrypt = AesTest.decrypt(encrypt, password);
        System.out.println("解密后的内容:" + new String(decrypt));        
    }

结果:

加密之前:美女,约吗?
加密后的内容:P�d�g�K�3�g�����,Ꝏ?U納�
解密后的内容:美女,约吗?

可见,如果直接输出加密后的内容是一个乱码。我们需要把它的进制转换一下。

进制转换:

 /**
     * @Author with-her
     * @Date 2018/9/5 0005 14:39
     * @Param buf
     * @return String
     * @Description: 将二进制转换成16进制
     **/
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * @Author with-her
     * @Date 2018/9/5 0005 14:38
     * @Param hexStr
     * @return byte[]
     * @Description: 将16进制转换为二进制
     **/
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length()/2];
        for (int i = 0;i< hexStr.length()/2; i++) {
            int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
            int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

再次测试

 public static void main(String[] args) {
        String content = "美女,约吗?";
        String password = "123";
        System.out.println("加密之前:" + content);
        // 加密
        byte[] encrypt = AesTest.encrypt(content, password);
        System.out.println("加密后的内容:" + new String(encrypt));
        
        //如果想要加密内容不显示乱码,可以先将密文转换为16进制
        String hexStrResult = ParseSystemUtil.parseByte2HexStr(encrypt);
        System.out.println("16进制的密文:"  + hexStrResult);
        
        //如果的到的是16进制密文,别忘了先转为2进制再解密
        byte[] twoStrResult = ParseSystemUtil.parseHexStr2Byte(hexStrResult);
                
        // 解密
        byte[] decrypt = AesTest.decrypt(encrypt, password);
        System.out.println("解密后的内容:" + new String(decrypt));    
    }

结果:

加密之前:美女,约吗?
加密后的内容:P�d�g�K�3�g�����,Ꝏ?U納�
16进制的密文:50FE6401E867A34BD533FE67BB85EDABFED62CEA9D8E3F5516E7B48D01F21A5F
解密后的内容:美女,约吗?

报错:

据说有的人只能加密,不能解密,一解密就报错,但我没有遇到

javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:966)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:824)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:436)
at javax.crypto.Cipher.doFinal(Cipher.java:2165)
...

网上搜了一个解决方案,在这写下:

在生成key的时候出现错误的,需要对生成key的代码进行修改。

原代码:

    //解密
    public static byte[] decrypt(byte[] content, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");// 创建AES的Key生产者
            kgen.init(128, new SecureRandom(password.getBytes()));
            SecretKey secretKey = kgen.generateKey();// 根据用户密码,生成一个密钥
            byte[] enCodeFormat = secretKey.getEncoded();// 返回基本编码格式的密钥
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");// 转换为AES专用密钥

            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, key);// 初始化为解密模式的密码器
            byte[] result = cipher.doFinal(content);
            return result; // 明文

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

修改后:

    //解密
    public static byte[] decrypt(byte[] content, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");// 创建AES的Key生产者
            
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(password.getBytes());

            kgen.init(128, random);
            SecretKey secretKey = kgen.generateKey();// 根据用户密码,生成一个密钥
            byte[] enCodeFormat = secretKey.getEncoded();// 返回基本编码格式的密钥
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");// 转换为AES专用密钥

            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, key);// 初始化为解密模式的密码器
            byte[] result = cipher.doFinal(content);
            return result; // 明文

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

是SecureRandom创建的方式不同而引起的错误。如果有遇到这样的问题,不妨试试

 

到此,AES的使用基本完成。欢迎留言交流
参考文档:
https://www.jb51.net/article/118482.htm

https://www.cnblogs.com/vmax-tam/p/4624032.html

http://www.cnblogs.com/zempty/p/4318902.html

https://blog.csdn.net/weixin_40784851/article/details/78405245

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
JavaAES加密解密是一种常用的对称加密算法,它可以将明文加密成密文,并且可以使用相同的密钥进行解密。在Java中,常用的JavaAES加密解密实现方式有两种:一种是基于Java自带的Cipher类实现的,另一种是基于第三方库实现的。 如果使用Java自带的Cipher类,可以按照以下步骤实现JavaAES加密解密: 1. 生成密钥,可以使用KeyGenerator类生成密钥。 2. 创建Cipher对象,设置加密模式和填充方式。 3. 初始化Cipher对象,设置加密或解密模式,以及密钥。 4. 调用Cipher的doFinal方法进行加密或解密操作。 以下是JavaAES加密解密的代码示例: ```java import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import java.nio.charset.StandardCharsets; import java.security.NoSuchAlgorithmException; public class JavaAESTest { public static void main(String[] args) throws Exception { String plaintext = "Hello, World!"; //明文 String password = "123456"; //密钥 //生成密钥 SecretKey secretKey = getSecretKey(password); //加密 byte[] ciphertext = encrypt(plaintext.getBytes(StandardCharsets.UTF_8), secretKey); System.out.println("加密后:" + new String(ciphertext, StandardCharsets.UTF_8)); //解密 byte[] decrypted = decrypt(ciphertext, secretKey); System.out.println("解密后:" + new String(decrypted, StandardCharsets.UTF_8)); } private static SecretKey getSecretKey(String password) throws NoSuchAlgorithmException { //生成AES算法的KeyGenerator对象 KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(128); //指定密钥长度为128位 //生成一个128位的随机安全密钥 return keyGenerator.generateKey(); } private static byte[] encrypt(byte[] plaintext, SecretKey secretKey) throws Exception { //创建Cipher对象,设置加密模式和填充方式 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); //初始化Cipher对象 //加密并返回结果 return cipher.doFinal(plaintext); } private static byte[] decrypt(byte[] ciphertext, SecretKey secretKey) throws Exception { //创建Cipher对象,设置解密模式和填充方式 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKey); //初始化Cipher对象 //解密并返回结果 return cipher.doFinal(ciphertext); } } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值