This is the 19th day of my participation in Gwen Challenge.
What is the RSA
RSA is an encryption method. The RSA encryption algorithm is an asymmetric encryption algorithm.
Asymmetric means that different keys are used for encryption and decryption. In THE RSA algorithm, the encryption key publicKey is public and the decryption key secretKey is saved by the user.
use
Join the lib
The Commons – the codec – 1.15. The jar
RSAEncrypt.java
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
public class RSAEncrypt {
// Encapsulates randomly generated public and private keys
private static Map<Integer, String> keyMap = new HashMap<Integer, String>();
/ / the private key
private static final String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCQD6YnXZiHj/5tl2sPf2i4mzcraFzaCs21SuqPe/G0gfHe1iHyBBrhuaE2t6v3CEkQ3/b2Srop7E6hHp0 tWeZrKPxsNGvla9S9C4PFK2cCHoFh0cT3JjnDeITc/ufCC6UPK+JuRwiqrwVSutd5sQXjU0v3gqNgleRWvV+bayaxeQIDAQAB";
/ / the public key
private static final String PRIVATE_KEY ="MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJAPpiddmIeP/m2Xaw9/aLibNytoXNoKzbVK6o978bSB8d7WIfIEGuG5oTa3q/cISRDf9vZ KuinsTqEenS1Z5mso/Gw0a+Vr1L0Lg8UrZwIegWHRxPcmOcN4hNz+58ILpQ8r4m5HCKqvBVK613mxBeNTS/eCo2CV5Fa9X5trJrF5AgMBAAECgYAecCAEG0N 6CROR5jdJq/rdXnY2prNPoo66Kl0K+f4kzHvlQEslznY7kTQd0or0A/0kIp4Uhc91wicO5eAB0Afd8vg2XnH6AXVnyWtrotlSwJhrdkUdN0+prkhQZDHd9ze 4Hlayv32Emi/jTUf2JrMRszemC3oO4ugnS40jH+AiMQJBAPNVyyJB/AVWN67aDQv7xs1jDkxAWMs7138Kz9TGfp8QVx7BlAd3GIk9NVZlmIYHjzZjaWxTIuk ySc67jo2RMc0CQQCXjx/+6VzUc6oCCDpFhdyIGQ5iEPy1h1dobAG6z3O7KORiRJG8X+R/XUPYAcfA6BlRCZZ6cPUhF/0ATp/TFAJdAkEA5nR2cfd0K8m/6sV wXc0SNyp9PBIlBjWinhsrQiTLfvIG0IYdIATXJALoJO8LSMSYCbaU/ZavFZQe+r/+/mxocQJANReQT84UFOCH17pmH2CrRonwfe4ReM32kr/zQyvVEOVcTAh VPTYiZ3OWhp7pCOzFoZvIORBE7tjmaisg1eKWiQJAL7xxlTqoLJeqXjgx4xqgDM8vf9FWJT+wUQcIVBVwAZ6qz2kETsftDr1sHVRfS30SmRruCBrT2dawEpP KF3KuwA==";
public static void main(String[] args) throws Exception {
// Generate public and private keys
genKeyPair();
// Encrypt the character string
String message = "ABC123abc one two three";
System.out.println("String before encryption:"+ message);
// system.out. println(" randomly generated public key :" + keymap.get (0));
// system.out. println(" randomly generated private key :" + keymap.get (1)); // system.out. println(" randomly generated private key :" + keymap.get (1));
System.out.println("The public key is: + PUBLIC_KEY);
System.out.println("Private key is :" + PRIVATE_KEY);
String messageEn = encrypt(message,PUBLIC_KEY);
System.out.println("Encrypted string :" + messageEn);
String messageDe = decrypt(messageEn,PRIVATE_KEY);
System.out.println("Decrypted string :" + messageDe);
}
/** * Randomly generates a key pair *@throws NoSuchAlgorithmException
*/
public static void genKeyPair(a) throws NoSuchAlgorithmException {
The KeyPairGenerator class is used to generate public and private key pairs based on the RSA algorithm to generate objects
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
// Initialize the key pair generator, the key size is 96-1024 bits
keyPairGen.initialize(1024.new SecureRandom());
// generate a keyPair, stored in keyPair
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // get the private key
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // Get the public key
String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
// Get the private key string
String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
// Save the public and private keys to Map
keyMap.put(0,publicKeyString); //0 indicates a public key
keyMap.put(1,privateKeyString); //1 indicates the private key
}
/** * RSA public key encryption **@paramSTR * Encrypted string *@paramPublicKey * publicKey *@returnCipher *@throwsException * Indicates an Exception during encryption */
public static String encrypt( String str, String publicKey ) throws Exception{
// Base64 encoded public key
byte[] decoded = Base64.decodeBase64(publicKey);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
/ / RSA encryption
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
return outStr;
}
/** * RSA private key decryption **@paramSTR * Encrypted string *@paramPrivateKey * privateKey *@returnInscription *@throwsException * Exception information during decryption */
public static String decrypt(String str, String privateKey) throws Exception{
// 64-bit decoded encrypted string
byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
// Base64 encoded private key
byte[] decoded = Base64.decodeBase64(privateKey);
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
/ / RSA decryption
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, priKey);
String outStr = new String(cipher.doFinal(inputByte));
returnoutStr; }}Copy the code