Home >Java >javaTutorial >How to implement RSA encryption algorithm using java

How to implement RSA encryption algorithm using java

PHPz
PHPzOriginal
2023-09-20 14:33:351541browse

How to implement RSA encryption algorithm using java

How to use Java to implement RSA encryption algorithm

RSA (Rivest-Shamir-Adleman) is an asymmetric encryption algorithm, which is one of the most commonly used encryption algorithms at present. one. This article will introduce how to use Java language to implement the RSA encryption algorithm and provide specific code examples.

  1. Generate key pair

First, we need to generate a pair of RSA keys, which consists of a public key and a private key. The public key can be used to encrypt data and the private key can be used to decrypt data. The following is a code example to generate an RSA key pair:

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;

public class RSAKeyGenerator {
    public static void main(String[] args) {
        try {
            // 创建RSA密钥对生成器
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            // 初始化密钥长度为2048位
            keyPairGenerator.initialize(2048);
            // 生成密钥对
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            // 获取公钥
            String publicKey = Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());
            System.out.println("公钥:" + publicKey);
            // 获取私钥
            String privateKey = Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());
            System.out.println("私钥:" + privateKey);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
}

The above code uses the KeyPairGenerator class to generate an RSA key pair, and uses the Base64 class to combine the public key and The private key is converted into a Base64 encoded string.

  1. Encrypt data using the public key

Next, we will encrypt the data using the public key. The following is a code example that uses an RSA public key to encrypt data:

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;

public class RSAEncryptor {
    public static void main(String[] args) {
        try {
            // 原始数据
            String data = "Hello, world!";
            // 公钥字符串(Base64编码)
            String publicKeyString = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALloSaH+P1Z1Q1A/qs3gejbddklEiROWf2EadwZ68GBgzHk491icoP5x24SBOweiYA+xSqNxxFxSKuWpMu922hMCAwEAAQ==";

            // 将公钥字符串转换为公钥对象
            byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyString);
            PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBytes));

            // 创建RSA密码器
            Cipher cipher = Cipher.getInstance("RSA");
            // 使用公钥进行加密
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] encryptedData = cipher.doFinal(data.getBytes("UTF-8"));

            // 输出加密后的数据(Base64编码)
            String encryptedDataString = Base64.getEncoder().encodeToString(encryptedData);
            System.out.println("加密后的数据:" + encryptedDataString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The above code uses the Cipher class for data encryption. First, convert the public key string into a public key object. Then, create the RSA cipher and initialize it with the public key. Finally, call the doFinal method to encrypt the data and convert the encrypted data into a Base64-encoded string for output.

  1. Use the private key to decrypt the data

Finally, we use the private key to decrypt the encrypted data. The following is a code example of using an RSA private key to decrypt data:

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;

public class RSADecryptor {
    public static void main(String[] args) {
        try {
            // 加密后的数据(Base64编码)
            String encryptedDataString = "3TiTv+AE9FF8NMMFYqx8y/Qz+uzFP/JEcsKGMJP+10r7SmNSDRsjMdK5Mbcz8zvrTaWCrIP4wmUgJhD7ZNoSmQ==";
            // 私钥字符串(Base64编码)
            String privateKeyString = "MIIBOAIBAAJALloSaH+P1Z1Q1A/qs3gejbddklEiROWf2EadwZ68GBgzHk491icoP5x24SBOweiYA+xSqNxxFxSKuWpMu922hMCAwEAAQJAB+hKDm+GF1z5soiqn8DBw7SHf/XRGlxpViWOGTm+LJ6NOkOFH0RRg/cdqq9umemQvR+E6YUcM/NzqxIqJFQyQIhAO2dNYXRKeHNmKXa5vYqWYJIJtyKXXDhLvCRukRz4WFAiEAz2jl8eXSaevi8YMnxRwYnH/OgnesWr0AFr0QemF5sECIBzvqdPKUQzzw3CHjgcTJtX9p9q/MVN4upqvtbJ2WxsNAiAYET666mlWgGIca1ePAbtoB10vhWzDY5YxQ/eTkDssCQIgNoDd1BtSVbWDEUSN/9fCP6UekytJfGFeUZerYB0UlL0=";
            
            // 将私钥字符串转换为私钥对象
            byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyString);
            PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));

            // 创建RSA密码器
            Cipher cipher = Cipher.getInstance("RSA");
            // 使用私钥进行解密
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encryptedDataString));

            // 输出解密后的数据
            String decryptedDataString = new String(decryptedData, "UTF-8");
            System.out.println("解密后的数据:" + decryptedDataString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The above code is similar to the code in the encryption part, except this time the private key is used to decrypt the encrypted data. Likewise, first convert the private key string into a private key object. Then, create the RSA cipher and initialize it with the private key. Finally, call the doFinal method to decrypt the encrypted data and convert the decrypted data into a string for output.

Summary

This article introduces how to use Java language to implement the RSA encryption algorithm and provides specific code examples. By generating a key pair, using the public key to encrypt the data, and using the private key to decrypt the data, we can implement the functions of the RSA encryption algorithm. I hope this article will be helpful to readers about the RSA encryption algorithm.

The above is the detailed content of How to implement RSA encryption algorithm using java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn