EDS的加密解密

Spring Boot实现EDS的加密解密

长话短说,短话就不说了,直接走流程。

加密方法

 private static final byte[] DES_KEY = { 21, 1, -110, 82, -32, -85,
    -128, -65 };
        @SuppressWarnings("restriction")
        public static String encryptBasedDes(String data) {
            String encryptedData = null;
            try {
                // DES算法要求有一个可信任的随机数源
                SecureRandom sr = new SecureRandom();
                DESKeySpec deskey = new DESKeySpec(DES_KEY);`在这里插入代码片`
                // 创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象
                SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
                SecretKey key = keyFactory.generateSecret(deskey);
                // 加密对象
                Cipher cipher = Cipher.getInstance("DES");
                cipher.init(Cipher.ENCRYPT_MODE, key, sr);
                // 加密,并把字节数组编码成字符串
                encryptedData = new sun.misc.BASE64Encoder().encode(cipher.doFinal(data.getBytes()));
            } catch (Exception e) {
                // log.error("加密错误,错误信息:", e);
                throw new RuntimeException("加密错误,错误信息:", e);
            }
            return encryptedData;
        }

解密方法

@SuppressWarnings("restriction")
    public static String decryptBasedDes(String cryptData) {
        String decryptedData = null;
        try {
            // DES算法要求有一个可信任的随机数源
            SecureRandom sr = new SecureRandom();
            DESKeySpec deskey = new DESKeySpec(DES_KEY);
            // 创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(deskey);
            // 解密对象
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, key, sr);
            // 把字符串进行解码,解码为为字节数组,并解密
            decryptedData = new String(cipher.doFinal(new sun.misc.BASE64Decoder().decodeBuffer(cryptData)));
        } catch (Exception e) {
            throw new RuntimeException("解密错误,错误信息:", e);
        }
        return decryptedData;
    }

在需要用到加密解密的地方调用方法即可

放弃不难,但坚持一定很酷!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值