欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

AES 对称加密 (JDK)

程序员文章站 2022-05-15 16:59:49
...

AES 对称加密 (JDK)

        /**
         * AES 加密 解密
         */

        //key生成
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        //长度有 64 112 128 192 256
        keyGenerator.init(256);
        SecretKey secretKey = keyGenerator.generateKey();
        byte[] encoded = secretKey.getEncoded();

        //key转换
        SecretKeySpec keySpec = new SecretKeySpec(encoded, "AES");

        //加密
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        byte[] bytes = cipher.doFinal("加密字符串".getBytes());
        System.out.println(Base64.encodeBase64String(bytes));

        //解密
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        bytes = cipher.doFinal(bytes);
        System.out.println(new String(bytes));