Hutool工具之RSA非对称加解密
时间:2022-11-18 01:30:00
生成密钥对
@Test void createRsa() { // 初始化RSA工具,生成密钥对 RSA rsa = new RSA(); // 获取公钥 String pubKey = rsa.getPublicKeyBase64(); System.out.println("pubKey:" pubKey); // 获取私钥 String priKey = rsa.getPrivateKeyBase64(); System.out.println("priKey:" priKey); }
加解密用例
一般来说,一种方法只使用一个密钥,公钥加密私钥解密,或私钥加密公钥解密。
@Test void rsa() { String data = "这是一个小例子haha"; String pubKey = "xxxxx"; String priKey = "xxxxx"; // 初始化RSA设置工具和私钥 RSA priRsa = new RSA(priKey, null); // 初始化RSA并设置公钥 RSA pubRsa = new RSA(null, pubKey); // 自定义密钥对的初始化RSA工具,但一般不用,因为公共和私钥需要分开 RSA Rsa = new RSA(priKey, pubKey); // 公钥加密 String encodeStr = pubRsa.encryptBase64(data, KeyType.PublicKey); System.out.println("encodeStr by public key:" encodeStr); // 私钥解密 String decodeStr = priRsa.decryptStr(encodeStr, KeyType.PrivateKey); System.out.println("decodeStr by private key:" decodeStr); // 私钥加密 String encodeStr1 = priRsa.encryptBase64(data, KeyType.PrivateKey); System.out.println("encodeStr1 by private key:" encodeStr1); // 公钥解密 String decodeStr1 = pubRsa.decryptStr(encodeStr1, KeyType.PublicKey); System.out.println("decodeStr1 by public key:" decodeStr1); }