JAVA 常用加密方法

1.Base64
  加密:org.apache.commons.codec.binary.Base64.encodeBase64(byte[] binaryData)
  解密:org.apache.commons.codec.binary.Base64.decodeBase64(byte[] base64Data)
2.Md5
  加密:org.apache.commons.codec.digest.md5Hex(byte[] data)
  解密:无
3.DES(des-ecb,3des,des-cbc,cbc-mac)

[java] view plain copy

  1.  import java.io.ByteArrayOutputStream;  
  2. import java.security.SecureRandom;  
  3. import java.util.Arrays;  
  4.   
  5. import javax.crypto.Cipher;  
  6. import javax.crypto.SecretKey;  
  7. import javax.crypto.SecretKeyFactory;  
  8. import javax.crypto.spec.DESKeySpec;  
  9. import javax.crypto.spec.DESedeKeySpec;  
  10. import javax.crypto.spec.IvParameterSpec;  
  11. import javax.crypto.spec.SecretKeySpec;  
  12.   
  13. import org.bouncycastle.crypto.BlockCipher;  
  14. import org.bouncycastle.crypto.Mac;  
  15. import org.bouncycastle.crypto.engines.DESEngine;  
  16. import org.bouncycastle.crypto.macs.CBCBlockCipherMac;  
  17. import org.bouncycastle.crypto.params.KeyParameter;  
  18.   
  19. import com.alibaba.common.lang.StringUtil;  
  20. import com.huateng.commons.lang.convert.HexUtils;  
  21.   
  22. public class ShfftDes {  
  23.     //验证用密钥  
  24.     private byte[]              key         = "000000000000000000000000".getBytes();  
  25.   
  26.     //    private byte[]              key         = Hex.decode("00000000");  
  27.   
  28.     private byte[]              ivs         = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };  
  29.   
  30.     private static final String DES_EDE     = "DESede/ECB/NoPadding";               //定义 加密算法,可用 DES,DESede,Blowfish        //keybyte为加密密钥,长度为24字节    //src为被加密的数据缓冲区(源)  
  31.   
  32.     private static final String DES_EDE_CBC = "DESede/CBC/NoPadding";               //定义 加密算法,可用 DES,DESede,Blowfish        //keybyte为加密密钥,长度为24字节    //src为被加密的数据缓冲区(源)  
  33.   
  34.     private static final String DES_CBC     = "DES/CBC/NoPadding";  
  35.   
  36.     private static final String DES_ECB     = "DES/ECB/PKCS5Padding";  
  37.   
  38.     /** 
  39.      * 使用DES_ECB方法进行加密 
  40.      * @param content   需加密内容 
  41.      * @param key       加密的密钥 
  42.      * @param mode      加密还是解密 
  43.      * @return 
  44.      * @throws Exception 
  45.      */  
  46.     public byte[] CryptByDes(byte[] content, int mode) throws Exception {  
  47.         Cipher cipher = Cipher.getInstance(DES_ECB);  
  48.         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");  
  49.         SecretKey secretKey = keyFactory.generateSecret(new DESKeySpec(key));  
  50.         cipher.init(mode, secretKey);  
  51.         return cipher.doFinal(content);  
  52.     }  
  53.   
  54.     /** 
  55.      * 使用3DES方法进行加密 
  56.      * @param content   需加密内容 
  57.      * @param key       加密的密钥 
  58.      * @param mode      加密还是解密 
  59.      * @return 
  60.      * @throws Exception 
  61.      */  
  62.     public byte[] CryptBy3Des(byte[] content, int mode) throws Exception {  
  63.         Cipher cipher = Cipher.getInstance(DES_EDE);  
  64.         SecretKey secretKey = new SecretKeySpec(key, "DESede");  
  65.         cipher.init(mode, secretKey);  
  66.         return cipher.doFinal(content);  
  67.     }  
  68.   
  69.     /** 
  70.      * 使用DES_CBC方法进行加密 
  71.      * @param content   需加密内容 
  72.      * @param key       加密的密钥 
  73.      * @param mode      加密还是解密 
  74.      * @return 
  75.      * @throws Exception 
  76.      */  
  77.     public byte[] CryptByDesCbc(byte[] content, int mode) throws Exception {  
  78.         Cipher cipher = Cipher.getInstance(DES_CBC);  
  79.         SecretKey secureKey = new SecretKeySpec(key, "DES");  
  80.         IvParameterSpec iv = new IvParameterSpec(ivs);  
  81.         cipher.init(mode, secureKey, iv);  
  82.         return cipher.doFinal(HexUtils.fromHex(new String(content)));  
  83.     }  
  84.   
  85.     /** 
  86.      * 使用3DES_CBC方法进行加密 
  87.      * @param content   需加密内容 
  88.      * @param key       加密的密钥 
  89.      * @param mode      加密还是解密 
  90.      * @return 
  91.      * @throws Exception 
  92.      */  
  93.     public byte[] CryptBy3DesCbc(byte[] content, int mode) throws Exception {  
  94.         Cipher cipher = Cipher.getInstance(DES_EDE_CBC);  
  95.         SecretKey secureKey = new SecretKeySpec(key, "DESede");  
  96.         IvParameterSpec iv = new IvParameterSpec(ivs);  
  97.         cipher.init(mode, secureKey, iv);  
  98.         return cipher.doFinal(content);  
  99.     }  
  100.   
  101.     /** 
  102.      *  CBC的MAC加密 
  103.      * @param content 
  104.      * @param mode 
  105.      * @return 
  106.      * @throws Exception 
  107.      */  
  108.     public byte[] CryptByDesCbcMac(byte[] content) throws Exception {  
  109.         BlockCipher engine = new DESEngine();  
  110.         Mac mac = new CBCBlockCipherMac(engine, 64);  
  111.         byte[] macText = new byte[engine.getBlockSize()];  
  112.         mac.init(new KeyParameter(key));  
  113.         mac.update(Padding(content, 64), 0, content.length);  
  114.         mac.update(content, 0, content.length);  
  115.         mac.doFinal(macText, 0);  
  116.         return macText;  
  117.     }  
  118.   
  119.     /** 
  120.      * CBC的MAC加密 
  121.      * @param content 
  122.      * @param mode 
  123.      * @return 
  124.      * @throws Exception 
  125.      */  
  126.     public byte[] ShFftCryptByDessdsCbc(byte[] content, int mode) throws Exception {  
  127.         byte[] ks1 = HexUtils.fromHex(new String(key));  
  128.         byte[] ks = new byte[24];  
  129.         System.arraycopy(ks1, 0, ks, 0, ks1.length);  
  130.         System.arraycopy(ks1, 0, ks, ks1.length, 8);  
  131.   
  132.         Cipher cipher = Cipher.getInstance(DES_EDE_CBC);  
  133.         SecretKeyFactory keyFactory = null;  
  134.         keyFactory = SecretKeyFactory.getInstance("DESede");  
  135.         SecretKey secretKey = null;  
  136.         secretKey = keyFactory.generateSecret(new DESedeKeySpec(ks));  
  137.         IvParameterSpec iv = new IvParameterSpec(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 });  
  138.         cipher.init(mode, secretKey, iv);  
  139.         return cipher.doFinal(HexUtils.fromHex(new String(content)));  
  140.     }  
  141.   
  142.     public byte[] mac(byte[] content) throws Exception {  
  143.         int len;  
  144.         byte plainData[];  
  145.         byte encryptedData[];  
  146.         len = (content.length / 8 + (content.length % 8 != 0 ? 1 : 0)) * 8;  
  147.         plainData = new byte[len];  
  148.         encryptedData = new byte[8];  
  149.         Arrays.fill(plainData, (byte) 32);  
  150.         System.arraycopy(content, 0, plainData, 0, content.length);  
  151.         SecureRandom sr = new SecureRandom();  
  152.         DESKeySpec dks = new DESKeySpec(key);  
  153.         SecretKeyFactory keyFactory = null;  
  154.         keyFactory = SecretKeyFactory.getInstance("DES");  
  155.         SecretKey secretKey = keyFactory.generateSecret(dks);  
  156.         Cipher cipher = Cipher.getInstance("DES/CBC/NoPadding");  
  157.         IvParameterSpec iv = new IvParameterSpec(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 });  
  158.         cipher.init(1, secretKey, iv, sr);  
  159.         System.arraycopy(cipher.doFinal(plainData), len - 8, encryptedData, 0, 8);  
  160.         return encryptedData;  
  161.     }  
  162.   
  163.     /** 
  164.      * 根据传入参数进行空格填充 
  165.      * @param content   需要填充的内容 
  166.      * @param block     填充的分块大小 
  167.      * @return 
  168.      */  
  169.     public byte[] Padding(byte[] content, int block) {  
  170.         int contentLength = content.length;  
  171.         int mod = contentLength % block;  
  172.         if (mod != 0) {  
  173.             int size = contentLength + block - mod;  
  174.             //            String s = new String(content);  
  175.             //            StringUtil.alignLeft(s, size, " ");  
  176.             byte[] s = new byte[size];  
  177.             System.arraycopy(content, 0, s, 0, content.length);  
  178.             for (int i = content.length; i < size; i++) {  
  179.                 s[i] = 32;  
  180.             }  
  181.             return s;  
  182.         }  
  183.         return content;  
  184.     }  
  185.   
  186.     /** 
  187.      * 根据传入参数进行空格填充 
  188.      * @param content   需要填充的内容 
  189.      * @param block     填充的分块大小 
  190.      * @return 
  191.      */  
  192.     public String Padding(String content, int block) {  
  193.         int contentLength = content.length();  
  194.         int mod = contentLength % block;  
  195.         if (mod != 0) {  
  196.             int size = contentLength + block - mod;  
  197.             String s = new String(content);  
  198.             StringUtil.alignLeft(s, size, " ");  
  199.             return s;  
  200.         }  
  201.         return content;  
  202.     }  
  203.   
  204.     /** 
  205.      * 打印byte数据 
  206.      * @param bs 
  207.      */  
  208.     public void println(byte[] bs) {  
  209.         for (byte b : bs) {  
  210.             System.out.print(b + " ");  
  211.         }  
  212.         System.out.println();  
  213.     }  
  214.   
  215.     /** 
  216.      * 打印无符号byte数组 
  217.      * @param bs 
  218.      */  
  219.     public void printlnByte(byte[] bs) {  
  220.         for (byte b : bs) {  
  221.             if (b < 0) {  
  222.                 System.out.print((int) b + 256 + " ");  
  223.             } else {  
  224.                 System.out.print(b + " ");  
  225.             }  
  226.         }  
  227.         System.out.println();  
  228.     }  
  229.   
  230.     /** 
  231.      * 以16进制形式打印BYTE数组 
  232.      * @param bs 
  233.      */  
  234.     public void printlnByteInt16(byte[] bs) {  
  235.         for (byte b : bs) {  
  236.             System.out.print(Integer.toHexString((int) b) + " ");  
  237.         }  
  238.         System.out.println();  
  239.     }  
  240.   
  241.     /** 
  242.      * 将byte数组按1个byte分解为2个字符 
  243.      * @param bytes 
  244.      * @return 
  245.      */  
  246.     public String dumpBytes(byte[] bytes) {  
  247.         int i;  
  248.         StringBuffer sb = new StringBuffer();  
  249.         for (i = 0; i < bytes.length; i++) {  
  250.             int n = bytes[i] >= 0 ? bytes[i] : 256 + bytes[i];  
  251.             String s = Integer.toHexString(n);  
  252.             if (s.length() < 2) {  
  253.                 s = "0" + s;  
  254.             }  
  255.             if (s.length() > 2) {  
  256.                 s = s.substring(s.length() - 2);  
  257.             }  
  258.             sb.append(s);  
  259.         }  
  260.         return sb.toString().toUpperCase();  
  261.         //return new BASE64Encoder().encode(bytes);  
  262.     }  
  263.   
  264.     // 一下程序将每2位16进制整数组装成一个字节  
  265.     private String hexString = "0123456789ABCDEF";  
  266.   
  267.     public byte[] decode(String bytes) {  
  268.         ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length() / 2);  
  269.         for (int i = 0; i < bytes.length(); i += 2)  
  270.             baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString.indexOf(bytes  
  271.                 .charAt(i + 1))));  
  272.         return baos.toByteArray();  
  273.     }  
  274.   
  275.     public byte[] getKey() {  
  276.         return key;  
  277.     }  
  278.   
  279.     public void setKey(byte[] key) {  
  280.         this.key = key;  
  281.     }  
  282.   
  283.     public byte[] getIvs() {  
  284.         return ivs;  
  285.     }  
  286.   
  287.     public void setIvs(byte[] ivs) {  
  288.         this.ivs = ivs;  
  289.     }  
  290.   
  291. }  

猜你喜欢

转载自my.oschina.net/u/3787897/blog/1628180
今日推荐