Java工具类-加密解密工具类

1、AES:高级加密标准(英语:Advanced Encryption Standard,缩写:AES),在密码学中又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。

工具类代码如下:

  1 import java.security.SecureRandom;
  2 import javax.crypto.Cipher;
  3 import javax.crypto.KeyGenerator;
  4 import javax.crypto.spec.SecretKeySpec;
  5 import com.asiainfo.lop.utils.string.StringUtil;
  6 public class AES {
  7     /** 
  8      * AES加密 
  9      * @param content 待加密的内容 
 10      * @param encryptKey 加密密钥 
 11      * @return 加密后的byte[] 
 12      * @throws Exception 
 13      */  
 14     public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {  
 15         KeyGenerator kgen = KeyGenerator.getInstance("AES");  
 16         kgen.init(128, new SecureRandom(encryptKey.getBytes()));  
 17   
 18         Cipher cipher = Cipher.getInstance("AES");  
 19         cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));  
 20           
 21         return cipher.doFinal(content.getBytes("utf-8"));  
 22     }  
 23       
 24     /** 
 25      * AES加密为base 64 code 
 26      * @param content 待加密的内容 
 27      * @param encryptKey 加密密钥 
 28      * @return 加密后的base 64 code 
 29      * @throws Exception 
 30      */  
 31     public static String encrypt(String content, String encryptKey) throws Exception {  
 32         AES aes = new AES();
 33         return aes.byte2hex((aesEncryptToBytes(content, encryptKey)));  
 34     }  
 35       
 36     /** 
 37      * AES解密 
 38      * @param encryptBytes 待解密的byte[] 
 39      * @param decryptKey 解密密钥 
 40      * @return 解密后的String 
 41      * @throws Exception 
 42      */  
 43     public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {  
 44         KeyGenerator kgen = KeyGenerator.getInstance("AES");  
 45         kgen.init(128, new SecureRandom(decryptKey.getBytes()));  
 46           
 47         Cipher cipher = Cipher.getInstance("AES");  
 48         cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));  
 49         byte[] decryptBytes = cipher.doFinal(encryptBytes);  
 50         return new String(decryptBytes);  
 51     }
 52       
 53     /** 
 54      * 将base 64 code AES解密 
 55      * @param encryptStr 待解密的base 64 code 
 56      * @param decryptKey 解密密钥 
 57      * @return 解密后的string 
 58      * @throws Exception 
 59      */  
 60     public static String decrypt(String encryptStr, String decryptKey) throws Exception { 
 61         AES aes = new AES();
 62         return StringUtil.isEmpty(encryptStr) ? null : aesDecryptByBytes(aes.hex2byte(encryptStr), decryptKey);  
 63     }  
 64     
 65     private String byte2hex(byte[] b) {
 66         String hs = "";
 67         String stmp = "";
 68         for (int i = 0; i < b.length; i++) {
 69             stmp = Integer.toHexString(b[i] & 0xFF);
 70             if (stmp.length() == 1) {
 71                 hs += "0" + stmp;
 72             } else {
 73                 hs += stmp;
 74             }
 75         }
 76         return hs.toUpperCase();
 77     }
 78 
 79     private byte[] hex2byte(String hex) throws IllegalArgumentException {
 80         if (hex.length() % 2 != 0) {
 81             System.out.println("hex:" + hex + "\nlength:" + hex.length());
 82             throw new IllegalArgumentException();
 83         }
 84         char[] arr = hex.toCharArray();
 85         byte[] b = new byte[hex.length() / 2];
 86         for (int i = 0, j = 0, l = hex.length(); i < l; i++, j++) {
 87             String swap = "" + arr[i++] + arr[i];
 88             int byteint = Integer.parseInt(swap, 16) & 0xFF;
 89             b[j] = new Integer(byteint).byteValue();
 90         }
 91         return b;
 92     }
 93 
 94 
 95     public static void main(String[] args) throws Exception {
 96         String content = "我爱你";
 97         System.out.println("加密前:" + content);
 98 
 99         String key = "123456";
100         System.out.println("加密密钥和解密密钥:" + key);
101 
102         String encrypt = encrypt(content, key);
103         System.out.println("加密后:" + encrypt);
104 
105         String decrypt = decrypt(encrypt, key);
106         System.out.println("解密后:" + decrypt);
107     }
108 }
View Code

2、BASE64

工具类代码如下:

 1 /**
 2  * 
 3  * <p>
 4  * Title: Base64.java
 5  * </p>
 6  * <p>
 7  * Description: 字符串加密解密
 8  * </p>
 9  * @version 1.0
10  * 
11  */
12 
13 @SuppressWarnings("restriction")
14 public final class BASE64 {
15     /**
16      * 
17      * 加密字符串
18      * 
19      * @param s
20      * @return String
21      * 
22      */
23     public static String encrypt(String s) {
24         if (s == null)
25             return null;
26         return (new sun.misc.BASE64Encoder()).encode(s.getBytes());
27     }
28 
29     /**
30      * 
31      * 解密字符串
32      * 
33      * @param s
34      * @return String
35      * 
36      */
37     public static String decrypt(String s) {
38         if (s == null)
39             return null;
40         sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
41         try {
42             byte[] b = decoder.decodeBuffer(s);
43             return new String(b);
44         } catch (Exception e) {
45             return null;
46         }
47     }
48 
49     public static void main(String[] aa) {
50         String pwd1 = "Wangbt777";
51         System.out.println(encrypt(pwd1)); // 加密
52 
53         String pwd2 = "V2FuZ2J0Nzc3";
54         System.out.println(decrypt(pwd2)); // 解密
55     }
56 }
View Code

3、DES:算法为密码体制中的对称密码体制,又被成为美国数据加密标准,是1972年美国IBM公司研制的对称密码体制加密算法。明文按64位进行分组, 密钥长64位,密钥事实上是56位参与DES运算(第8、16、24、32、40、48、56、64位是校验位,使得每个密钥都有奇数个1)分组后的明文组和56位的密钥按位替代或交换的方法形成密文组的加密方法。DESede又称Triple-DES即三重DES加密算法,加强了DES的安全性,但速度稍慢,它是一种对称加密算法,加密解密都是用同一个密钥。本文介绍使用Java自带的API实现DEDede加密解密。

工具类代码如下:

  1 import java.security.Security;
  2 import javax.crypto.Cipher;
  3 import javax.crypto.KeyGenerator;
  4 import javax.crypto.SecretKey;
  5 import javax.crypto.spec.SecretKeySpec;
  6 
  7 /**
  8  * 
  9  * <p>
 10  * Title: DES.java
 11  * </p>
 12  * <p>
 13  * Description: 字符串加密类,支持算法DES、DESede、Blowfish
 14  * </p>
 15  * 
 16  * @author
 17  * @version 1.0
 18  * 
 19  */
 20 @SuppressWarnings({ "static-access", "restriction" })
 21 public class DES {
 22     public static int _DES = 1;
 23     public static int _DESede = 2;
 24     public static int _Blowfish = 3;
 25     // Cipher负责完成加密或解密工作
 26     private Cipher p_Cipher;
 27     // SecretKey 负责保存对称密钥
 28     private SecretKey p_Key;
 29     private String p_Algorithm;
 30     private static DES _instance;
 31     private static String hexKey = "B5584A5D9B61C23BE52CA1168C9110894C4FE9ABC8E9F251";// 密钥
 32 
 33     private void selectAlgorithm(int al) {
 34         switch (al) {
 35         default:
 36         case 1:
 37             this.p_Algorithm = "DES";
 38             break;
 39         case 2:
 40             this.p_Algorithm = "DESede";
 41             break;
 42         case 3:
 43             this.p_Algorithm = "Blowfish";
 44             break;
 45         }
 46     }
 47 
 48     /**
 49      * 构造函数
 50      * 
 51      * @param algorithm
 52      *            加密算法类型,取值为1,2,3其中一个,对应为DES,DESede,Blowfish
 53      * @throws Exception
 54      */
 55     public DES(int algorithm) throws Exception {
 56         this.selectAlgorithm(algorithm);
 57         Security.addProvider(new com.sun.crypto.provider.SunJCE());
 58         this.p_Cipher = Cipher.getInstance(this.p_Algorithm);
 59     }
 60 
 61     @SuppressWarnings("unused")
 62     private byte[] getKey() {
 63         return this.checkKey().getEncoded();
 64     }
 65 
 66     private SecretKey checkKey() {
 67         try {
 68             if (this.p_Key == null) {
 69                 KeyGenerator keygen = KeyGenerator.getInstance(this.p_Algorithm);
 70                 /*
 71                  * SecureRandom sr = new SecureRandom(key.getBytes());
 72                  * keygen.init(168, sr);
 73                  */
 74                 this.p_Key = keygen.generateKey();
 75             }
 76         } catch (Exception nsae) {
 77         }
 78         return this.p_Key;
 79     }
 80 
 81     private void setKey(byte[] enckey) {
 82         this.p_Key = new SecretKeySpec(enckey, this.p_Algorithm);
 83     }
 84 
 85     private byte[] encode(byte[] data) throws Exception {
 86         this.p_Cipher.init(Cipher.ENCRYPT_MODE, this.checkKey());
 87         return this.p_Cipher.doFinal(data);
 88     }
 89 
 90     private byte[] decode(byte[] encdata, byte[] enckey) throws Exception {
 91         this.setKey(enckey);
 92         this.p_Cipher.init(Cipher.DECRYPT_MODE, this.p_Key);
 93         return this.p_Cipher.doFinal(encdata);
 94     }
 95 
 96     private String byte2hex(byte[] b) {
 97         String hs = "";
 98         String stmp = "";
 99         for (int i = 0; i < b.length; i++) {
100             stmp = Integer.toHexString(b[i] & 0xFF);
101             if (stmp.length() == 1) {
102                 hs += "0" + stmp;
103             } else {
104                 hs += stmp;
105             }
106         }
107         return hs.toUpperCase();
108     }
109 
110     private byte[] hex2byte(String hex) throws IllegalArgumentException {
111         if (hex.length() % 2 != 0) {
112             System.out.println("hex:" + hex + "\nlength:" + hex.length());
113             throw new IllegalArgumentException();
114         }
115         char[] arr = hex.toCharArray();
116         byte[] b = new byte[hex.length() / 2];
117         for (int i = 0, j = 0, l = hex.length(); i < l; i++, j++) {
118             String swap = "" + arr[i++] + arr[i];
119             int byteint = Integer.parseInt(swap, 16) & 0xFF;
120             b[j] = new Integer(byteint).byteValue();
121         }
122         return b;
123     }
124 
125     /**
126      * 加密字符串
127      * 
128      * @param s
129      *            待加密的字符串
130      * @return String 加密后的字符串
131      * @throws Exception
132      * 
133      */
134     public static String encrypt(String s) throws Exception {
135         // byte[] key; //密钥文件(byte)
136         if (null == _instance) {
137             _instance = new DES(DES._DESede);
138         }
139         // key = _instance.getKey();
140         _instance.setKey(_instance.hex2byte(_instance.hexKey));
141         // String hexkey = _instance.byte2hex(key); //生成十六进制密钥
142         byte[] enc = _instance.encode(s.getBytes()); // 生成加密文件(byte)
143         String hexenc = _instance.byte2hex(enc);
144         return hexenc;
145     }
146 
147     /**
148      * 解密字符串
149      * 
150      * @param s
151      *            待解密的字符串
152      * @return String 解密后的字符串
153      * @throws Exception
154      * 
155      *
156      */
157     public static String decrypt(String s) throws Exception {
158         if (null == _instance) {
159             _instance = new DES(DES._DESede);
160         }
161         return new String(_instance.decode(_instance.hex2byte(s), _instance.hex2byte(_instance.hexKey)));
162     }
163 
164     public static void main(String[] args) throws Exception {
165         String pwd = "admin";
166         System.out.println(DES.encrypt(pwd));
167     }
168 }
View Code

4、RSA:公钥加密算法是1977年由Ron Rivest、Adi Shamirh和LenAdleman在(美国麻省理工学院)开发的。RSA取名来自开发他们三者的名字。RSA是目前最有影响力的公钥加密算法,它能够抵抗到目前为止已知的所有密码攻击,已被ISO推荐为公钥数据加密标准。RSA算法基于一个十分简单的数论事实:将两个大素数相乘十分容易,但那时想要对其乘积进行因式分解却极其困难,因此可以将乘积公开作为加密密钥。

工具类代码如下:

  1 import java.security.InvalidKeyException;
  2 import java.security.KeyPair;
  3 import java.security.KeyPairGenerator;
  4 import java.security.NoSuchAlgorithmException;
  5 import java.security.interfaces.RSAPrivateKey;
  6 import java.security.interfaces.RSAPublicKey;
  7 import javax.crypto.BadPaddingException;
  8 import javax.crypto.Cipher;
  9 import javax.crypto.IllegalBlockSizeException;
 10 import javax.crypto.NoSuchPaddingException;
 11 public class RSA {
 12     
 13     /**
 14      * 
 15      * @param publicKey
 16      * @param srcBytes
 17      * @return
 18      * @throws NoSuchAlgorithmException
 19      * @throws NoSuchPaddingException
 20      * @throws InvalidKeyException
 21      * @throws IllegalBlockSizeException
 22      * @throws BadPaddingException
 23      */
 24     public static byte[] encrypt(RSAPublicKey publicKey,byte[] srcBytes) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{  
 25         if(publicKey!=null){  
 26             //Cipher负责完成加密或解密工作,基于RSA  
 27             Cipher cipher = Cipher.getInstance("RSA");  
 28             //根据公钥,对Cipher对象进行初始化  
 29             cipher.init(Cipher.ENCRYPT_MODE, publicKey);  
 30             byte[] resultBytes = cipher.doFinal(srcBytes);  
 31             return resultBytes;  
 32         }  
 33         return null;  
 34     }  
 35       
 36     /** 
 37      * 解密  
 38      * @param privateKey 
 39      * @param srcBytes 
 40      * @return 
 41      * @throws NoSuchAlgorithmException 
 42      * @throws NoSuchPaddingException 
 43      * @throws InvalidKeyException 
 44      * @throws IllegalBlockSizeException 
 45      * @throws BadPaddingException 
 46      */  
 47     public static byte[] decrypt(RSAPrivateKey privateKey,byte[] srcBytes) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{  
 48         if(privateKey!=null){  
 49             //Cipher负责完成加密或解密工作,基于RSA  
 50             Cipher cipher = Cipher.getInstance("RSA");  
 51             //根据公钥,对Cipher对象进行初始化  
 52             cipher.init(Cipher.DECRYPT_MODE, privateKey);  
 53             byte[] resultBytes = cipher.doFinal(srcBytes);  
 54             return resultBytes;  
 55         }  
 56         return null;  
 57     }  
 58     
 59     /**
 60      * 
 61      * @return
 62      * @throws NoSuchAlgorithmException
 63      */
 64     public static KeyPair getKeyPair() throws NoSuchAlgorithmException{
 65         //KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象  
 66         KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");  
 67         //初始化密钥对生成器,密钥大小为1024位  
 68         keyPairGen.initialize(1024);  
 69         //生成一个密钥对,保存在keyPair中  
 70         KeyPair keyPair = keyPairGen.generateKeyPair();  
 71         return keyPair;
 72     }
 73     
 74   
 75     /** 
 76      * @param args 
 77      * @throws NoSuchAlgorithmException  
 78      * @throws BadPaddingException  
 79      * @throws IllegalBlockSizeException  
 80      * @throws NoSuchPaddingException  
 81      * @throws InvalidKeyException  
 82      */  
 83     public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {  
 84         String msg = "郭XX-精品相声";  
 85         KeyPair keyPair = getKeyPair();
 86         //得到私钥  
 87         RSAPrivateKey privateKey = (RSAPrivateKey)keyPair.getPrivate();               
 88         //得到公钥  
 89         RSAPublicKey publicKey = (RSAPublicKey)keyPair.getPublic();  
 90           
 91         //用公钥加密  
 92         byte[] srcBytes = msg.getBytes();  
 93         byte[] resultBytes = encrypt(publicKey, srcBytes);  
 94           
 95         //用私钥解密  
 96         byte[] decBytes = decrypt(privateKey, resultBytes);  
 97           
 98         System.out.println("明文是:" + msg);
 99         System.out.println("加密后是:" + new String(resultBytes));  
100         System.out.println("解密后是:" + new String(decBytes));  
101     }  
102 }
View Code
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杜林晓

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值