java对称加解密

来源:互联网 发布:同方知网 知乎 编辑:程序博客网 时间:2024/04/28 23:31
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  *  
  3.  */  
  4. package security;  
  5.   
  6. import java.io.File;  
  7. import java.io.FileInputStream;  
  8. import java.io.FileOutputStream;  
  9. import java.io.IOException;  
  10. import java.io.InputStream;  
  11. import java.io.OutputStream;  
  12. import java.io.UnsupportedEncodingException;  
  13. import java.math.BigInteger;  
  14. import java.security.InvalidKeyException;  
  15. import java.security.MessageDigest;  
  16. import java.security.NoSuchAlgorithmException;  
  17. import java.security.SecureRandom;  
  18. import java.security.spec.InvalidKeySpecException;  
  19.   
  20. import javax.crypto.BadPaddingException;  
  21. import javax.crypto.Cipher;  
  22. import javax.crypto.CipherInputStream;  
  23. import javax.crypto.IllegalBlockSizeException;  
  24. import javax.crypto.SecretKey;  
  25. import javax.crypto.SecretKeyFactory;  
  26. import javax.crypto.spec.DESKeySpec;  
  27.   
  28. /** 
  29.  * DESC: 对称加密 
  30.  * <p> 
  31.  * 仅作学习交流用途,严禁用作商业用途。版权所有,伪版必究。 
  32.  *  
  33.  * @Copyright YangFei 
  34.  *            </p> 
  35.  * @author yfei Date:2013-8-28 
  36.  */  
  37. public class SymmetricEncryption {  
  38.   
  39.     /** 
  40.      * mark as DES. 
  41.      */  
  42.     private static final String ALGORITHM = "DES";  
  43.   
  44.     /** 
  45.      * DEFAULT password. 
  46.      */  
  47.     private static String defaultStrKey = "yangfei";  
  48.     /** 
  49.      * 加密器. 
  50.      */  
  51.     private Cipher decryptCipher = Cipher.getInstance(ALGORITHM);  
  52.     /** 
  53.      * 解密器. 
  54.      */  
  55.     private Cipher encryptCipher = Cipher.getInstance(ALGORITHM);  
  56.   
  57.     /** 
  58.      * construct without parameter. 
  59.      *  
  60.      * @throws Exception 
  61.      *             the exception 
  62.      */  
  63.     public SymmetricEncryption() throws Exception {  
  64.         // key = DEFAULT_KEY;  
  65.         this(defaultStrKey);  
  66.     }  
  67.   
  68.     /** 
  69.      * construct with parameter password. 
  70.      *  
  71.      * @param strKey 
  72.      *            the str key 
  73.      * @throws Exception 
  74.      *             the exception 
  75.      */  
  76.     public SymmetricEncryption(String strKey) throws Exception {  
  77.         // DES算法要求有一个可信任的随机数源,可以认为是salt(加盐的加密)  
  78.         SecureRandom sr = new SecureRandom();  
  79.         // 生成DESKey  
  80.         SecretKey desKey = generateDESKey(strKey);  
  81.         // 初始化加密器  
  82.         encryptCipher.init(Cipher.ENCRYPT_MODE, desKey, sr);  
  83.         // 初始化解密器  
  84.         decryptCipher.init(Cipher.DECRYPT_MODE, desKey, sr);  
  85.     }  
  86.   
  87.     /** 
  88.      * <b>解密二进制数据.</b> 
  89.      *  
  90.      * @param source 
  91.      *            the source 
  92.      * @return the byte[] 
  93.      */  
  94.     public byte[] decrypt(byte[] source) {  
  95.         byte[] result = null;  
  96.         try {  
  97.             result = decryptCipher.doFinal(source);  
  98.         } catch (IllegalBlockSizeException e) {  
  99.             e.printStackTrace();  
  100.         } catch (BadPaddingException e) {  
  101.             e.printStackTrace();  
  102.         }  
  103.         return result;  
  104.     }  
  105.   
  106.     /* 
  107.      * (non-Javadoc) 
  108.      *  
  109.      * @see com.cnpc.pms.base.crypto.ICrypto#decrypt(java.io.InputStream) 
  110.      */  
  111.     /** 
  112.      * Decrypt. 
  113.      *  
  114.      * @param input 
  115.      *            the input 
  116.      * @return the output stream 
  117.      */  
  118.     public OutputStream decrypto(InputStream input,OutputStream output) {  
  119.         //OutputStream output = new ByteArrayOutputStream();  
  120.         CipherInputStream cis = new CipherInputStream(input, decryptCipher);  
  121.         byte[] buffer = new byte[1024];  
  122.         int r;  
  123.         try {  
  124.             while ((r = cis.read(buffer)) > 0) {  
  125.                 output.write(buffer, 0, r);  
  126.             }  
  127.             cis.close();  
  128.             input.close();  
  129.         } catch (IOException e) {  
  130.             e.printStackTrace();  
  131.         }  
  132.         return output;  
  133.     }  
  134.   
  135.     /** 
  136.      * <b>加密二进制数据.</b> 
  137.      *  
  138.      * @param source 
  139.      *            the source 
  140.      * @return the byte[] 
  141.      */  
  142.     public byte[] encrypt(byte[] source) {  
  143.         byte[] result = null;  
  144.         try {  
  145.             result = encryptCipher.doFinal(source);  
  146.         } catch (IllegalBlockSizeException e) {  
  147.             e.printStackTrace();  
  148.         } catch (BadPaddingException e) {  
  149.             e.printStackTrace();  
  150.         }  
  151.         return result;  
  152.     }  
  153.   
  154.     /** 
  155.      * Encrypt. 
  156.      *  
  157.      * @param input 
  158.      *            the input 
  159.      * @return the output stream 
  160.      */  
  161.     public OutputStream encrypto(InputStream input,OutputStream output) {  
  162.         //OutputStream output = new ByteArrayOutputStream();  
  163.         CipherInputStream cis = new CipherInputStream(input, encryptCipher);  
  164.         byte[] buffer = new byte[1024];  
  165.         int r;  
  166.         try {  
  167.             while ((r = cis.read(buffer)) > 0) {  
  168.                 output.write(buffer, 0, r);  
  169.             }  
  170.             cis.close();  
  171.             input.close();  
  172.         } catch (IOException e) {  
  173.             e.printStackTrace();  
  174.         }  
  175.         return output;  
  176.     }  
  177.   
  178.     /** 
  179.      * <b>transfer byte[8] to SecretKey.</b> 
  180.      *  
  181.      * @param strKey 
  182.      *            the str key 
  183.      * @return the secret key 
  184.      * @throws InvalidKeyException 
  185.      *             the invalid key exception 
  186.      * @throws NoSuchAlgorithmException 
  187.      *             the no such algorithm exception 
  188.      * @throws InvalidKeySpecException 
  189.      *             the invalid key spec exception 
  190.      * @throws UnsupportedEncodingException  
  191.      */  
  192.     private final SecretKey generateDESKey(String strKey)  
  193.             throws InvalidKeyException, NoSuchAlgorithmException,  
  194.             InvalidKeySpecException, UnsupportedEncodingException {  
  195.         byte[] byteKey = this.getByteKey(strKey);  
  196.         BigInteger bigInteger = new BigInteger(1,byteKey);  
  197.         System.out.println("the secrity md5 key is == "+bigInteger.toString(16));  
  198.         // get DESKey.  
  199.         DESKeySpec dks = null;  
  200.         SecretKeyFactory keyFactory = null// key Factory  
  201.         SecretKey secretKey = null// DESKey  
  202.         // 从原始密匙数据创建DESKeySpec对象  
  203.         dks = new DESKeySpec(byteKey);  
  204.         // 创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象  
  205.         keyFactory = SecretKeyFactory.getInstance(ALGORITHM);  
  206.         secretKey = keyFactory.generateSecret(dks);  
  207.         return secretKey;  
  208.     }  
  209.   
  210.     /** 
  211.      * <b>transfer password to byte[8]..</b> byte[] 
  212.      *  
  213.      * @param strKey 
  214.      *            the str key 
  215.      * @return the byte key 
  216.      * @throws NoSuchAlgorithmException  
  217.      */  
  218.     private final byte[] getByteKey(final String strKey) throws NoSuchAlgorithmException {  
  219.         // transfer password to byte[8].  
  220.         MessageDigest md = MessageDigest.getInstance("MD5");  
  221.         return md.digest(strKey.getBytes());  
  222.     }  
  223.   
  224.     /** 
  225.      * @param args 
  226.      *  
  227.      */  
  228.     public static void main(String[] args) {  
  229.         try {  
  230.             SymmetricEncryption clazz = new SymmetricEncryption();  
  231.             InputStream input = new FileInputStream(new File(  
  232.                     "testData/test.docx"));  
  233.             OutputStream out = new FileOutputStream(new File(  
  234.                     "testData/test_en.docx"));  
  235.             clazz.encrypto(input, out);  
  236.   
  237.             input.close();  
  238.             out.close();  
  239.   
  240.             InputStream input2 = new FileInputStream(new File(  
  241.                     "testData/test_en.docx"));  
  242.             OutputStream out2 = new FileOutputStream(new File(  
  243.                     "testData/test_de.docx"));  
  244.             clazz.decrypto(input2, out2);  
  245.   
  246.             input2.close();  
  247.             out2.close();  
  248.         } catch (Exception e) {  
  249.             // TODO Auto-generated catch block  
  250.             e.printStackTrace();  
  251.         }  
  252.     }  
  253.   
  254. }  


对称算法:A用一个密钥对一个文件加密,而B读取这个文件的话,则须要和A一样的密钥,双方共享一个私钥(而在web环境下,私钥在传递时简单被侦听): 

 运用私钥加密的话,最先须要一个密钥,可用javax.crypto.KeyGenerator产生一个密钥(java.security.Key), 然后传递给一个加密工具(javax.crypto.Cipher),该工具再运用相应的算法来执行 加密,首要对称算法有:DES(实际密钥只用到56 位),AES(支持三种密钥长度:128、192、256位),通常最先 128位,其他的还有DESede等,jdk1.5种也提供了对对称算法的支持,

0 0
原创粉丝点击