zoukankan      html  css  js  c++  java
  • Java常用的加密解密类(对称加密类)

    Java常用的加密解密类

    原文转载至:http://blog.csdn.net/wyc_cs/article/details/8793198

    原创 2013年04月12日 14:33:35
    最近做一个项目,想到以前所有的项目在用户注册与登录及所有涉及用户自身隐私的信息进行提交到后台时都没有进行加密处理,甚至直接以明文方式在网络上传输,同时直接以明文的方式存到数据库中。所以想到需要先进行加密处理之后再进行网络传输,最后将加密后的数据存到数据库中,这样也可以增强系统的安全性。

    对于加密与解密是一个很复杂的学科,如果想了解更深入的加密解密知识可以参考其它资料,本文只讲解一部分加密解密的使用方式。

    常用的加密解密可以分为:信息摘要算法:MD5,SHA(也就是单向加密理论上无法解密)、对称加密算法 :DES,3DES,AES、非对称加密算法:RSA,DSA

    本文只讲解单向加密和对称加密,关于非对称加密在以后的时间里进行添加。直接上代码,亲测可以运行:

    [java] view plain copy
     
    1. import java.security.MessageDigest;  
    2. import java.security.NoSuchAlgorithmException;  
    3.   
    4. import javax.crypto.Cipher;  
    5. import javax.crypto.KeyGenerator;  
    6. import javax.crypto.SecretKey;  
    7. import javax.crypto.spec.SecretKeySpec;  
    8. /** 
    9.  * 加密解密工具类 
    10.  */  
    11. public class EncryptUtils {  
    12.     /** 
    13.      * 进行MD5加密 
    14.      *  
    15.      * @param info 要加密的信息 
    16.      * @return String 加密后的字符串 
    17.      */  
    18.     public String encryptToMD5(String info) {  
    19.         byte[] digesta = null;  
    20.         try {  
    21.             // 得到一个md5的消息摘要  
    22.             MessageDigest alga = MessageDigest.getInstance("MD5");  
    23.             // 添加要进行计算摘要的信息  
    24.             alga.update(info.getBytes());  
    25.             // 得到该摘要  
    26.             digesta = alga.digest();  
    27.         } catch (NoSuchAlgorithmException e) {  
    28.             e.printStackTrace();  
    29.         }  
    30.         // 将摘要转为字符串  
    31.         String rs = byte2hex(digesta);  
    32.         return rs;  
    33.     }  
    34.   
    35.     /** 
    36.      * 进行SHA加密 
    37.      *  
    38.      * @param info 要加密的信息 
    39.      * @return String 加密后的字符串 
    40.      */  
    41.     public String encryptToSHA(String info) {  
    42.         byte[] digesta = null;  
    43.         try {  
    44.             // 得到一个SHA-1的消息摘要  
    45.             MessageDigest alga = MessageDigest.getInstance("SHA-1");  
    46.             // 添加要进行计算摘要的信息  
    47.             alga.update(info.getBytes());  
    48.             // 得到该摘要  
    49.             digesta = alga.digest();  
    50.         } catch (NoSuchAlgorithmException e) {  
    51.             e.printStackTrace();  
    52.         }  
    53.         // 将摘要转为字符串  
    54.         String rs = byte2hex(digesta);  
    55.         return rs;  
    56.     }  
    57.       
    58.   
    59.     /** 
    60.      * 根据一定的算法得到相应的key 
    61.      * @param src 
    62.      * @return 
    63.      */  
    64.     public String getKey(String algorithm,String src){  
    65.         if(algorithm.equals("AES")){  
    66.             return src.substring(0, 16);  
    67.         }else if(algorithm.equals("DES")){  
    68.             return src.substring(0, 8);  
    69.         }else{  
    70.             return null;  
    71.         }  
    72.     }  
    73.     /** 
    74.      * 得到AES加密的key 
    75.      * @param src 
    76.      * @return 
    77.      */  
    78.     public String getAESKey(String src){  
    79.         return this.getKey("AES", src);  
    80.     }  
    81.     /** 
    82.      * 得到DES加密的key 
    83.      * @param src 
    84.      * @return 
    85.      */  
    86.     public String getDESKey(String src){  
    87.         return this.getKey("DES", src);  
    88.     }  
    89.     /** 
    90.      * 创建密匙 
    91.      *  
    92.      * @param algorithm 加密算法,可用 AES,DES,DESede,Blowfish 
    93.      * @return SecretKey 秘密(对称)密钥 
    94.      */  
    95.     public SecretKey createSecretKey(String algorithm) {  
    96.         // 声明KeyGenerator对象  
    97.         KeyGenerator keygen;  
    98.         // 声明 密钥对象  
    99.         SecretKey deskey = null;  
    100.         try {  
    101.             // 返回生成指定算法的秘密密钥的 KeyGenerator 对象  
    102.             keygen = KeyGenerator.getInstance(algorithm);  
    103.             // 生成一个密钥  
    104.             deskey = keygen.generateKey();  
    105.         } catch (NoSuchAlgorithmException e) {  
    106.             e.printStackTrace();  
    107.         }  
    108.         // 返回密匙  
    109.         return deskey;  
    110.     }  
    111.   
    112.     /** 
    113.      * 创建一个AES的密钥 
    114.      * @return 
    115.      */  
    116.     public SecretKey createSecretAESKey() {  
    117.         return createSecretKey("AES");  
    118.     }  
    119.   
    120.     /** 
    121.      * 创建一个DES的密钥 
    122.      * @return 
    123.      */  
    124.     public SecretKey createSecretDESKey() {  
    125.         return createSecretKey("DES");  
    126.     }  
    127.   
    128.     /** 
    129.      * 根据相应的加密算法、密钥、源文件进行加密,返回加密后的文件 
    130.      * @param Algorithm 加密算法:DES,AES 
    131.      * @param key 
    132.      * @param info 
    133.      * @return 
    134.      */  
    135.     public String encrypt(String Algorithm, SecretKey key, String info) {  
    136.         // 定义要生成的密文  
    137.         byte[] cipherByte = null;  
    138.         try {  
    139.             // 得到加密/解密器  
    140.             Cipher c1 = Cipher.getInstance(Algorithm);  
    141.             // 用指定的密钥和模式初始化Cipher对象  
    142.             // 参数:(ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE,UNWRAP_MODE)  
    143.             c1.init(Cipher.ENCRYPT_MODE, key);  
    144.             // 对要加密的内容进行编码处理,  
    145.             cipherByte = c1.doFinal(info.getBytes());  
    146.         } catch (Exception e) {  
    147.             e.printStackTrace();  
    148.         }  
    149.         // 返回密文的十六进制形式  
    150.         return byte2hex(cipherByte);  
    151.     }  
    152.   
    153.     /** 
    154.      * 根据相应的解密算法、密钥和需要解密的文本进行解密,返回解密后的文本内容 
    155.      * @param Algorithm 
    156.      * @param key 
    157.      * @param sInfo 
    158.      * @return 
    159.      */  
    160.     public String decrypt(String Algorithm, SecretKey key, String sInfo) {  
    161.         byte[] cipherByte = null;  
    162.         try {  
    163.             // 得到加密/解密器  
    164.             Cipher c1 = Cipher.getInstance(Algorithm);  
    165.             // 用指定的密钥和模式初始化Cipher对象  
    166.             c1.init(Cipher.DECRYPT_MODE, key);  
    167.             // 对要解密的内容进行编码处理  
    168.             cipherByte = c1.doFinal(hex2byte(sInfo));  
    169.         } catch (Exception e) {  
    170.             e.printStackTrace();  
    171.         }  
    172.         return new String(cipherByte);  
    173.     }  
    174.   
    175.     /** 
    176.      * 根据相应的解密算法、指定的密钥和需要解密的文本进行解密,返回解密后的文本内容 
    177.      * @param Algorithm 加密算法:DES,AES 
    178.      * @param key 这个key可以由用户自己指定 注意AES的长度为16位,DES的长度为8位 
    179.      * @param sInfo 
    180.      * @return 
    181.      */  
    182.     public static String decrypt(String Algorithm, String sSrc, String sKey) throws Exception {  
    183.         try {  
    184.             // 判断Key是否正确  
    185.             if (sKey == null) {  
    186.                 throw new Exception("Key为空null");  
    187.             }  
    188.             // 判断采用AES加解密方式的Key是否为16位  
    189.             if (Algorithm.equals("AES") && sKey.length() != 16) {  
    190.                 throw new Exception("Key长度不是16位");  
    191.             }  
    192.             // 判断采用DES加解密方式的Key是否为8位  
    193.             if (Algorithm.equals("DES") && sKey.length() != 8) {  
    194.                 throw new Exception("Key长度不是8位");  
    195.             }  
    196.             byte[] raw = sKey.getBytes("ASCII");  
    197.             SecretKeySpec skeySpec = new SecretKeySpec(raw, Algorithm);  
    198.             Cipher cipher = Cipher.getInstance(Algorithm);  
    199.             cipher.init(Cipher.DECRYPT_MODE, skeySpec);  
    200.             byte[] encrypted1 = hex2byte(sSrc);  
    201.             try {  
    202.                 byte[] original = cipher.doFinal(encrypted1);  
    203.                 String originalString = new String(original);  
    204.                 return originalString;  
    205.             } catch (Exception e) {  
    206.                 throw e;  
    207.             }  
    208.         } catch (Exception ex) {  
    209.             throw ex;  
    210.         }  
    211.     }  
    212.   
    213.     /** 
    214.      * 根据相应的加密算法、指定的密钥、源文件进行加密,返回加密后的文件 
    215.      * @param Algorithm 加密算法:DES,AES 
    216.      * @param key 这个key可以由用户自己指定 注意AES的长度为16位,DES的长度为8位 
    217.      * @param info 
    218.      * @return 
    219.      */  
    220.     public static String encrypt(String Algorithm, String sSrc, String sKey) throws Exception {  
    221.         // 判断Key是否正确  
    222.         if (sKey == null) {  
    223.             throw new Exception("Key为空null");  
    224.         }  
    225.         // 判断采用AES加解密方式的Key是否为16位  
    226.         if (Algorithm.equals("AES") && sKey.length() != 16) {  
    227.             throw new Exception("Key长度不是16位");  
    228.         }  
    229.         // 判断采用DES加解密方式的Key是否为8位  
    230.         if (Algorithm.equals("DES") && sKey.length() != 8) {  
    231.             throw new Exception("Key长度不是8位");  
    232.         }  
    233.         byte[] raw = sKey.getBytes("ASCII");  
    234.         SecretKeySpec skeySpec = new SecretKeySpec(raw, Algorithm);  
    235.         Cipher cipher = Cipher.getInstance(Algorithm);  
    236.         cipher.init(Cipher.ENCRYPT_MODE, skeySpec);  
    237.         byte[] encrypted = cipher.doFinal(sSrc.getBytes());  
    238.         return byte2hex(encrypted);  
    239.     }  
    240.   
    241.     /** 
    242.      * 采用DES随机生成的密钥进行加密 
    243.      * @param key 
    244.      * @param info 
    245.      * @return 
    246.      */  
    247.     public String encryptToDES(SecretKey key, String info) {  
    248.         return encrypt("DES", key, info);  
    249.     }  
    250.   
    251.     /** 
    252.      * 采用DES指定密钥的方式进行加密 
    253.      * @param key 
    254.      * @param info 
    255.      * @return 
    256.      * @throws Exception 
    257.      */  
    258.     public String encryptToDES(String key, String info) throws Exception {  
    259.         return encrypt("DES", info, key);  
    260.     }  
    261.   
    262.     /** 
    263.      * 采用DES随机生成密钥的方式进行解密,密钥需要与加密的生成的密钥一样 
    264.      * @param key 
    265.      * @param sInfo 
    266.      * @return 
    267.      */  
    268.     public String decryptByDES(SecretKey key, String sInfo) {  
    269.         return decrypt("DES", key, sInfo);  
    270.     }  
    271.   
    272.     /** 
    273.      * 采用DES用户指定密钥的方式进行解密,密钥需要与加密时指定的密钥一样 
    274.      * @param key 
    275.      * @param sInfo 
    276.      * @return 
    277.      */  
    278.     public String decryptByDES(String key, String sInfo) throws Exception {  
    279.         return decrypt("DES", sInfo, key);  
    280.     }  
    281.   
    282.     /** 
    283.      * 采用AES随机生成的密钥进行加密 
    284.      * @param key 
    285.      * @param info 
    286.      * @return 
    287.      */  
    288.     public String encryptToAES(SecretKey key, String info) {  
    289.         return encrypt("AES", key, info);  
    290.     }  
    291.     /** 
    292.      * 采用AES指定密钥的方式进行加密 
    293.      * @param key 
    294.      * @param info 
    295.      * @return 
    296.      * @throws Exception 
    297.      */  
    298.     public String encryptToAES(String key, String info) throws Exception {  
    299.         return encrypt("AES", info, key);  
    300.     }  
    301.   
    302.     /** 
    303.      * 采用AES随机生成密钥的方式进行解密,密钥需要与加密的生成的密钥一样 
    304.      * @param key 
    305.      * @param sInfo 
    306.      * @return 
    307.      */  
    308.     public String decryptByAES(SecretKey key, String sInfo) {  
    309.         return decrypt("AES", key, sInfo);  
    310.     }  
    311.     /** 
    312.      * 采用AES用户指定密钥的方式进行解密,密钥需要与加密时指定的密钥一样 
    313.      * @param key 
    314.      * @param sInfo 
    315.      * @return 
    316.      */  
    317.     public String decryptByAES(String key, String sInfo) throws Exception {  
    318.         return decrypt("AES", sInfo, key);  
    319.     }  
    320.   
    321.     /** 
    322.      * 十六进制字符串转化为2进制 
    323.      *  
    324.      * @param hex 
    325.      * @return 
    326.      */  
    327.     public static byte[] hex2byte(String strhex) {  
    328.         if (strhex == null) {  
    329.             return null;  
    330.         }  
    331.         int l = strhex.length();  
    332.         if (l % 2 == 1) {  
    333.             return null;  
    334.         }  
    335.         byte[] b = new byte[l / 2];  
    336.         for (int i = 0; i != l / 2; i++) {  
    337.             b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2), 16);  
    338.         }  
    339.         return b;  
    340.     }  
    341.   
    342.     /** 
    343.      * 将二进制转化为16进制字符串 
    344.      *  
    345.      * @param b 二进制字节数组 
    346.      * @return String 
    347.      */  
    348.     public static String byte2hex(byte[] b) {  
    349.         String hs = "";  
    350.         String stmp = "";  
    351.         for (int n = 0; n < b.length; n++) {  
    352.             stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));  
    353.             if (stmp.length() == 1) {  
    354.                 hs = hs + "0" + stmp;  
    355.             } else {  
    356.                 hs = hs + stmp;  
    357.             }  
    358.         }  
    359.         return hs.toUpperCase();  
    360.     }  
    361.   
    362.     /** 
    363.      * 测试 
    364.      *  
    365.      * @param args 
    366.      */  
    367.     public static void main(String[] args) {  
    368.         EncryptUtils encryptUtils = new EncryptUtils();  
    369.         String source = "www.putiman.com";  
    370.         System.out.println("Hello经过MD5:" + encryptUtils.encryptToMD5(source));  
    371.         System.out.println("Hello经过SHA:" + encryptUtils.encryptToSHA(source));  
    372.         System.out.println("========随机生成Key进行加解密==============");  
    373.         // 生成一个DES算法的密匙  
    374.         SecretKey key = encryptUtils.createSecretDESKey();  
    375.         String str1 = encryptUtils.encryptToDES(key, source);  
    376.         System.out.println("DES加密后为:" + str1);  
    377.         // 使用这个密匙解密  
    378.         String str2 = encryptUtils.decryptByDES(key, str1);  
    379.         System.out.println("DES解密后为:" + str2);  
    380.   
    381.         // 生成一个AES算法的密匙  
    382.         SecretKey key1 = encryptUtils.createSecretAESKey();  
    383.         String stra = encryptUtils.encryptToAES(key1, source);  
    384.         System.out.println("AES加密后为:" + stra);  
    385.         // 使用这个密匙解密  
    386.         String strb = encryptUtils.decryptByAES(key1, stra);  
    387.         System.out.println("AES解密后为:" + strb);  
    388.         System.out.println("========指定Key进行加解密==============");  
    389.         try {  
    390.             String AESKey = encryptUtils.getAESKey(encryptUtils.encryptToSHA(source));  
    391.             String DESKey = encryptUtils.getDESKey(encryptUtils.encryptToSHA(source));  
    392.             System.out.println(AESKey);  
    393.             System.out.println(DESKey);  
    394.             String str11 = encryptUtils.encryptToDES(DESKey, source);  
    395.             System.out.println("DES加密后为:" + str11);  
    396.             // 使用这个密匙解密  
    397.             String str12 = encryptUtils.decryptByDES(DESKey, str11);  
    398.             System.out.println("DES解密后为:" + str12);  
    399.   
    400.             // 生成一个AES算法的密匙  
    401.             String strc = encryptUtils.encryptToAES(AESKey, source);  
    402.             System.out.println("AES加密后为:" + strc);  
    403.             // 使用这个密匙解密  
    404.             String strd = encryptUtils.decryptByAES(AESKey, strc);  
    405.             System.out.println("AES解密后为:" + strd);  
    406.         } catch (Exception e) {  
    407.             e.printStackTrace();  
    408.         }  
    409.     }  
    410. }  
     

    更多文章见:http://www.16boke.com
  • 相关阅读:
    【数学】【AOJ-614】座位安排
    【乱搞】【AOJ-611】消失的5,8,9
    redis 与session
    Nginx 与 tomcat 部署网站
    linux 进程在后台执行
    印象笔记
    consul 小結
    spring boot 使用拦截器,注解 实现 权限过滤
    Springcloud/Springboot项目绑定域名,使用Nginx配置Https
    spring boot 登录认证
  • 原文地址:https://www.cnblogs.com/mkl34367803/p/8430240.html
Copyright © 2011-2022 走看看