采用hutool的工具类,自定义公钥私钥的方法
// 应用代码
KeyPair pair = SecureUtil.generateKeyPair("RSA");
String encode = Base64.encode(pair.getPrivate().getEncoded());
System.out.println(encode);// 可以存储永久的私钥 可以不是获取的私钥,自定义字符串也可以
String encode1 = Base64.encode(pair.getPublic().getEncoded());
System.out.println(encode1);// 可以存储永久的公钥 可以不是获取的公钥,自定义字符串也可以
AsymmetricCrypto asymmetricCrypto = new AsymmetricCrypto("RSA", getRSAPrivateKeyBybase64(encode),
getRSAPublidKeyBybase64(encode1));
String s1 = asymmetricCrypto.encryptBase64("你好呀", KeyType.PublicKey);
System.out.println(s1);
byte[] s = asymmetricCrypto.decryptFromBase64(s1, KeyType.PrivateKey);
System.out.println(new String(s));
//---------------------------------------------------------------------------------------------------------
/**
* @desc: 将字符串转换成RSAPublicKey类型
* @date 2020-6-12 11:03:05
* @param
* @return
*/
public static RSAPublicKey getRSAPublidKeyBybase64(String base64s) throws Exception {
X509EncodedKeySpec keySpec = new X509EncodedKeySpec((new BASE64Decoder()).decodeBuffer(base64s));
RSAPublicKey publicKey = null;
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
try {
publicKey = (RSAPublicKey)keyFactory.generatePublic(keySpec);
} catch (InvalidKeySpecException var4) {
}
return publicKey;
}
/**
* @desc: 将字符串转换成RSAPrivateKey类型
* @date 2020-6-12 11:03:01
* @param
* @return
*/
public static RSAPrivateKey getRSAPrivateKeyBybase64(String base64s) throws Exception{
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec((new BASE64Decoder()).decodeBuffer(base64s));
RSAPrivateKey privateKey = null;
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
try {
privateKey = (RSAPrivateKey)keyFactory.generatePrivate(keySpec);
} catch (InvalidKeySpecException var4) {
}
System.out.println(privateKey);
return privateKey;
}
如果非自定义的公钥私钥,那么可以用hutool自动生成公钥私钥,然后利用单例模式,每次都用同一个公钥私钥对象,且无需存储
RsaFactory .java
import cn.hutool.crypto.asymmetric.RSA;
import org.springframework.stereotype.Component;
@Component
public class RsaFactory {
private final RSA rsa = new RSA();
private RsaFactory() {
}
public RSA getinstance(){
return rsa;
}
}
测试
@SpringBootTest
class EncodeServiceImplTest {
@Autowired
RsaFactory rsaFactory;
@Test
void rsa() throws Exception {
RSA rsa = rsaFactory.getinstance();
RSA rsa1 = rsaFactory.getinstance();
RSA rsa2 = rsaFactory.getinstance();
RSA rsa3 = rsaFactory.getinstance();
//获得私钥
System.out.println("私钥" + rsa.getPrivateKeyBase64());
System.out.println("私钥" + rsa1.getPrivateKeyBase64());
rsa.getPrivateKeyBase64();
//获得公钥
System.out.println("公钥" + rsa.getPublicKeyBase64());
rsa.getPublicKeyBase64();
//公钥加密,私钥解密 并且此处利用单例模式获取公钥私钥,模拟项目中多次调用加密解密,公钥私钥不会变 rsa2/rsa3
byte[] encrypt = rsa2.encrypt(StrUtil.bytes("我是一段测试aaaa", CharsetUtil.CHARSET_UTF_8), KeyType.PublicKey);
byte[] decrypt = rsa3.decrypt(encrypt, KeyType.PrivateKey);
System.out.println("我是一段测试aaaa".equals(StrUtil.str(decrypt, CharsetUtil.CHARSET_UTF_8)));
}
}
本文转自 jimolvxing.blog.csdn.net/article/det…,如有侵权,请联系删除。