加密解密算法java实现(2)—DES

来源:互联网 发布:2015中国进口粮食数据 编辑:程序博客网 时间:2024/06/12 20:01

1、maven依赖

<dependency>          <groupId>commons-codec</groupId>          <artifactId>commons-codec</artifactId>          <version>1.9</version>      </dependency> 
2、java代码

/**  * DES加密解密  * 原文相同,密钥相同,DES加密后的密文是一样的  */  public class DESUtil {      /**      * DES算法密钥      * 个数为8的倍数      */      private static final byte[] DES_KEY = {125, -120, 52, 45, 98, -78, 85, -12, 45, -12, 69, 51, 30, -122, 45, -33};      private static final String ALGORITHM_DES = "DES";      private static final String TRANSFORMATION = "DES";            /**      * 加密      * @param source      * @return      * @throws Exception      */      public static String encode(String source) throws Exception {          SecureRandom sr = new SecureRandom();//DES算法要求有一个可信任的随机数源          DESKeySpec desks = new DESKeySpec(DES_KEY);          SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM_DES);//创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象          SecretKey secretKey = factory.generateSecret(desks);          Cipher cipher = Cipher.getInstance(TRANSFORMATION);//加密对象          cipher.init(Cipher.ENCRYPT_MODE, secretKey, sr);          String result = BASE64Util.encodeByte(cipher.doFinal(source.getBytes()));//加密,并把字节数组编码成字符串                    return result;      }            /**      * 解密      * @param source      * @return      * @throws Exception      */      public static String decode(String source) throws Exception {          SecureRandom sr = new SecureRandom();//DES算法要求有一个可信任的随机数源          DESKeySpec desks = new DESKeySpec(DES_KEY);          SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM_DES);//创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象          SecretKey secretKey = factory.generateSecret(desks);          Cipher cipher = Cipher.getInstance(TRANSFORMATION);//解密对象          cipher.init(Cipher.DECRYPT_MODE, secretKey, sr);          String result = new String(cipher.doFinal(BASE64Util.decodeToByte(source)));//把字符串解码为字节数组,并解密          return result;      }            /**      * 示例      * 支持中文 空格 字符      * @param args      * @throws Exception       */      public static void main(String[] args) throws Exception {          String source = "12dfefDKLJKLKL464d中文f465as43f1a3 f46e353D1F34&*^$E65F46EF43456abcd54as56f00ef";          String encodeData = DESUtil.encode(source);//先加密          System.out.println("加密后:\n" + encodeData);          String decodeData = DESUtil.decode(encodeData);//解密          System.out.println("解密后:\n" + decodeData);          System.out.println("解密后是否和原文相同:" + source.equals(decodeData));      }  }