import com.google.common.collect.Maps;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
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.Map;
import java.util.UUID;
/**
* RSA plus decryption tool class
*
* @Author Wangqinglong01
*/
@Slf4j
public class RSAUtil {
private static final String RSA = "RSA";
private static final String PRIVATE_KEY = "privateKey";
private static final String PUBLIC_KEY = "publicKey";
private static final String ALGORITHM = "MD5withRSA";
private static final int ZERO = 0;
/**
* RSA's maximum encryption text size
*/
private static final int MAX_ENCRYPT_BLOCK = 117;
/**
* RSA's maximum decryption ciphertext size
*/
private static final int MAX_DECRYPT_BLOCK = 128;
/**
* Public key and private key used for packaging randomly
*/
private final static Map<String, String> KEY_MAP = Maps.newHashMap();
/**
* Get the public key
*/
public static String getPublicKey() {
if (KEY_MAP.size() == ZERO) {
genKeyPair();
}
return KEY_MAP.get(PUBLIC_KEY);
}
/**
* Get private key
*/
public static String getPriKey() {
if (KEY_MAP.size() == ZERO) {
genKeyPair();
}
return KEY_MAP.get(PRIVATE_KEY);
}
@SneakyThrows
public static void genKeyPair() {
// keypairgenrator class is used to generate public key and private key pairs, based on the RSA algorithm generation object
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(RSA);
// Initialize the key-generator, the key size is 96-1024 bits
keyPairGen.initialize(1024, new SecureRandom());
// generate a key pair, store in keypair
KeyPair keyPair = keyPairGen.generateKeyPair();
// get the private key
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
// Get the public key
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
// Get the private key string
String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
// Save the public key and private key to MAP
// 0 means the public key
KEY_MAP.put(PUBLIC_KEY, publicKeyString);
// 1 means private key
KEY_MAP.put(PRIVATE_KEY, privateKeyString);
}
/**
* RSA public key encryption (field length cannot exceed 117 bytes)
*
* @param Str encrypted string
* @param PublicKey Public Key
* @Return ciphertext
* @throws Exception in the process of encryption process
*/
public static String encrypt(String str, String publicKey) throws Exception {
// base64 encoding 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);
return Base64.encodeBase64String(cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)));
}
/**
* RSA private key decryption (field length cannot exceed 128 bytes)
*
* @param Str encrypted string
* @param PrivateKey private key
* @Return inscription
* @throws Exception Decrypting Disciplinary Information
*/
public static String decrypt(String str, String privateKey) throws Exception {
// 64 -bit decoding and encrypted string
byte[] inputByte = Base64.decodeBase64(str.getBytes(StandardCharsets.UTF_8));
// base64 encoding 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);
return new String(cipher.doFinal(inputByte));
}
/*=========================================== ========================*/
/**
* RSA encryption (segment)
*
* @param Data to be encrypted data
* @param PubKey Public Key
* @Return encrypted data
*/
public static String encryptSegment(String data, String pubKey) throws Exception {
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
byte[] decodedKey = Base64.decodeBase64(pubKey.getBytes());
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
int inputLen = data.getBytes().length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offset = ZERO;
byte[] cache;
int i = ZERO;
// Encryption of data segments
while (inputLen - offset > ZERO) {
if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
}
out.write(cache, ZERO, cache.length);
i++;
offset = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
// Get the encrypted content and use Base64 to encode it, and use UTF-8 as the standard to be transformed into a string
// The encrypted string
return Base64.encodeBase64String(encryptedData);
}
/**
* RSA decryption (segment)
*
* @param Data to be deprived of the secret data
* @param prikey private key
* @Return Decodily data
*/
public static String decryptSegment(String data, String priKey) throws Exception {
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
byte[] decodedKey = Base64.decodeBase64(priKey.getBytes());
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] dataBytes = Base64.decodeBase64(data);
int inputLen = dataBytes.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offset = ZERO;
byte[] cache;
int i = ZERO;
// Decrypt the data segmentation
while (inputLen - offset > ZERO) {
if (inputLen - offset > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
}
out.write(cache, ZERO, cache.length);
i++;
offset = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
// The content after decryption
return new String(decryptedData, StandardCharsets.UTF_8);
}
/*========================================== =======================*/
/**
* sign
*
* @param Data to be signed data
* @param PrivateKey private key
* @Return signature
*/
public static String sign(String data, PrivateKey privateKey) throws Exception {
byte[] keyBytes = privateKey.getEncoded();
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PrivateKey key = keyFactory.generatePrivate(keySpec);
Signature signature = Signature.getInstance(ALGORITHM);
signature.initSign(key);
signature.update(data.getBytes());
return new String(Base64.encodeBase64(signature.sign()));
}
/**
* Check
*
* @param srcdata raw string
* @param PublicKey Public Key
* @param Sign signature
* @Return Whether to check the visa
*/
public static boolean verify(String srcData, PublicKey publicKey, String sign) throws Exception {
byte[] keyBytes = publicKey.getEncoded();
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PublicKey key = keyFactory.generatePublic(keySpec);
Signature signature = Signature.getInstance(ALGORITHM);
signature.initVerify(key);
signature.update(srcData.getBytes());
return signature.verify(Base64.decodeBase64(sign.getBytes()));
}
public static void main(String[] args) {
try {
// Generate key pair
genKeyPair();
// RSA encryption
StringBuilder builder = new StringBuilder();
do {
builder.append(UUID.randomUUID().toString());
} while (builder.toString().length() <= 100);
String data = builder.toString();
System.out.println("Data length:" + data.length());
// ======================= Use segments plus decryption ============ =========
String encryptSegment = encryptSegment(data, getPublicKey());
System.out.println("Cousin after encryption:" + encryptSegment);
System.out.println("After encrypted content length:" + encryptSegment.length());
// RSA decryption
String decryptSegment = decryptSegment(encryptSegment, getPriKey());
System.out.println("After decryption, the content:" + decryptSegment);
System.out.println("The content length after decryption:" + decryptSegment.length());
// ======================= Use conventional decryption ============= =========
String encrypt = encrypt(data, getPublicKey());
System.out.println("Cousin after encryption:" + encrypt);
System.out.println("After encrypted content length:" + encrypt.length());
// RSA decryption
String decrypt = decrypt(encrypt, getPriKey());
System.out.println("After decryption, the content:" + decrypt);
System.out.println("The content length after decryption:" + decrypt.length());
} catch (Exception e) {
e.printStackTrace();
System.out.print("Adding Deconsion Abnormal");
}
}
}
Spring Boot’s default scanning path
2023-01-03
ES