chenjiahe
2022-01-19 d4efbe547f8b239ebe04c5a30927ddbff1dfd91d
提交 | 用户 | age
f52692 1 package com.hx.util.rsa;
C 2
3 import org.slf4j.Logger;
4 import org.slf4j.LoggerFactory;
5 import sun.misc.BASE64Decoder;
6 import sun.misc.BASE64Encoder;
7
8 import javax.crypto.Cipher;
9 import java.io.IOException;
10 import java.security.*;
11 import java.security.spec.PKCS8EncodedKeySpec;
12 import java.security.spec.X509EncodedKeySpec;
13
14 public class RSAUtil {
15
16     //log4j日志
17     private static Logger logger = LoggerFactory.getLogger(RSAUtil.class.getName());
18
19     /**生成秘钥对*/
20     public static KeyPair getKeyPair() throws Exception {
21         KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
22         keyPairGenerator.initialize(2048);
23         KeyPair keyPair = keyPairGenerator.generateKeyPair();
24         return keyPair;
25     }
26
27     /**获取公钥(Base64编码)*/
28     public static String getPublicKey(KeyPair keyPair) {
29         PublicKey publicKey = keyPair.getPublic();
30         byte[] bytes = publicKey.getEncoded();
31         return byte2Base64(bytes);
32     }
33
34     /**获取私钥(Base64编码)*/
35     public static String getPrivateKey(KeyPair keyPair) {
36         PrivateKey privateKey = keyPair.getPrivate();
37         byte[] bytes = privateKey.getEncoded();
38         return byte2Base64(bytes);
39     }
40
41     /**将Base64编码后的公钥转换成PublicKey对象*/
42     public static PublicKey string2PublicKey(String pubStr) throws Exception {
43         byte[] keyBytes = base642Byte(pubStr);
44         X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
45         KeyFactory keyFactory = KeyFactory.getInstance("RSA");
46         PublicKey publicKey = keyFactory.generatePublic(keySpec);
47         return publicKey;
48     }
49
50     /**将Base64编码后的私钥转换成PrivateKey对象*/
51     public static PrivateKey string2PrivateKey(String priStr) throws Exception {
52         byte[] keyBytes = base642Byte(priStr);
53         PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
54         KeyFactory keyFactory = KeyFactory.getInstance("RSA");
55         PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
56         return privateKey;
57     }
58
59     /**公钥加密*/
60     public static String publicEncrypt(String content, String publicKey) {
61         try {
62             Cipher cipher = Cipher.getInstance("RSA");
63             cipher.init(Cipher.ENCRYPT_MODE, string2PublicKey(publicKey));
64             byte[] bytes = cipher.doFinal(content.getBytes());
65             return byte2Base64(bytes);
66         } catch (Exception e) {
e10d41 67             //logger.error("公钥加密失败{}", e);
f52692 68         }
C 69         return null;
70     }
71
72     /**私钥解密*/
73     public static String privateDecrypt(String content, String privateKey) {
74         try {
75             Cipher cipher = Cipher.getInstance("RSA");
76             cipher.init(Cipher.DECRYPT_MODE, string2PrivateKey(privateKey));
77             byte[] bytes = cipher.doFinal(base642Byte(content));
78             return new String(bytes);
79         } catch (Exception e) {
e10d41 80             //logger.error("私钥解密失败{}", e);
f52692 81         }
C 82         return null;
83     }
84
85     //字节数组转Base64编码
86     public static String byte2Base64(byte[] bytes) {
87         BASE64Encoder encoder = new BASE64Encoder();
88         return encoder.encode(bytes);
89     }
90
91     //Base64编码转字节数组
92     public static byte[] base642Byte(String base64Key) throws IOException {
93         BASE64Decoder decoder = new BASE64Decoder();
94         return decoder.decodeBuffer(base64Key);
95     }
96
97     public static void main(String[] args) {
98         try {
99
100             KeyPair keyPair = getKeyPair();
101             String publicKeyStr = getPublicKey(keyPair);
102             String privateKeyStr = getPrivateKey(keyPair);
103             System.out.println("publicKey:"+publicKeyStr);
104             System.out.println("privateKey:"+privateKeyStr);
105
106             //String publicKeyStr = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCWY1VKIXGStXOMtSkb2nqV9A4V6MqlTPv8Dg9Sdxm8TZgOYJJxFAjpUOwt0au6q5JDTrslZngg9um1IhNJlRLEySbTvN7Bzeq6XOpZx5w6XRZ+7/o0Ui4YvcYwIHB5DgS5XJnLa3vLqWOk4NAtY0lqC20170mHi5Fmjdak63OTzwIDAQAB";
107             //=================客户端=================
108             String message = "jia_he";
109             //用公钥加密
110             String byte2Base64 = RSAUtil.publicEncrypt(message, publicKeyStr);
111             System.out.println("公钥加密并Base64编码的结果:" + byte2Base64);
112             //===================服务端================
113             //String privateKeyStr = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJZjVUohcZK1c4y1KRvaepX0DhXoyqVM+/wOD1J3GbxNmA5gknEUCOlQ7C3Rq7qrkkNOuyVmeCD26bUiE0mVEsTJJtO83sHN6rpc6lnHnDpdFn7v+jRSLhi9xjAgcHkOBLlcmctre8upY6Tg0C1jSWoLbTXvSYeLkWaN1qTrc5PPAgMBAAECgYAJuQBRm5npHzwKM8glmdllCnNCrVs0lqaP5CTPcw3B485Z15qAHwh4dRff2ndcySzalyN4RoirsOrpH/vZPP8KinIhOT9zcHInWMKEPqGH+twB+c0hS6x2YZFuJqW3+zy56jnUMn3MDjNF5A5N9hD6taP1V+UOqgZvYwwMSCFLkQJBANZtQS2AqahHNjPgjkWcuaG8zXzgbu0VeU+wXDjxR81aLLJBOK6AGe7w5yJnip2w/FqGxPfORcn/bLxyDHOhpQcCQQCzi5zeeiXt1cxeGGqVxNvC51PuSna9YnPs+phiwwGVdAqVdMOJzsThs5EDVhX4eQYIeA4B6PItiPLHsw+6AXD5AkAp/ac/4+xVeeyRaC40T6bCl5ieFc1jPEtPYbgNpqJrAneySLdy5L8vXZnF0QUCMICasb2s0YY1MoH2vVbW5hbNAkEAsCxD5oFQikiI2aN3ojGhuWMnFeB3Fmlueo+ByxaxjSZp5DDIVYZP5W8+0Vk9Aawu4Ux74h/i0g9Yud7XhZo4cQJARyq8WJGDawo65CVcQQ2opbL8LqApr7Co4CAKmV4YFDraY00q9h1Dbj7WO+urJz7XUqbEYG0Yga+37jQAnQHUUQ==";
114             //解密后的明文
115             System.out.println("解密后的明文: " +RSAUtil.privateDecrypt(byte2Base64, privateKeyStr));
116         } catch (Exception e) {
117             e.printStackTrace();
118         }
119     }
120 }