AES秘钥加密解密方式

一、首先是生成一个秘钥,可以使固定死的一个秘钥也可以每次随机生成

public final static byte[] getKey(){
        byte[] keyBytes = null;
        //生成Key
        try {
            KeyGenerator keyGenerator = null;
            keyGenerator = KeyGenerator.getInstance("AES");
            //随机生成秘钥
            //keyGenerator.init(128);       
            //生成固定的秘钥
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");   
            random.setSeed("123456798".getBytes());
            keyGenerator.init(128, random);
            SecretKey secretKey = keyGenerator.generateKey();
            keyBytes = secretKey.getEncoded();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return keyBytes;
    }

二、加密方法

public static String checkAES(String value){    //value是你需要加密的字符串
    //调用生成秘钥方法
    Key key = new SecretKeySpec(ToolUtils.getKey(), "AES");
    //加密
    Cipher cipher = null;
    byte[] encodeResult = null;
    try {
        cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        encodeResult = cipher.doFinal(value.getBytes());
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }
    return Hex.encodeHexString(encodeResult);
}

三、解密方式

public static String getAES(String value){           //value是需要解密的字符串
        //调用key的生成方法
        Key key = new SecretKeySpec(ToolUtils.getKey(), "AES");
        //解密
        Cipher cipher = null;
        byte[] decodeResult = null;
        try {
            cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key);
            //byte[] test = value.getBytes();
            byte[] test = Hex.decodeHex(token);
            decodeResult = cipher.doFinal(test);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (DecoderException e) {
            e.printStackTrace();
        }
        return (new String (decodeResult));
    }

注:这些可以分装起来,直接调用,不用谢我,我叫雷锋

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值