原理
Java实战
import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Base64;
/**
* @PROJECT_NAME: demo
* @DESCRIPTION:
*/
public class RESTest {
public static void main(String[] args) throws Exception {
// 获取RSA算法的密钥生成器对象
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
// 设定密钥长度为1024位
keyPairGenerator.initialize(1024);
//生成"密钥对"对象
KeyPair keyPair = keyPairGenerator.generateKeyPair();
//分别获取私钥和公钥对象
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
// 使用标准Base64编码输出公钥and私钥
System.out.println("标准Base64编码输出私钥:"+new String(Base64.getEncoder().encode(privateKey.getEncoded())));
System.out.println("标准Base64编码输出公钥:"+new String(Base64.getEncoder().encode(publicKey.getEncoded())));
// 安全的Base64编码输出公钥and私钥
System.out.println("安全的Base64编码输出私钥:"+org.apache.tomcat.util.codec.binary.Base64.encodeBase64URLSafeString(privateKey.getEncoded()));
System.out.println("安全的Base64编码输出公钥:"+org.apache.tomcat.util.codec.binary.Base64.encodeBase64URLSafeString(publicKey.getEncoded()));
String data = "需要加密的内容";
System.out.println("需要加密的内容:" + data);
//得到要加密内容的数组
byte[] byteData = data.getBytes(StandardCharsets.UTF_8);
// 加密
byte[] encryptText = encrypt(publicKey, byteData);
System.out.println("使用安全Base64编码输出加密后的字符串:" + org.apache.tomcat.util.codec.binary.Base64.encodeBase64URLSafeString(encryptText));
// 解密
byte[] decryptText = decrypt(privateKey, encryptText);
System.out.println("解密后的内容:" + new String(decryptText));
}
public static byte[] encrypt(RSAPublicKey publicKey, byte[] obj) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
//返回加密后的内容
return cipher.doFinal(obj);
}
public static byte[] decrypt(RSAPrivateKey privateKey, byte[] obj) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
//返回解密后的数组
return cipher.doFinal(obj);
}
}
输出结果: