教你如何实现Java RSA2加密

流程图

flowchart TD
    A(生成RSA公私钥) --> B(使用公钥加密)
    B --> C(使用私钥解密)

整体流程

下面是实现Java RSA2加密的整体流程,包括生成RSA公私钥,使用公钥加密和使用私钥解密。

步骤 描述
生成RSA公私钥 生成公钥和私钥对
使用公钥加密 使用公钥加密数据
使用私钥解密 使用私钥解密加密的数据

生成RSA公私钥

// 引入相关包
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;

// 生成RSA公私钥对
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048); // 初始化密钥长度
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// 获取公钥和私钥
String publicKey = Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());
String privateKey = Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());

使用公钥加密

// 引入相关包
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;

// 获取公钥字节数组
byte[] publicKeyBytes = Base64.getDecoder().decode(publicKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(keySpec);

// 使用公钥加密数据
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedBytes = cipher.doFinal("Hello, RSA!".getBytes());
String encryptedData = Base64.getEncoder().encodeToString(encryptedBytes);

使用私钥解密

// 引入相关包
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;

// 获取私钥字节数组
byte[] privateKeyBytes = Base64.getDecoder().decode(privateKey);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);

// 使用私钥解密数据
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
String decryptedData = new String(decryptedBytes);

通过以上步骤,你就可以实现Java RSA2加密。如果有任何问题,欢迎随时向我提问。祝学习顺利!