AES加密解密

 

 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;
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值