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

AES加密解密

程序员文章站 2022-06-05 09:00:51
...

 

 1、生成秘钥

private static SecretKeySpec getKey(String key) {
        //指定秘钥生成算法
        byte[] arrBTmp = key.getBytes();
        // 创建一个空的16位字节数组(默认值为0)
        //TODO 秘钥只能是16位或32位,有待处理
        byte[] arrB = new byte[16];
        for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
            arrB[i] = arrBTmp[i];
        }
        SecretKeySpec secretKey = new SecretKeySpec(arrB, "AES");
        return secretKey;
    }

 2、加密

private static String encrypt(String content , SecretKeySpec secretKey) {
        try {
            //实例化密码器AES算法
            Cipher cipher = Cipher.getInstance("AES");
            //初始化密码器类型-加密类型
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            //明文字节长度 length/16=n,如果不是整除的 n=n+1
            byte [] byte_encode = content.getBytes("utf-8");
            //密文字节长度是16*n
            byte [] byte_aes = cipher.doFinal(byte_encode);
            //密文字节数组转字符串
            String aes_encode = new BASE64Encoder().encode(byte_aes);
            return aes_encode;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }
        return null;
    }

 3、解密

private static String decrypt(String encryptText,SecretKeySpec secretKey) {
        try {
            //实例化密码器AES算法
            Cipher cipher=Cipher.getInstance("AES");
            //初始化密码器类型-解密类型
            cipher.init(Cipher.DECRYPT_MODE,secretKey);
            //密文转字节数组
            byte[] byte_decode = new BASE64Decoder().decodeBuffer(encryptText);
            //解密
            byte[] byte_aes = cipher.doFinal(byte_decode);
            //还原明文字符串
            String plainText = new String(byte_aes,"utf-8");
            return plainText;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }
        return null;
    }

 

相关标签: 对称加密

上一篇: SHA256Utils

下一篇: 多播委托