Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

java rsa加密算法

作者:潇洒一醉   发布日期:2025-06-17   浏览:84

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

解释说明:

  1. 生成密钥对:使用 KeyPairGenerator 类生成一对 RSA 公钥和私钥。这里指定了密钥长度为 2048 位。
  2. 加密方法:使用公钥对消息进行加密,返回加密后的字节数组。
  3. 解密方法:使用私钥对加密后的字节数组进行解密,返回原始消息字符串。
  4. 主函数:演示了如何生成密钥对、加密消息以及解密消息。

通过这个示例代码,你可以了解如何在 Java 中使用 RSA 算法进行加密和解密操作。

上一篇:java遍历数组

下一篇:java取绝对值

大家都在看

java连接数据库的代码

ubuntu 卸载java

java sort用法

java collections.sort

java file类的方法

java 判断

java时间数据类型

java 时间加一天

java demo

java 截取

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站