Java RSA 公钥加密解密

RSA(Rivest-Shamir-Adleman)是一种非对称加密算法,它使用一对密钥(公钥和私钥)来进行加密和解密。在RSA中,公钥用于加密数据,私钥用于解密数据。在Java中,我们可以使用java.security包中的KeyPairGenerator类来生成RSA密钥对,并使用Cipher类来进行加密和解密操作。

RSA 公钥加密解密示例

下面是一个简单的示例,演示了如何使用RSA公钥加密和解密数据。

生成RSA密钥对

首先,我们需要生成RSA密钥对。下面是一个方法,用于生成RSA密钥对:

import java.security.*;

public class RSAKeyGenerator {
    public static KeyPair generateKeyPair() throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        return keyPairGenerator.generateKeyPair();
    }
}

使用公钥加密数据

接下来,我们使用公钥对数据进行加密:

import java.security.*;

public class RSAEncryption {
    public static byte[] encrypt(byte[] data, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(data);
    }
}

使用私钥解密数据

最后,我们使用私钥对加密后的数据进行解密:

import java.security.*;

public class RSADecryption {
    public static byte[] decrypt(byte[] data, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }
}

类图

下面是一个展示RSAKeyGeneratorRSAEncryptionRSADecryption类之间关系的类图:

classDiagram
    RSAKeyGenerator --|> KeyPairGenerator
    RSAEncryption --|> Cipher
    RSADecryption --|> Cipher

甘特图

以下是一个展示RSA加密解密操作的甘特图:

gantt
    title RSA加密解密操作
    section 生成RSA密钥对
        RSA密钥对生成: done, 2022-01-01, 2022-01-01
    section 公钥加密数据
        公钥加密数据: done, 2022-01-01, 2022-01-02
    section 私钥解密数据
        私钥解密数据: done, 2022-01-02, 2022-01-03

通过以上代码示例和图表,我们可以看到如何在Java中使用RSA公钥进行加密和私钥进行解密。RSA算法在信息安全领域中广泛应用,能够有效保护数据的安全性,为数据传输提供了一种可靠的加密方式。如果您需要在Java中实现数据加密解密功能,RSA算法是一个不错的选择。