RSA加密和解密

RSA是一种非对称加密算法.RSA有两个密钥,一个是公开的,称为公开密钥;一个是私密的,称为私密密钥。公开密钥是对大众公开的,私密密钥是服务器私有的,两者不能互推得出。用公开密钥对数据进行加密,私密密钥可解密;私密密钥对数据加密,公开密钥可解密。

一、工具类

 1 import java.io.IOException;
 2 import java.security.KeyFactory;
 3 import java.security.KeyPair;
 4 import java.security.KeyPairGenerator;
 5 import java.security.PrivateKey;
 6 import java.security.PublicKey;
 7 import java.security.spec.PKCS8EncodedKeySpec;
 8 import java.security.spec.X509EncodedKeySpec;
 9 
10 import javax.crypto.Cipher;
11 import sun.misc.BASE64Decoder;
12 import sun.misc.BASE64Encoder;
13  
14  
15 public class RSAUtil {
16     
17     
18     //生成秘钥对
19     public static KeyPair getKeyPair() throws Exception {
20         KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
21         keyPairGenerator.initialize(512); //长度可更改  512 1024 2048 4096
22         KeyPair keyPair = keyPairGenerator.generateKeyPair();
23         return keyPair;
24     }
25     
26     //获取公钥(Base64编码)
27     public static String getPublicKey(KeyPair keyPair){
28         PublicKey publicKey = keyPair.getPublic();
29         byte[] bytes = publicKey.getEncoded();
30         return byte2Base64(bytes);
31     }
32     
33     //获取私钥(Base64编码)
34     public static String getPrivateKey(KeyPair keyPair){
35         PrivateKey privateKey = keyPair.getPrivate();
36         byte[] bytes = privateKey.getEncoded();
37         return byte2Base64(bytes);
38     }
39     
40     //将Base64编码后的公钥转换成PublicKey对象
41     public static PublicKey string2PublicKey(String pubStr) throws Exception{
42         byte[] keyBytes = base642Byte(pubStr);
43         X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
44         KeyFactory keyFactory = KeyFactory.getInstance("RSA");
45         PublicKey publicKey = keyFactory.generatePublic(keySpec);
46         return publicKey;
47     }
48     
49     //将Base64编码后的私钥转换成PrivateKey对象
50     public static PrivateKey string2PrivateKey(String priStr) throws Exception{
51         byte[] keyBytes = base642Byte(priStr);
52         PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
53         KeyFactory keyFactory = KeyFactory.getInstance("RSA");
54         PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
55         return privateKey;
56     }
57     
58     //公钥加密
59     public static byte[] publicEncrypt(byte[] content, PublicKey publicKey) throws Exception{
60         Cipher cipher = Cipher.getInstance("RSA");
61         cipher.init(Cipher.ENCRYPT_MODE, publicKey);
62         byte[] bytes = cipher.doFinal(content);
63         return bytes;
64     }
65     
66     //私钥解密
67     public static byte[] privateDecrypt(byte[] content, PrivateKey privateKey) throws Exception{
68         Cipher cipher = Cipher.getInstance("RSA");
69         cipher.init(Cipher.DECRYPT_MODE, privateKey);
70         byte[] bytes = cipher.doFinal(content);
71         return bytes;
72     }
73     
74     //字节数组转Base64编码
75     public static String byte2Base64(byte[] bytes){
76         BASE64Encoder encoder = new BASE64Encoder();
77         return encoder.encode(bytes);
78     }
79     
80     //Base64编码转字节数组
81     public static byte[] base642Byte(String base64Key) throws IOException{
82         BASE64Decoder decoder = new BASE64Decoder();
83         return decoder.decodeBuffer(base64Key);
84     }
85 }

 

二、测试类

import static org.junit.Assert.*;

import org.junit.Test;

import com.sino.nms.gpon.serviceImpl.SinoLicenseTimeServiceImpl;
import com.sino.nms.otn.utils.RSAUtil;
import com.sino.nms.struts.gpon.bean.User;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
 
 
public class RSA {
 
    @Test
    public void testRSA(){
        try {
            //===============生成公钥和私钥,公钥传给客户端,私钥服务端保留==================
//            生成RSA公钥和私钥,并Base64编码
            KeyPair keyPair = RSAUtil.getKeyPair();
            String publicKeyStr = RSAUtil.getPublicKey(keyPair);
            String privateKeyStr = RSAUtil.getPrivateKey(keyPair);
            System.out.println("RSA公钥Base64编码:" + publicKeyStr);
            System.out.println("RSA私钥Base64编码:" + privateKeyStr);
//            String publicKeyStr = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAK6RG8dNlCP5Jhksr/r3A4Zqm2yPAa+HUDEkXANvos48of7IelwenZBfjXTeZShKrYdyIfAosyU7jkb/4FOmBTMCAwEAAQ==";
//            String privateKeyStr = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEArpEbx02UI/kmGSyv+vcDhmqbbI8B\n"
//+"r4dQMSRcA2+izjyh/sh6XB6dkF+NdN5lKEqth3Ih8CizJTuORv/gU6YFMwIDAQABAkAuEf3Sy5ad\n"
//+"J9P2MOUAxtAXWWtLazJ2sK9pSL8/6OZ+pvJERzNyygSW7FQrLrRcdYljHw+tn1uJDcfz5B0CozUB\n"
//+"AiEA1I5sVwILBIzPBTsJ3/CFdIBQAtfApRlgr5RFChufpYkCIQDSPvYxLR5h0kr6+KmpwmYsHI8E\n"
//+"Ja66UzxshvoNxWbh2wIhAMWgnm7PgXr7iMguOmIyeYL2gm4COCXJULIvQ3nAcVExAiBIovwHjWD7\n"
//+"xt2ky5hCUClggBVhB2vQb8VmcVOewl6DFQIhAI3MJY/xoPqqBbw2cHSXR+iFOYBdumpRLB4GvOUR\n"
//+"isaP";
//            System.out.println("RSA公钥Base64编码:" + publicKeyStr);
//            System.out.println("RSA私钥Base64编码:" + privateKeyStr);
            
            //=================客户端=================
            //public 加密
            String message = "public";
            //将Base64编码后的公钥转换成PublicKey对象
            PublicKey publicKey = RSAUtil.string2PublicKey(publicKeyStr);
            //用公钥加密
            byte[] publicEncrypt = RSAUtil.publicEncrypt(message.getBytes(), publicKey);
            //加密后的内容Base64编码
            String byte2Base64 = RSAUtil.byte2Base64(publicEncrypt);
//            String byte2Base64 = "fcqRB2XPu53meL8dgXFlmv2NBGaZ62JfmExu5KVao4Epr6Q5P0vKOddW6T/cDYtCkKYhQsY06u70XNoUrS34Rg==";
            System.out.println("公钥加密并Base64编码的结果:" + byte2Base64);
            
            
            //##############    网络上传输的内容有Base64编码后的公钥 和 Base64编码后的公钥加密的内容     #################
            
            //===================服务端================
            //将Base64编码后的私钥转换成PrivateKey对象
            PrivateKey privateKey = RSAUtil.string2PrivateKey(privateKeyStr);
            //加密后的内容Base64解码
            byte[] base642Byte = RSAUtil.base642Byte(byte2Base64);
            //用私钥解密
            byte[] privateDecrypt = RSAUtil.privateDecrypt(base642Byte, privateKey);
            //解密后的明文
            System.out.println("解密后的明文: " + new String(privateDecrypt));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
 
}

 

posted @ 2020-08-26 15:29  那时·此刻  阅读(590)  评论(0编辑  收藏  举报
/* 看板娘 */