代码描述了如何在Java代码下使用RSA算法进行非对称、分段式、双向加解密的方法, 一对密钥由公钥和私钥组成(可以使用很多对密钥)。私钥可以解密公钥加密的数据,公钥可以解密私钥加密的数据(私钥公钥可以互相加密解密)。
废话不多说直接上测试代码. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
package com.yfr;
/**
* Copyright © CapRobin
* <p>
* Name:RsaTest
* Describe:基于RSA算法实现的非对称分段式双向加解密
* Date:2020-06-17 13:44:47
* Author: YuFarong CapRobin@yeah.net
*/
public class RsaTest {
public static void main(String[] args) {
//生成密钥对
RsaUtil.KeyPairInfo keyObj = RsaUtil.StaticMethod(new RsaUtil());
//公钥(供客户端使用)
String publickey = keyObj.publicKey;
//私钥(服务端保留)
String privatekey = keyObj.privateKey;
System.out.println("本地生成公钥(客户端使用):" + publickey + "\n本地生成私钥(服务端保留):" + privatekey + "\n");
String clientRequestParams = "{\"name\":\"BeJson\",\"url\":\"http://www.bejson.com\",\"page\":88,\"isNonProfit\":true,\"address\":{\"street\":\"科技园路.\",\"city\":\"江苏苏州\",\"country\":\"中国\"},\"links\":[{\"name\":\"Google\",\"url\":\"http://www.google.com\"},{\"name\":\"Baidu\",\"url\":\"http://www.baidu.com\"},{\"name\":\"SoSo\",\"url\":\"http://www.SoSo.com\"}]}";
System.out.println("客户端请求明文参数:\n" + clientRequestParams + "\n");
//1、客户端使用公钥加密后发送服务端
String encipherPublicStr = RsaUtil.encipherPublic(clientRequestParams, publickey, RsaUtil.enSegmentSize);
System.out.println("1、客户端使用公钥加密后发送服务端:\n" + encipherPublicStr + "\n");
//2、服务端接收并使用私钥解密客户端数据后
String decipherPrivateStr = RsaUtil.decipherPrivate(encipherPublicStr, privatekey, RsaUtil.deSegmentSize);
System.out.println("2、服务端接收并使用私钥解密客户端数据后:\n" + decipherPrivateStr + "\n");
//3、服务端使用私钥加密后发送客户端
String encipherPrivateStr = RsaUtil.encipherPrivate(decipherPrivateStr, privatekey, RsaUtil.enSegmentSize);
System.out.println("3、服务端使用私钥加密后发送客户端:\n" + encipherPrivateStr + "\n");
//4、客户端接收并使用公钥解密服务端数据
String decipherPublicStr = RsaUtil.decipherPublic(encipherPrivateStr, publickey, RsaUtil.deSegmentSize);
System.out.println("4、客户端接收并使用公钥解密服务端数据后:\n" + decipherPublicStr + "\n");
}
}
有用得着的朋友可直接查看完整源码
https://download.youkuaiyun.com/download/yfr5734/12529725