A方和B方,使用同一对公钥和私钥
A方使用公钥进行加密,发送给B方,B方使用私钥进行解密
B方使用私钥进行加密,发送给A方,A方使用公钥进行解密
所以只需要生成一对公钥和私钥,公钥给A方,私钥给B方即可进行加密通信
pom依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-crypto</artifactId>
<version>5.6.5</version>
</dependency>
KeyPair keyPair = SecureUtil.generateKeyPair(AsymmetricAlgorithm.RSA_ECB_PKCS1.getValue(), 2048);
PublicKey aPublic = keyPair.getPublic();
PrivateKey aPrivate = keyPair.getPrivate();
//new RSA(PrivateKeyStr,PublicKeyStr)
RSA rsa = new RSA(Base64.getEncoder().encodeToString(aPrivate.getEncoded()),
Base64.getEncoder().encodeToString(aPublic.getEncoded()));
String content = "1234567890";
byte[] encrypt = rsa.encrypt(content, KeyType.PrivateKey);
System.out.println("私钥加密后数据:" + Base64.getEncoder().encodeToString(encrypt));
byte[] decrypt = rsa.decrypt(encrypt, KeyType.PublicKey);
System.out.println("公钥解密后数据:" + new String(decrypt, StandardCharsets.UTF_8));
byte[] encrypt1 = rsa.encrypt(content, KeyType.PublicKey);
System.out.println("公钥加密后数据:" + Base64.getEncoder().encodeToString(encrypt1));
byte[] decrypt1 = rsa.decrypt(encrypt1, KeyType.PrivateKey);
System.out.println("私钥解密后数据:" + new String(decrypt1, StandardCharsets.UTF_8));