温馨提示×

Java RSA算法怎么实现

小亿
91
2023-10-26 02:28:38
栏目: 编程语言

Java中可以使用Java内置的加密库javax.crypto来实现RSA算法。

下面是一个简单的RSA加密和解密的示例代码:

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RSAExample {

    public static void main(String[] args) throws Exception {
        String originalText = "Hello, RSA!";

        // 生成公私密钥对
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();

        // 使用公钥加密数据
        byte[] encryptedBytes = encrypt(originalText, publicKey);

        // 使用私钥解密数据
        String decryptedText = decrypt(encryptedBytes, privateKey);

        System.out.println("Original Text: " + originalText);
        System.out.println("Encrypted Text: " + Base64.getEncoder().encodeToString(encryptedBytes));
        System.out.println("Decrypted Text: " + decryptedText);
    }

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

    public static String decrypt(byte[] encryptedBytes, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes);
    }
}

在这个示例代码中,首先生成一个2048位的RSA公私钥对,然后使用公钥加密原始文本,再使用私钥解密加密后的数据。最后输出原始文本、加密后的文本和解密后的文本。

需要注意的是,这里使用了Base64编码来将加密后的文本以字符串的形式输出,方便观察。在实际应用中,可以根据需要选择合适的方式来存储和传输加密后的数据。

0