RES加密

来源:互联网 发布:windows正版好处 编辑:程序博客网 时间:2024/04/29 05:38
  1. import Java.security.SecureRandom;  
  2. import javax.crypto.Cipher;  
  3. import javax.crypto.SecretKey;  
  4. import javax.crypto.SecretKeyFactory;  
  5. import javax.crypto.spec.DESKeySpec;  
  6.   
  7. import sun.misc.BASE64Decoder;  
  8. import sun.misc.BASE64Encoder;  
  9.   
  10.   
  11. public class DESHelper {  
  12.     /** 
  13.      * 加密解密接口 
  14.      * @param data      数据 
  15.      * @param password  加密解密密码 必须8位字节 
  16.      * @param flag      加密解密标志 0:加密 ,1:解密 
  17.      * @return 
  18.      */  
  19.     public static String doWork(String data, String password,int flag) {  
  20.         try {  
  21.             SecureRandom random = new SecureRandom();  
  22.             DESKeySpec desKey = new DESKeySpec(password.getBytes());  
  23.             SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");  
  24.             SecretKey securekey = keyFactory.generateSecret(desKey);  
  25.             Cipher cipher = Cipher.getInstance("DES");  
  26.             //   
  27.             if(flag == 0){  
  28.                 BASE64Encoder base64encoder = new BASE64Encoder();  
  29.                 cipher.init(Cipher.ENCRYPT_MODE, securekey, random);  
  30.                 return base64encoder.encode(cipher.doFinal(data.getBytes("UTF-8")));  
  31.             }else{  
  32.                 BASE64Decoder base64decoder = new BASE64Decoder();  
  33.                 byte[] encodeByte = base64decoder.decodeBuffer(data);  
  34.                 cipher.init(Cipher.DECRYPT_MODE, securekey, random);  
  35.                 byte[] decoder = cipher.doFinal(encodeByte);  
  36.                 return new String(decoder,"UTF-8");  
  37.             }  
  38.               
  39.         } catch (Exception e) {  
  40.             e.printStackTrace();  
  41.         }  
  42.         return null;  
  43.     }  
  44.       
  45.     /** 
  46.      * test 
  47.      * @param args 
  48.      */  
  49.     public static void main(String[] args) {  
  50.         try {  
  51.             // 明文  
  52.             String str = "mobile:15810557051|type:0|content:你好";  
  53.             // 密码  
  54.             String password = "01010101";  
  55.             String desc = DESHelper.doWork(str, password,0);  
  56.             System.out.println("密文:" + desc);  
  57.             // 解密  
  58.             str = DESHelper.doWork(desc, password,1);  
  59.             System.out.println("明文:" +str);  
  60.         } catch (Exception e1) {  
  61.             e1.printStackTrace();  
  62.         }  
  63.   
  64.     }  
  65. }  
0 0
原创粉丝点击