JAVA RSA加解密和数字签名、DES加解密 在项目中的实际使用

RSA:
1、生成随机秘钥对
2、用公钥加密私钥解密 

客户端:RSA用公钥加密之后,需要对加密后的数据在进行Base64加密, 以便在HTTP协议之间传输(兼容各语言的差异性)。
服务端:以JAVA端为列,接受到数据流(InputStream)之后,将流转化为字符串,先用Base64解密,将解密后的结果,在用RSA的私钥解密。
PS:公钥保存在客户端,私钥保存在服务器端。

如果需要加解密的,采用公钥加密,私钥解密的流程。

私钥加密,一般用来做数字签名,然后用公钥来验证改数字签名。

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. import java.io.BufferedReader;   
  2. import java.io.BufferedWriter;   
  3. import java.io.FileReader;   
  4. import java.io.FileWriter;   
  5. import java.io.IOException;   
  6. import java.security.InvalidKeyException;   
  7. import java.security.KeyFactory;   
  8. import java.security.KeyPair;   
  9. import java.security.KeyPairGenerator;   
  10. import java.security.NoSuchAlgorithmException;   
  11. import java.security.SecureRandom;   
  12.    
  13. import java.security.interfaces.RSAPrivateKey;   
  14. import java.security.interfaces.RSAPublicKey;   
  15. import java.security.spec.InvalidKeySpecException;   
  16. import java.security.spec.PKCS8EncodedKeySpec;   
  17. import java.security.spec.X509EncodedKeySpec;   
  18.    
  19. import javax.crypto.BadPaddingException;   
  20. import javax.crypto.Cipher;   
  21. import javax.crypto.IllegalBlockSizeException;   
  22. import javax.crypto.NoSuchPaddingException;   
  23.   
  24. import sun.misc.BASE64Decoder;  
  25. import sun.misc.BASE64Encoder;  
  26.   
  27.    
  28.    
  29. public class RSAEncrypt {   
  30.     /** 
  31.      * 字节数据转字符串专用集合 
  32.      */   
  33.     private static final char[] HEX_CHAR = { '0''1''2''3''4''5''6',   
  34.             '7''8''9''a''b''c''d''e''f' };   
  35.    
  36.     /** 
  37.      * 随机生成密钥对 
  38.      */   
  39.     public static void genKeyPair(String filePath) {   
  40.         // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象   
  41.         KeyPairGenerator keyPairGen = null;   
  42.         try {   
  43.             keyPairGen = KeyPairGenerator.getInstance("RSA");   
  44.         } catch (NoSuchAlgorithmException e) {   
  45.             // TODO Auto-generated catch block   
  46.             e.printStackTrace();   
  47.         }   
  48.         // 初始化密钥对生成器,密钥大小为96-1024位   
  49.         keyPairGen.initialize(1024,new SecureRandom());   
  50.         // 生成一个密钥对,保存在keyPair中   
  51.         KeyPair keyPair = keyPairGen.generateKeyPair();   
  52.         // 得到私钥   
  53.         RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   
  54.         // 得到公钥   
  55.         RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();   
  56.         try {   
  57.             // 得到公钥字符串   
  58.             String publicKeyString = new String(encryptBASE64(publicKey.getEncoded()));   
  59.             // 得到私钥字符串   
  60.             String privateKeyString =new String(encryptBASE64(privateKey.getEncoded()));   
  61.             // 将密钥对写入到文件   
  62.             FileWriter pubfw = new FileWriter(filePath + "/publicKey.keystore");   
  63.             FileWriter prifw = new FileWriter(filePath + "/privateKey.keystore");   
  64.             BufferedWriter pubbw = new BufferedWriter(pubfw);   
  65.             BufferedWriter pribw = new BufferedWriter(prifw);   
  66.             pubbw.write(publicKeyString);   
  67.             pribw.write(privateKeyString);   
  68.             pubbw.flush();   
  69.             pubbw.close();   
  70.             pubfw.close();   
  71.             pribw.flush();   
  72.             pribw.close();   
  73.             prifw.close();   
  74.         } catch (Exception e) {   
  75.             e.printStackTrace();   
  76.         }   
  77.     }   
  78.    
  79.     /** 
  80.      * 从文件中输入流中加载公钥 
  81.      *  
  82.      * @param in 
  83.      *            公钥输入流 
  84.      * @throws Exception 
  85.      *             加载公钥时产生的异常 
  86.      */   
  87.     public static String loadPublicKeyByFile(String path) throws Exception {   
  88.         try {   
  89.             BufferedReader br = new BufferedReader(new FileReader(path   
  90.                     + "/publicKey.keystore"));   
  91.             String readLine = null;   
  92.             StringBuilder sb = new StringBuilder();   
  93.             while ((readLine = br.readLine()) != null) {   
  94.                 sb.append(readLine);   
  95.             }   
  96.             br.close();   
  97.             return sb.toString();   
  98.         } catch (IOException e) {   
  99.             throw new Exception("公钥数据流读取错误");   
  100.         } catch (NullPointerException e) {   
  101.             throw new Exception("公钥输入流为空");   
  102.         }   
  103.     }   
  104.    
  105.     /** 
  106.      * 从字符串中加载公钥 
  107.      *  
  108.      * @param publicKeyStr 
  109.      *            公钥数据字符串 
  110.      * @throws Exception 
  111.      *             加载公钥时产生的异常 
  112.      */   
  113.     public static RSAPublicKey loadPublicKeyByStr(String publicKeyStr)   
  114.             throws Exception {   
  115.         try {   
  116.             byte[] buffer = decryptBASE64(publicKeyStr);   
  117.             KeyFactory keyFactory = KeyFactory.getInstance("RSA");   
  118.             X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);   
  119.             return (RSAPublicKey) keyFactory.generatePublic(keySpec);   
  120.         } catch (NoSuchAlgorithmException e) {   
  121.             throw new Exception("无此算法");   
  122.         } catch (InvalidKeySpecException e) {   
  123.             throw new Exception("公钥非法");   
  124.         } catch (NullPointerException e) {   
  125.             throw new Exception("公钥数据为空");   
  126.         }   
  127.     }   
  128.    
  129.     /** 
  130.      * 从文件中加载私钥 
  131.      *  
  132.      * @param keyFileName 
  133.      *            私钥文件名 
  134.      * @return 是否成功 
  135.      * @throws Exception 
  136.      */   
  137.     public static String loadPrivateKeyByFile(String path) throws Exception {   
  138.         try {   
  139.             BufferedReader br = new BufferedReader(new FileReader(path   
  140.                     + "/privateKey.keystore"));   
  141.             String readLine = null;   
  142.             StringBuilder sb = new StringBuilder();   
  143.             while ((readLine = br.readLine()) != null) {   
  144.                 sb.append(readLine);   
  145.             }   
  146.             br.close();   
  147.             return sb.toString();   
  148.         } catch (IOException e) {   
  149.             throw new Exception("私钥数据读取错误");   
  150.         } catch (NullPointerException e) {   
  151.             throw new Exception("私钥输入流为空");   
  152.         }   
  153.     }   
  154.    
  155.     public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr)   
  156.             throws Exception {   
  157.         try {   
  158.             byte[] buffer = decryptBASE64(privateKeyStr);   
  159.             PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);   
  160.             KeyFactory keyFactory = KeyFactory.getInstance("RSA");   
  161.             return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);   
  162.         } catch (NoSuchAlgorithmException e) {   
  163.             throw new Exception("无此算法");   
  164.         } catch (InvalidKeySpecException e) {   
  165.             throw new Exception("私钥非法");   
  166.         } catch (NullPointerException e) {   
  167.             throw new Exception("私钥数据为空");   
  168.         }   
  169.     }   
  170.    
  171.     /** 
  172.      * 公钥加密过程 
  173.      *  
  174.      * @param publicKey 
  175.      *            公钥 
  176.      * @param plainTextData 
  177.      *            明文数据 
  178.      * @return 
  179.      * @throws Exception 
  180.      *             加密过程中的异常信息 
  181.      */   
  182.     public static byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData)   
  183.             throws Exception {   
  184.         if (publicKey == null) {   
  185.             throw new Exception("加密公钥为空, 请设置");   
  186.         }   
  187.         Cipher cipher = null;   
  188.         try {   
  189.             // 使用默认RSA   
  190.             cipher = Cipher.getInstance("RSA");   
  191.             // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());   
  192.             cipher.init(Cipher.ENCRYPT_MODE, publicKey);   
  193.             byte[] output = cipher.doFinal(plainTextData);   
  194.             return output;   
  195.         } catch (NoSuchAlgorithmException e) {   
  196.             throw new Exception("无此加密算法");   
  197.         } catch (NoSuchPaddingException e) {   
  198.             e.printStackTrace();   
  199.             return null;   
  200.         } catch (InvalidKeyException e) {   
  201.             throw new Exception("加密公钥非法,请检查");   
  202.         } catch (IllegalBlockSizeException e) {   
  203.             throw new Exception("明文长度非法");   
  204.         } catch (BadPaddingException e) {   
  205.             throw new Exception("明文数据已损坏");   
  206.         }   
  207.     }   
  208.    
  209.     /** 
  210.      * 私钥加密过程 
  211.      *  
  212.      * @param privateKey 
  213.      *            私钥 
  214.      * @param plainTextData 
  215.      *            明文数据 
  216.      * @return 
  217.      * @throws Exception 
  218.      *             加密过程中的异常信息 
  219.      */   
  220.     public static byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData)   
  221.             throws Exception {   
  222.         if (privateKey == null) {   
  223.             throw new Exception("加密私钥为空, 请设置");   
  224.         }   
  225.         Cipher cipher = null;   
  226.         try {   
  227.             // 使用默认RSA   
  228.             cipher = Cipher.getInstance("RSA");   
  229.             cipher.init(Cipher.ENCRYPT_MODE, privateKey);   
  230.             byte[] output = cipher.doFinal(plainTextData);   
  231.             return output;   
  232.         } catch (NoSuchAlgorithmException e) {   
  233.             throw new Exception("无此加密算法");   
  234.         } catch (NoSuchPaddingException e) {   
  235.             e.printStackTrace();   
  236.             return null;   
  237.         } catch (InvalidKeyException e) {   
  238.             throw new Exception("加密私钥非法,请检查");   
  239.         } catch (IllegalBlockSizeException e) {   
  240.             throw new Exception("明文长度非法");   
  241.         } catch (BadPaddingException e) {   
  242.             throw new Exception("明文数据已损坏");   
  243.         }   
  244.     }   
  245.    
  246.     /** 
  247.      * 私钥解密过程 
  248.      *  
  249.      * @param privateKey 
  250.      *            私钥 
  251.      * @param cipherData 
  252.      *            密文数据 
  253.      * @return 明文 
  254.      * @throws Exception 
  255.      *             解密过程中的异常信息 
  256.      */   
  257.     public static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData)   
  258.             throws Exception {   
  259.         if (privateKey == null) {   
  260.             throw new Exception("解密私钥为空, 请设置");   
  261.         }   
  262.         Cipher cipher = null;   
  263.         try {   
  264.             // 使用默认RSA   
  265.             cipher = Cipher.getInstance("RSA");   
  266.             // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());   
  267.             cipher.init(Cipher.DECRYPT_MODE, privateKey);   
  268.             byte[] output = cipher.doFinal(cipherData);   
  269.             return output;   
  270.         } catch (NoSuchAlgorithmException e) {   
  271.             throw new Exception("无此解密算法");   
  272.         } catch (NoSuchPaddingException e) {   
  273.             e.printStackTrace();   
  274.             return null;   
  275.         } catch (InvalidKeyException e) {   
  276.             throw new Exception("解密私钥非法,请检查");   
  277.         } catch (IllegalBlockSizeException e) {   
  278.             throw new Exception("密文长度非法");   
  279.         } catch (BadPaddingException e) {   
  280.             throw new Exception("密文数据已损坏");   
  281.         }   
  282.     }   
  283.    
  284.     /** 
  285.      * 公钥解密过程 
  286.      *  
  287.      * @param publicKey 
  288.      *            公钥 
  289.      * @param cipherData 
  290.      *            密文数据 
  291.      * @return 明文 
  292.      * @throws Exception 
  293.      *             解密过程中的异常信息 
  294.      */   
  295.     public static byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData)   
  296.             throws Exception {   
  297.         if (publicKey == null) {   
  298.             throw new Exception("解密公钥为空, 请设置");   
  299.         }   
  300.         Cipher cipher = null;   
  301.         try {   
  302.             // 使用默认RSA   
  303.             cipher = Cipher.getInstance("RSA");   
  304.             // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());   
  305.             cipher.init(Cipher.DECRYPT_MODE, publicKey);   
  306.             byte[] output = cipher.doFinal(cipherData);   
  307.             return output;   
  308.         } catch (NoSuchAlgorithmException e) {   
  309.             throw new Exception("无此解密算法");   
  310.         } catch (NoSuchPaddingException e) {   
  311.             e.printStackTrace();   
  312.             return null;   
  313.         } catch (InvalidKeyException e) {   
  314.             throw new Exception("解密公钥非法,请检查");   
  315.         } catch (IllegalBlockSizeException e) {   
  316.             throw new Exception("密文长度非法");   
  317.         } catch (BadPaddingException e) {   
  318.             throw new Exception("密文数据已损坏");   
  319.         }   
  320.     }   
  321.    
  322.     /** 
  323.      * 字节数据转十六进制字符串 
  324.      *  
  325.      * @param data 
  326.      *            输入数据 
  327.      * @return 十六进制内容 
  328.      */   
  329.     public static String byteArrayToString(byte[] data) {   
  330.         StringBuilder stringBuilder = new StringBuilder();   
  331.         for (int i = 0; i < data.length; i++) {   
  332.             // 取出字节的高四位 作为索引得到相应的十六进制标识符 注意无符号右移   
  333.             stringBuilder.append(HEX_CHAR[(data[i] & 0xf0) >>> 4]);   
  334.             // 取出字节的低四位 作为索引得到相应的十六进制标识符   
  335.             stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]);   
  336.             if (i < data.length - 1) {   
  337.                 stringBuilder.append(' ');   
  338.             }   
  339.         }   
  340.         return stringBuilder.toString();   
  341.     }   
  342.      
  343.      public static String encryptBASE64(byte[] key) throws Exception {  
  344.           return (new BASE64Encoder()).encodeBuffer(key);  
  345.      }  
  346.      public static byte[] decryptBASE64(String key) throws Exception {  
  347.           return (new BASE64Decoder()).decodeBuffer(key);  
  348.      }  
  349.   
  350. }    

上面代码中,利用 genKeyPair ()方法来生成钥匙对。
加密: RSAEncrypt. encryptBASE64 (RSAEncrypt. encrypt (RSAEncrypt. loadPublicKeyByStr (RSAEncrypt. loadPublicKeyByFile (filepath)),"要加密的字符串".getBytes()))
解密: RSAEncrypt. decrypt (RSAEncrypt. loadPrivateKeyByStr (RSAEncrypt. loadPrivateKeyByFile (filepath)), RSAEncrypt. decryptBASE64 ("要解密的字符串"))


下面用 私钥加密(数字签名),用公钥进行验证
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1.         System. out.println( "---------------私钥签名过程------------------" );   
  2.         String content= "ihep_这是用于签名的原始数据" ;   
  3.         String signstr=RSASignature.encryptBASE64(RSASignature. sign(content,RSAEncrypt.loadPrivateKeyByFile(filepath)));   
  4.         System. out.println( "签名原串:" +content);   
  5.         System. out.println( "签名串:"+signstr);   
  6.         System. out.println();   
  7. //           
  8.         System. out.println( "---------------公钥校验签名------------------" );   
  9.         System. out.println( "签名原串:" +content);   
  10.         System. out.println( "签名串:"+signstr);   
  11.            
  12.         System. out. println("验签结果:"+RSASignature. doCheck(content, signstr, RSAEncrypt.loadPublicKeyByFile(filepath)));  

输出结果:



附上签名的class:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1.    
  2. import java.security.KeyFactory;   
  3. import java.security.PrivateKey;   
  4. import java.security.PublicKey;   
  5. import java.security.spec.PKCS8EncodedKeySpec;   
  6. import java.security.spec.X509EncodedKeySpec;   
  7.   
  8.   
  9. import sun.misc.BASE64Decoder;  
  10. import sun.misc.BASE64Encoder;  
  11.    
  12.    
  13.    
  14. /** 
  15. * RSA签名验签类 
  16. */   
  17. public class RSASignature{   
  18.        
  19.     /** 
  20.      * 签名算法 
  21.      */   
  22.     public static final String SIGN_ALGORITHMS = "SHA1WithRSA";   
  23. //    public static final String SIGN_ALGORITHMS = "sha1WithRSAEncryption";   
  24.    
  25.     /** 
  26.     * RSA签名 
  27.     * @param content 待签名数据 
  28.     * @param privateKey 商户私钥 
  29.     * @param encode 字符集编码 
  30.     * @return 签名值 
  31.     */   
  32.     public static String sign(String content, String privateKey, String encode)   
  33.     {   
  34.         try    
  35.         {   
  36.             PKCS8EncodedKeySpec priPKCS8    = new PKCS8EncodedKeySpec(decryptBASE64(privateKey) );    
  37.                
  38.             KeyFactory keyf                 = KeyFactory.getInstance("RSA");   
  39.             PrivateKey priKey               = keyf.generatePrivate(priPKCS8);   
  40.    
  41.             java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);   
  42.    
  43.             signature.initSign(priKey);   
  44.             signature.update( content.getBytes(encode));   
  45.    
  46.             byte[] signed = signature.sign();   
  47.                
  48.             return new String( encryptBASE64(signed));   
  49.         }   
  50.         catch (Exception e)    
  51.         {   
  52.             e.printStackTrace();   
  53.         }   
  54.            
  55.         return null;   
  56.     }   
  57.        
  58.     public static byte[] sign(String content, String privateKey)   
  59.     {   
  60.         try    
  61.         {   
  62.             PKCS8EncodedKeySpec priPKCS8    = new PKCS8EncodedKeySpec( decryptBASE64(privateKey) );    
  63.             KeyFactory keyf = KeyFactory.getInstance("RSA");   
  64.             PrivateKey priKey = keyf.generatePrivate(priPKCS8);   
  65.             java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);   
  66.             signature.initSign(priKey);   
  67.             signature.update( content.getBytes());   
  68.             byte[] signed = signature.sign();   
  69.             return signed;   
  70.         }   
  71.         catch (Exception e)    
  72.         {   
  73.             e.printStackTrace();   
  74.         }   
  75.         return null;   
  76.     }   
  77.        
  78.     /** 
  79.     * RSA验签名检查 
  80.     * @param content 待签名数据 
  81.     * @param sign 签名值 
  82.     * @param publicKey 分配给开发商公钥 
  83.     * @param encode 字符集编码 
  84.     * @return 布尔值 
  85.     */   
  86.     public static boolean doCheck(String content, String sign, String publicKey,String encode)   
  87.     {   
  88.         try    
  89.         {   
  90.             KeyFactory keyFactory = KeyFactory.getInstance("RSA");   
  91.             byte[] encodedKey =decryptBASE64(publicKey);   
  92.             PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));   
  93.    
  94.            
  95.             java.security.Signature signature = java.security.Signature   
  96.             .getInstance(SIGN_ALGORITHMS);   
  97.            
  98.             signature.initVerify(pubKey);   
  99.             signature.update( content.getBytes(encode) );   
  100.            
  101.             boolean bverify = signature.verify( decryptBASE64(sign) );   
  102.             return bverify;   
  103.                
  104.         }    
  105.         catch (Exception e)    
  106.         {   
  107.             e.printStackTrace();   
  108.         }   
  109.            
  110.         return false;   
  111.     }   
  112.        
  113.     public static boolean doCheck(String content, String sign, String publicKey)   
  114.     {   
  115.         try    
  116.         {   
  117.             KeyFactory keyFactory = KeyFactory.getInstance("RSA");   
  118.             byte[] encodedKey =decryptBASE64(publicKey);   
  119.             PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));   
  120.    
  121.            
  122.             java.security.Signature signature = java.security.Signature   
  123.             .getInstance(SIGN_ALGORITHMS);   
  124.            
  125.             signature.initVerify(pubKey);   
  126.             signature.update( content.getBytes() );   
  127.            
  128.             boolean bverify = signature.verify(decryptBASE64(sign) );   
  129.             return bverify;   
  130.                
  131.         }    
  132.         catch (Exception e)    
  133.         {   
  134.             e.printStackTrace();   
  135.         }   
  136.            
  137.         return false;   
  138.     }   
  139.      public static String encryptBASE64(byte[] key) throws Exception {  
  140.           return (new BASE64Encoder()).encodeBuffer(key);  
  141.      }  
  142.      public static byte[] decryptBASE64(String key) throws Exception {  
  143.           return (new BASE64Decoder()).decodeBuffer(key);  
  144.      }  
  145.       
  146. }   


DES加解密:
1、客户端:首先进行DES加密,再将加密后的结果进行BASE64加密。
2、服务端:将得到的流转化为字符串,在进行BASE64解密, 将解密之后的结果再进行DES解密。
DES加解密的KEY必须一致!

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package des;  
  2.   
  3. import java.net.URLDecoder;  
  4. import java.net.URLEncoder;  
  5. import java.security.SecureRandom;  
  6.   
  7. import javax.crypto.Cipher;  
  8. import javax.crypto.SecretKey;  
  9. import javax.crypto.SecretKeyFactory;  
  10. import javax.crypto.spec.DESKeySpec;  
  11.   
  12. import com.alibaba.fastjson.JSONObject;  
  13.   
  14. import sun.misc.BASE64Decoder;  
  15. import sun.misc.BASE64Encoder;  
  16.   
  17. public class EncryptUtil {  
  18.       
  19.      public static final String DES_KEY="@Wx^t)V#";  
  20.   
  21.      /** 
  22.      * 
  23.      * 解密 
  24.      * 
  25.      * @param src 
  26.      *            数据源 
  27.      * @param key 
  28.      *            密钥,长度必须是8的倍数 
  29.      * @return 返回解密后的原始数据 
  30.      * @throws Exception 
  31.      */  
  32.      public static byte[] decrypt(byte[] src, byte[] key) throws Exception {  
  33.           // DES算法要求有一个可信任的随机数源  
  34.           SecureRandom sr = new SecureRandom();  
  35.           // 从原始密匙数据创建一个DESKeySpec对象  
  36.           DESKeySpec dks = new DESKeySpec(key);  
  37.           // 创建一个密匙工厂,然后用它把DESKeySpec对象转换成  
  38.           // 一个SecretKey对象  
  39.           SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");  
  40.           SecretKey securekey = keyFactory.generateSecret(dks);  
  41.           // Cipher对象实际完成解密操作  
  42.           Cipher cipher = Cipher.getInstance("DES");  
  43.           // 用密匙初始化Cipher对象  
  44.           cipher.init(Cipher.DECRYPT_MODE, securekey, sr);  
  45.           // 现在,获取数据并解密  
  46.           // 正式执行解密操作  
  47.           return cipher.doFinal(src);  
  48.      }  
  49.   
  50.      /** 
  51.      * 
  52.      * 加密 
  53.      * 
  54.      * @param src 
  55.      *            数据源 
  56.      * 
  57.      * @param key 
  58.      *            密钥,长度必须是8的倍数 
  59.      * 
  60.      * @return 返回加密后的数据 
  61.      * 
  62.      * @throws Exception 
  63.      * 
  64.      */  
  65.      public static byte[] encrypt(byte[] src, byte[] key) throws Exception {  
  66.           // DES算法要求有一个可信任的随机数源  
  67.           SecureRandom sr = new SecureRandom();  
  68.           // 从原始密匙数据创建DESKeySpec对象  
  69.           DESKeySpec dks = new DESKeySpec(key);  
  70.           // 创建一个密匙工厂,然后用它把DESKeySpec转换成  
  71.           // 一个SecretKey对象  
  72.           SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");  
  73.           SecretKey securekey = keyFactory.generateSecret(dks);  
  74.           // Cipher对象实际完成加密操作  
  75.           Cipher cipher = Cipher.getInstance("DES");  
  76.           // 用密匙初始化Cipher对象  
  77.           cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);  
  78.           // 现在,获取数据并加密  
  79.           // 正式执行加密操作  
  80.           return cipher.doFinal(src);  
  81.      }  
  82.      public static String encryptBASE64(byte[] key) throws Exception {  
  83.           return (new BASE64Encoder()).encodeBuffer(key);  
  84.      }  
  85.      public static byte[] decryptBASE64(String key) throws Exception {  
  86.           return (new BASE64Decoder()).decodeBuffer(key);  
  87.      }  
  88.       
  89.      @SuppressWarnings("deprecation")  
  90.      public static void main(String[] args) throws Exception {  
  91.           JSONObject obj= new JSONObject();  
  92.           obj.put("name""张三");  
  93.           System.out.println("加密前的数据:"+obj.toString());  
  94.           System.out.println("DES开始加密......");  
  95.            
  96.           String enData=encryptBASE64(encrypt(obj.toString().getBytes(), DES_KEY.getBytes()));  
  97.           System.out.println("加密后的数据"+enData);  
  98.            
  99.           System.out.println("DES开始解密.....");  
  100.           String deData=new String(decrypt(decryptBASE64(enData), DES_KEY.getBytes()));  
  101.           System.out.println("DES解密后的数据:"+deData);  
  102.      }  
  103. }  

输入结果:
加密前的数据:{"name":"张三"}
DES开始加密......
加密后的数据cOOCD8/CXRmjaBYA5K7KYA==

DES开始解密.....
DES解密后的数据:{"name":"张三"}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值