RSA算法是一种非对称加密算法,公钥和私钥都可以用于加密和解密操作。在RSA算法中,公钥用于加密数据,私钥用于解密数据。
具体来说,使用公钥加密的数据只能使用相应的私钥进行解密。而使用私钥加密的数据则可以使用相应的公钥进行解密。
这种非对称性使得RSA算法非常适合用于加密通信和数字签名等场景,其中公钥通常用于加密传输的数据,而私钥用于解密接收到的数据。这样,只有持有私钥的一方能够解密加密的数据,从而确保了数据的机密性和完整性。
虽然公钥相同,但是每次加密后的密文是不一样的。
package xin.students.exam;import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;public class EncryptionUtils {//公钥private static String publicKeyStr;//私钥private static String privateKeyStr;static {try {KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");keyPairGenerator.initialize(1024);KeyPair keyPair = keyPairGenerator.generateKeyPair();PublicKey publicKey = keyPair.getPublic();PrivateKey privateKey = keyPair.getPrivate();publicKeyStr = Base64.getEncoder().encodeToString(publicKey.getEncoded());privateKeyStr = Base64.getEncoder().encodeToString(privateKey.getEncoded());} catch (NoSuchAlgorithmException e) {e.printStackTrace();}}private static String encryptFun(String plainText, String publicKeyStr) throws Exception {byte[] bytes = Base64.getDecoder().decode(publicKeyStr);X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);KeyFactory keyFactory = KeyFactory.getInstance("RSA");PublicKey publicKey = keyFactory.generatePublic(keySpec);Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.ENCRYPT_MODE, publicKey);byte[] cipherText = cipher.doFinal(plainText.getBytes());return Base64.getEncoder().encodeToString(cipherText);}private static String decryptFun(String cipherText, String privateKeyStr) throws Exception {byte[] bytes = Base64.getDecoder().decode(privateKeyStr);PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);KeyFactory keyFactory = KeyFactory.getInstance("RSA");PrivateKey privateKey = keyFactory.generatePrivate(keySpec);Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.DECRYPT_MODE, privateKey);byte[] plainText = cipher.doFinal(Base64.getDecoder().decode(cipherText));return new String(plainText);}//用于加密public static String encrypt(String plainText, String publicKeyStr) throws Exception {return EncryptionUtils.encryptFun(plainText, publicKeyStr);}//用于解密public static String decrypt(String cipherText, String privateKeyStr) throws Exception {return EncryptionUtils.decryptFun(cipherText, privateKeyStr);}public static void main(String[] args) throws Exception {String plainText = "李义新";// Encrypt the plain text using the public keyString encrypted = EncryptionUtils.encrypt(plainText, EncryptionUtils.publicKeyStr);System.out.println("Encrypted Text: " + encrypted);// Decrypt the encrypted text using the private keyString decrypted = EncryptionUtils.decrypt(encrypted, EncryptionUtils.privateKeyStr);System.out.println("Decrypted Text: " + decrypted);}
}