美文网首页
DES使用示例代码 java版

DES使用示例代码 java版

作者: 乡村码农 | 来源:发表于2022-01-09 15:03 被阅读0次

    des有点简单 直接上代码

    package com.utils;
    
    import java.security.SecureRandom;
    import java.util.Base64;
    
    import javax.crypto.Cipher;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.DESKeySpec;
    
    public class DesUtils {
    
        private static final String CHARSET = "utf-8";
        
            // 加密方法   data:待加密数据  key:加密密钥
        public static String encrypt(String data, String key) throws Exception {
            byte[] bytes = data.getBytes(CHARSET);
            byte[] encryptData = encrypt(bytes, key);
            return Base64.getEncoder().encodeToString(encryptData);
        }
        // 解密方法 data:待解密数据  key:解密密钥
        public static String decrypt(String data, String key) throws Exception {
            byte[] bytes = Base64.getDecoder().decode(data);
            byte[] decryptData = decrypt(bytes, key);
            return new String(decryptData, CHARSET);
        }
        
        public static byte[] encrypt(byte[] data, String key) throws Exception {
            SecureRandom random = new SecureRandom();
            DESKeySpec desKey = new DESKeySpec(key.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey securekey = keyFactory.generateSecret(desKey);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
            return cipher.doFinal(data);
            
        }
        
        public static byte[] decrypt(byte[] data, String key) throws Exception {
            SecureRandom random = new SecureRandom();
            DESKeySpec desKey = new DESKeySpec(key.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey securekey = keyFactory.generateSecret(desKey);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, securekey, random);
            return cipher.doFinal(data);
        }
        
    }
    
    

    相关文章

      网友评论

          本文标题:DES使用示例代码 java版

          本文链接:https://www.haomeiwen.com/subject/ropucrtx.html