• 所需依赖:
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.5.2</version>
</dependency>
  • 代码示例:
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;

public class TestDemo {

public static void main(String[] args) throws Exception {
createRsa();
rsa();
}

static 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);
}

static void rsa() {
String data = "这是一个小例子haha";
String pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCR+01RrLWQSJa25s8yk9dvR664A2zdITUvhGW0UCo31yFg8oPnFr965rFUGmnJhsEo+9pAC8/+qfBoHdC7SksZm7lZn3WTMgGvBIiRjWf1J4xklBqOjjCFlvDzeuESdtwh4OL7d8FLfVtxbedeiT1R9E80a/6e4B5GYefvm4DvfQIDAQAB";
String priKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJH7TVGstZBIlrbmzzKT129HrrgDbN0hNS+EZbRQKjfXIWDyg+cWv3rmsVQaacmGwSj72kALz/6p8Ggd0LtKSxmbuVmfdZMyAa8EiJGNZ/UnjGSUGo6OMIWW8PN64RJ23CHg4vt3wUt9W3Ft516JPVH0TzRr/p7gHkZh5++bgO99AgMBAAECgYATeGYen59zyAq6CFzYTRmt0Oy/xE0vzS8P0GPUQeDvo7Ti/lWTa9hMJxq9sewsIdn/gl/grPKn77iN2nQtlsIfSc+y9fINcttNdxWyYyHVjqzgym0gUAMwQIM5RxOvQ/EB63pI+kaMaUdSvTxV2Lp0k4BPJagEsT4qkfogSCj1bQJBAP0R1v6UFz/bTNw2R9RSjqGzOyaxW8MCL2ZCMJbavdFAK/2b9Rz3dQ978XtxwQqlVQwnIPZMpqwI/2CRsm2aGj8CQQCTrAb1bsifZDMNX1YWU+iaGjH4aSXBvF9HKU4sEpANbLHl2UWoRGJ8aEVTsOPmNAWEwkilfLcPmGblFWOvBa9DAkEAkLCIeZl2CX563VTzkIN7JRxyb1bsHfy72P1zBm0eJetIu4FVjTA2b5nvoSKSumF41K/yep+sk6O5Tx8+Isf+xQJAV2ydxgmrLmn0q3MIlTlh2HGvqcAeQT8TLR7wD7mBnOD/xPLHgWHS6JIWkQCFO5EKv1kCBy75dXslV3Q9Sq3T3wJBANzn8qbTKJKAMVqEQo4/h/qCEDF1vO+EBiyH3oVK4Eu0pR3Zvsz5LKBwCnEZgcPGAY/49bTcp+mmuGe4g/0+yZE=";

// 初始化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);
}