import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
public class RSADemo {
    // 生成密钥对
    public static KeyPair generateKeyPair() throws Exception {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(2048); // 指定密钥长度
        return keyGen.generateKeyPair();
    }
    // 加密方法
    public static byte[] encrypt(PublicKey publicKey, String message) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(message.getBytes());
    }
    // 解密方法
    public static String decrypt(PrivateKey privateKey, byte[] encrypted) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return new String(cipher.doFinal(encrypted));
    }
    public static void main(String[] args) {
        try {
            // 生成密钥对
            KeyPair keyPair = generateKeyPair();
            PublicKey publicKey = keyPair.getPublic();
            PrivateKey privateKey = keyPair.getPrivate();
            // 原始消息
            String originalMessage = "Hello, RSA!";
            System.out.println("Original Message: " + originalMessage);
            // 加密消息
            byte[] encrypted = encrypt(publicKey, originalMessage);
            System.out.println("Encrypted Message: " + new String(encrypted));
            // 解密消息
            String decrypted = decrypt(privateKey, encrypted);
            System.out.println("Decrypted Message: " + decrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}KeyPairGenerator 类生成一对 RSA 公钥和私钥。这里指定了密钥长度为 2048 位。通过这个示例代码,你可以了解如何在 Java 中使用 RSA 算法进行加密和解密操作。
上一篇:java遍历数组
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站