RSA加密和解密工具类

  1 import org.apache.commons.codec.binary.Base64;
  2 
  3 import javax.crypto.Cipher;
  4 import java.security.*;
  5 import java.security.spec.PKCS8EncodedKeySpec;
  6 import java.security.spec.X509EncodedKeySpec;
  7 import java.util.HashMap;
  8 import java.util.Map;
  9 
 10 /**
 11  * RSA加密和解密工具
 12  *
 13  * @Author: syj
 14  * @CreateDate: 2018/7/20 16:52
 15  */
 16 public class RSAUtil {
 17 
 18     /**
 19      * 数字签名,密钥算法
 20      */
 21     private static final String RSA_KEY_ALGORITHM = "RSA";
 22 
 23     /**
 24      * 数字签名签名/验证算法
 25      */
 26     private static final String SIGNATURE_ALGORITHM = "MD5withRSA";
 27 
 28     /**
 29      * RSA密钥长度,RSA算法的默认密钥长度是1024密钥长度必须是64的倍数,在512到65536位之间
 30      */
 31     private static final int KEY_SIZE = 1024;
 32 
 33     /**
 34      * 生成密钥对
 35      */
 36     private static Map<String, String> initKey() throws Exception {
 37         KeyPairGenerator keygen = KeyPairGenerator.getInstance(RSA_KEY_ALGORITHM);
 38         SecureRandom secrand = new SecureRandom();
 39         /**
 40          * 初始化随机产生器
 41          */
 42         secrand.setSeed("initSeed".getBytes());
 43         /**
 44          * 初始化密钥生成器
 45          */
 46         keygen.initialize(KEY_SIZE, secrand);
 47         KeyPair keys = keygen.genKeyPair();
 48 
 49         byte[] pub_key = keys.getPublic().getEncoded();
 50         String publicKeyString = Base64.encodeBase64String(pub_key);
 51 
 52         byte[] pri_key = keys.getPrivate().getEncoded();
 53         String privateKeyString = Base64.encodeBase64String(pri_key);
 54 
 55         Map<String, String> keyPairMap = new HashMap<>();
 56         keyPairMap.put("publicKeyString", publicKeyString);
 57         keyPairMap.put("privateKeyString", privateKeyString);
 58 
 59         return keyPairMap;
 60     }
 61 
 62     /**
 63      * 密钥转成字符串
 64      *
 65      * @param key
 66      * @return
 67      */
 68     public static String encodeBase64String(byte[] key) {
 69         return Base64.encodeBase64String(key);
 70     }
 71 
 72     /**
 73      * 密钥转成byte[]
 74      *
 75      * @param key
 76      * @return
 77      */
 78     public static byte[] decodeBase64(String key) {
 79         return Base64.decodeBase64(key);
 80     }
 81 
 82     /**
 83      * 公钥加密
 84      *
 85      * @param data      加密前的字符串
 86      * @param publicKey 公钥
 87      * @return 加密后的字符串
 88      * @throws Exception
 89      */
 90     public static String encryptByPubKey(String data, String publicKey) throws Exception {
 91         byte[] pubKey = RSAUtil.decodeBase64(publicKey);
 92         byte[] enSign = encryptByPubKey(data.getBytes(), pubKey);
 93         return Base64.encodeBase64String(enSign);
 94     }
 95 
 96     /**
 97      * 公钥加密
 98      *
 99      * @param data   待加密数据
100      * @param pubKey 公钥
101      * @return
102      * @throws Exception
103      */
104     public static byte[] encryptByPubKey(byte[] data, byte[] pubKey) throws Exception {
105         X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pubKey);
106         KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
107         PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
108         Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
109         cipher.init(Cipher.ENCRYPT_MODE, publicKey);
110         return cipher.doFinal(data);
111     }
112 
113     /**
114      * 私钥加密
115      *
116      * @param data       加密前的字符串
117      * @param privateKey 私钥
118      * @return 加密后的字符串
119      * @throws Exception
120      */
121     public static String encryptByPriKey(String data, String privateKey) throws Exception {
122         byte[] priKey = RSAUtil.decodeBase64(privateKey);
123         byte[] enSign = encryptByPriKey(data.getBytes(), priKey);
124         return Base64.encodeBase64String(enSign);
125     }
126 
127     /**
128      * 私钥加密
129      *
130      * @param data   待加密的数据
131      * @param priKey 私钥
132      * @return 加密后的数据
133      * @throws Exception
134      */
135     public static byte[] encryptByPriKey(byte[] data, byte[] priKey) throws Exception {
136         PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(priKey);
137         KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
138         PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
139         Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
140         cipher.init(Cipher.ENCRYPT_MODE, privateKey);
141         return cipher.doFinal(data);
142     }
143 
144     /**
145      * 公钥解密
146      *
147      * @param data   待解密的数据
148      * @param pubKey 公钥
149      * @return 解密后的数据
150      * @throws Exception
151      */
152     public static byte[] decryptByPubKey(byte[] data, byte[] pubKey) throws Exception {
153         X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pubKey);
154         KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
155         PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
156         Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
157         cipher.init(Cipher.DECRYPT_MODE, publicKey);
158         return cipher.doFinal(data);
159     }
160 
161     /**
162      * 公钥解密
163      *
164      * @param data      解密前的字符串
165      * @param publicKey 公钥
166      * @return 解密后的字符串
167      * @throws Exception
168      */
169     public static String decryptByPubKey(String data, String publicKey) throws Exception {
170         byte[] pubKey = RSAUtil.decodeBase64(publicKey);
171         byte[] design = decryptByPubKey(Base64.decodeBase64(data), pubKey);
172         return new String(design);
173     }
174 
175     /**
176      * 私钥解密
177      *
178      * @param data   待解密的数据
179      * @param priKey 私钥
180      * @return
181      * @throws Exception
182      */
183     public static byte[] decryptByPriKey(byte[] data, byte[] priKey) throws Exception {
184         PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(priKey);
185         KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
186         PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
187         Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
188         cipher.init(Cipher.DECRYPT_MODE, privateKey);
189         return cipher.doFinal(data);
190     }
191 
192     /**
193      * 私钥解密
194      *
195      * @param data       解密前的字符串
196      * @param privateKey 私钥
197      * @return 解密后的字符串
198      * @throws Exception
199      */
200     public static String decryptByPriKey(String data, String privateKey) throws Exception {
201         byte[] priKey = RSAUtil.decodeBase64(privateKey);
202         byte[] design = decryptByPriKey(Base64.decodeBase64(data), priKey);
203         return new String(design);
204     }
205 
206     /**
207      * RSA签名
208      *
209      * @param data   待签名数据
210      * @param priKey 私钥
211      * @return 签名
212      * @throws Exception
213      */
214     public static String sign(byte[] data, byte[] priKey) throws Exception {
215         // 取得私钥
216         PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(priKey);
217         KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
218         // 生成私钥
219         PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
220         // 实例化Signature
221         Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
222         // 初始化Signature
223         signature.initSign(privateKey);
224         // 更新
225         signature.update(data);
226         return Base64.encodeBase64String(signature.sign());
227     }
228 
229     /**
230      * RSA校验数字签名
231      *
232      * @param data   待校验数据
233      * @param sign   数字签名
234      * @param pubKey 公钥
235      * @return boolean 校验成功返回true,失败返回false
236      */
237     public boolean verify(byte[] data, byte[] sign, byte[] pubKey) throws Exception {
238         // 实例化密钥工厂
239         KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
240         // 初始化公钥
241         X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pubKey);
242         // 产生公钥
243         PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
244         // 实例化Signature
245         Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
246         // 初始化Signature
247         signature.initVerify(publicKey);
248         // 更新
249         signature.update(data);
250         // 验证
251         return signature.verify(sign);
252     }
253 
254     public static void main(String[] args) {
255         try {
256             Map<String, String> keyMap = initKey();
257             String publicKeyString = keyMap.get("publicKeyString");
258             String privateKeyString = keyMap.get("privateKeyString");
259             System.out.println("公钥:" + publicKeyString);
260             System.out.println("私钥:" + privateKeyString);
261 
262             // 待加密数据
263             String data = "admin123";
264             // 公钥加密
265             String encrypt = RSAUtil.encryptByPubKey(data, publicKeyString);
266             // 私钥解密
267             String decrypt = RSAUtil.decryptByPriKey(encrypt, privateKeyString);
268 
269             System.out.println("加密前:" + data);
270             System.out.println("加密后:" + encrypt);
271             System.out.println("解密后:" + decrypt);
272         } catch (Exception e) {
273             e.printStackTrace();
274         }
275     }
276 
277 }

 

posted @ 2018-07-21 10:52  xuebusi  阅读(8595)  评论(0编辑  收藏  举报