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

java rsa加密解密

作者:傲世,小狂徒   发布日期:2026-07-21   浏览:33

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;

public class RSAExample {

    public static void main(String[] args) throws Exception {
        // 生成RSA密钥对
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(2048); // 密钥长度为2048位
        KeyPair keyPair = keyGen.generateKeyPair();
        PrivateKey privateKey = keyPair.getPrivate();
        PublicKey publicKey = keyPair.getPublic();

        // 要加密的明文
        String originalText = "Hello, RSA!";
        System.out.println("Original Text: " + originalText);

        // 使用公钥加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedBytes = cipher.doFinal(originalText.getBytes());
        System.out.println("Encrypted Text: " + new String(encryptedBytes));

        // 使用私钥解密
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        String decryptedText = new String(decryptedBytes);
        System.out.println("Decrypted Text: " + decryptedText);
    }
}

解释说明:

  1. 生成密钥对:使用 KeyPairGenerator 类生成一个 RSA 密钥对(包括公钥和私钥),密钥长度为 2048 位。
  2. 加密过程:使用公钥对明文进行加密,生成密文。加密时使用了 Cipher 类,并指定了加密模式为 ENCRYPT_MODE
  3. 解密过程:使用私钥对密文进行解密,恢复原始明文。解密时同样使用 Cipher 类,并指定了解密模式为 DECRYPT_MODE

这段代码展示了如何使用 Java 的 javax.cryptojava.security 包来实现 RSA 加密和解密的基本操作。

上一篇:java网络编程技术

下一篇:java快排

大家都在看

java url decode

java判断是windows还是linux

java原始数据类型

java连接数据库的代码

java date类型比较大小

java djl

ubuntu 卸载java

es java api

java常用的设计模式有哪些

java list 查找

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

Laravel 中文站