Java RSA加密解密实现方法分析【附BASE64 jar包下载】

yizhihongxing

Java RSA加密解密实现方法分析

本文介绍了Java中RSA加密解密的实现方法。主要讲解了如何生成密钥对、如何进行加密解密、如何将密钥序列化和反序列化等操作。同时为了方便实际开发,我们也提供了BASE64 jar包下载链接。

生成密钥对

首先我们需要使用Java中的KeyPairGenerator类来生成RSA密钥对。代码如下:

KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom random = new SecureRandom();
keyPairGenerator.initialize(1024, random);
KeyPair keyPair = keyPairGenerator.generateKeyPair();

在上述代码中,我们使用了RSA算法并且指定了密钥长度为1024位。生成的密钥对包含公钥和私钥,可以通过KeyPair对象获取。

加密解密

在得到密钥对之后,我们可以使用公钥进行加密,使用私钥进行解密。代码如下:

PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
String plainText = "Hello World";
byte[] cipherText = null;
byte[] result = null;
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
cipherText = cipher.doFinal(plainText.getBytes());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
result = cipher.doFinal(cipherText);
System.out.println("PlainText: " + new String(plainText));
System.out.println("CipherText: " + new String(cipherText));
System.out.println("Result: " + new String(result));

在上述代码中,我们使用了Java中的Cipher类进行加密解密操作。使用init方法进行初始化操作,doFinal方法进行加密解密操作。同时在实际开发中,我们一般将加密后的结果进行BASE64编码操作,使其更易于传输和存储。

序列化和反序列化

在实际开发中,我们需要将生成的密钥对进行序列化和反序列化操作以方便存储和传输。代码如下:

// 序列化
FileOutputStream fos = new FileOutputStream("keyPair.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(keyPair);
oos.close();

// 反序列化
FileInputStream fis = new FileInputStream("keyPair.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
KeyPair keyPair = (KeyPair) ois.readObject();
ois.close();

在上述代码中,我们使用了Java中的ObjectOutputStreamObjectInputStream类进行序列化和反序列化操作。将生成的密钥对写入到文件中,然后读取出来即可。

示例

下面是两个简单的示例,第一个示例演示了生成密钥对、加密解密和BASE64编码解码操作;第二个示例演示了序列化和反序列化操作。

示例1:生成密钥对、加密解密和BASE64编码解码操作

import java.security.*;
import javax.crypto.*;
import java.util.Base64;

public class EncryptDecryptExample {
    public static void main(String[] args) throws Exception {
        // 生成密钥对
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        SecureRandom random = new SecureRandom();
        keyPairGenerator.initialize(1024, random);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();

        // 加密
        String plainText = "Hello World";
        byte[] cipherText = null;
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        cipherText = cipher.doFinal(plainText.getBytes());

        // BASE64编码
        String encodedCipherText = Base64.getEncoder().encodeToString(cipherText);
        String encodedPrivateKey = Base64.getEncoder().encodeToString(privateKey.getEncoded());
        String encodedPublicKey = Base64.getEncoder().encodeToString(publicKey.getEncoded());

        // BASE64解码
        byte[] decodedCipherText = Base64.getDecoder().decode(encodedCipherText);
        byte[] decodedPrivateKey = Base64.getDecoder().decode(encodedPrivateKey);
        byte[] decodedPublicKey = Base64.getDecoder().decode(encodedPublicKey);

        // 解密
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] result = cipher.doFinal(decodedCipherText);
        System.out.println("PlainText: " + plainText);
        System.out.println("CipherText: " + encodedCipherText);
        System.out.println("DecodedCipherText: " + new String(decodedCipherText));
        System.out.println("Result: " + new String(result));
    }
}

示例2:序列化和反序列化操作

import java.io.*;
import java.security.*;

public class SerializeDeserializeExample {
    public static void main(String[] args) throws Exception {
        // 生成密钥对
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        SecureRandom random = new SecureRandom();
        keyPairGenerator.initialize(1024, random);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        // 序列化
        FileOutputStream fos = new FileOutputStream("keyPair.ser");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(keyPair);
        oos.close();

        // 反序列化
        FileInputStream fis = new FileInputStream("keyPair.ser");
        ObjectInputStream ois = new ObjectInputStream(fis);
        KeyPair keyPair2 = (KeyPair) ois.readObject();
        ois.close();

        // 验证
        PublicKey publicKey1 = keyPair.getPublic();
        PrivateKey privateKey1 = keyPair.getPrivate();
        PublicKey publicKey2 = keyPair2.getPublic();
        PrivateKey privateKey2 = keyPair2.getPrivate();
        System.out.println("PublicKey equals: " + publicKey1.equals(publicKey2));
        System.out.println("PrivateKey equals: " + privateKey1.equals(privateKey2));
    }
}

BASE64 jar包下载

为了方便使用BASE64操作,我们提供了BASE64 jar包下载链接:

https://github.com/haochenpan/markdown-qna-creator/files/7221178/commons-codec-1.15.jar.zip

将下载下来的jar包导入到项目中即可使用。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java RSA加密解密实现方法分析【附BASE64 jar包下载】 - Python技术站

(0)
上一篇 2023年5月20日
下一篇 2023年5月20日

相关文章

  • android apk反编译到java源码的实现方法

    要将Android APK 反编译成 Java 源码,我们需要使用 apktool 工具和 jd-GUI 工具。 环境准备 安装 JDK 和 Android SDK 下载 apktool 工具,可在 https://ibotpeaches.github.io/Apktool/ 下载最新版本 下载 jd-GUI 工具,可在 https://github.com…

    Java 2023年5月26日
    00
  • springboot如何为web层添加统一请求前缀

    为web层添加统一请求前缀可以通过Spring Boot提供的@RestControllerAdvice注解来实现,具体步骤如下: 步骤1:添加@RestControllerAdvice注解 在包含@Controller注解的基础类上添加@RestControllerAdvice注解,如下所示: @RestControllerAdvice public cl…

    Java 2023年6月16日
    00
  • Java编程生产者消费者实现的四种方法

    Java编程生产者消费者实现的四种方法 生产者消费者问题是指在生产者和消费者之间同步的问题。生产者一直在生产消息,消费者一直在从队列中取走消息,并且队列中只能存储有限的消息。Java中提供了多种实现生产者消费者问题的方法,具体如下: 方法一:使用wait()和notify()方法 这是最基本的一种实现方式。使用wait()方法让生产者线程等待,当消息队列满时…

    Java 2023年5月18日
    00
  • Java 实战练习之网上电商项目的实现

    Java 实战练习之网上电商项目的实现攻略 准备工作 确保已安装JDK,建议使用JDK8以上版本。 确保已安装Maven,用于依赖管理和项目构建。 确认使用的开发工具,如:Eclipse、Intellij IDEA等。 在Github 上创建一个项目并关联到本地。 技术选型 后端框架:Spring Boot 数据库:MySQL ORM框架:MyBatis 前…

    Java 2023年5月18日
    00
  • spring+mybatis实现图书管理系统

    以下是“spring+mybatis实现图书管理系统”的完整攻略。 1. 环境准备 首先需要准备好开发环境,包括以下工具和框架: JDK(Java Development Kit): 用于编译和运行Java程序的开发工具包。 Eclipse(或其他Java开发工具):用于编写和调试Java代码的集成开发环境(IDE)。 Maven:Java项目的构建工具,用…

    Java 2023年6月15日
    00
  • Spring中的spring.factories文件用法(Spring如何加载第三方Bean)

    在Spring中,有一个特殊的配置文件spring.factories,它可以用于指定Spring加载的应用程序上下文中的第三方Bean,而无需创建XML配置文件。下面详细介绍它的用法和加载过程: spring.factories的用法 spring.factories文件位于Spring项目的META-INF目录中,并且遵循标准Java属性文件格式。该文件…

    Java 2023年5月31日
    00
  • PHP、Java des加密解密实例

    PHP、Java des加密解密实例攻略 简介 DES(Data Encryption Standard)是一种对称加密算法,广泛应用于信息安全领域中的数据传输和文件加密。本攻略将介绍使用PHP和Java语言实现的DES加密解密算法。 环境准备 PHP版本:5.3及以上 Java版本:1.6及以上 IDE:PhpStorm、Eclipse、IntelliJ …

    Java 2023年5月19日
    00
  • 一个处理用户登陆的servlet简单实例

    下面我来详细讲解如何实现一个处理用户登录的servlet的完整攻略,包括在Eclipse中的创建项目、编写代码和运行测试等过程。 创建项目和包 首先,我们需要在Eclipse中创建一个Java Web项目,具体步骤如下: 在Eclipse中点击 File > New > Project; 选择“Java Web”项目类型,点击“Next”按钮; …

    Java 2023年6月16日
    00
合作推广
合作推广
分享本页
返回顶部