import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
/**
* @ClassName SHA256WithRSAUtils
* @Description (SHA256WithRSA Signature Utility Class)
* @Author Finlay
* @Date 2021-02-01
* @Version 1.0.0
*/
@Slf4j
public class SHA256WithRSAUtils {
public static final Charset CHARSET = StandardCharsets.UTF_8;
/**
* Key Algorithm
*/
public static final String ALGORITHM_RSA = "RSA";
/**
* RSA Signature Algorithm
*/
public static final String ALGORITHM_RSA_SIGN = "SHA256WithRSA";
public static final int ALGORITHM_RSA_PRIVATE_KEY_LENGTH = 2048;
private SHA256WithRSAUtils() {
}
/**
* RSA Algorithm Public Key Encryption
*
* @param data The plain text string to be encrypted
* @param key RSA public key string
* @return The encrypted cipher text string, encoded in Base64
*/
public static String buildRSAEncryptByPublicKey(String data, String key) {
try {
// Get the public key object through X509-encoded Key instruction
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(key));
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
Key publicKey = keyFactory.generatePublic(x509KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return Base64.getEncoder().encodeToString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET)));
} catch (Exception e) {
throw new RuntimeException("An error occurred while encrypting the string [" + data + "]", e);
}
}
/**
* RSA Algorithm Public Key Decryption
*
* @param data The Base64-encoded cipher text string to be decrypted
* @param key RSA public key string
* @return The decrypted plain text string
*/
public static String buildRSADecryptByPublicKey(String data, String key) {
try {
// Get the public key object through X509-encoded Key instruction
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(key));
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
Key publicKey = keyFactory.generatePublic(x509KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicKey);
return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.getDecoder().decode(data)), CHARSET);
} catch (Exception e) {
throw new RuntimeException("An error occurred while decrypting the string [" + data + "]", e);
}
}
/**
* RSA Algorithm Private Key Encryption
*
* @param data The plain text string to be encrypted
* @param key RSA private key string
* @return The encrypted cipher text string, encoded in Base64
*/
public static String buildRSAEncryptByPrivateKey(String data, String key) {
try {
// Get the private key object through PKCS#8-encoded Key instruction
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(key));
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
return Base64.getEncoder().encodeToString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET)));
} catch (Exception e) {
throw new RuntimeException("An error occurred while encrypting the string [" + data + "]", e);
}
}
/**
* RSA Algorithm Private Key Decryption
*
* @param data The Base64-encoded cipher text string to be decrypted
* @param key RSA private key string
* @return The decrypted plain text string
*/
public static String buildRSADecryptByPrivateKey(String data, String key) {
try {
// Get the private key object through PKCS#8-encoded Key instruction
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(key));
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.getDecoder().decode(data)), CHARSET);
} catch (Exception e) {
throw new RuntimeException("An error occurred while decrypting the string [" + data + "]", e);
}
}
/**
* RSA Algorithm Private Key Digital Signature Generation
*
* @param data The plain text string to be signed
* @param key RSA private key string
* @return The Base64-encoded signed string using RSA private key
*/
public static String buildRSASignByPrivateKey(String data, String key) {
try {
// Get the private key object through PKCS#8-encoded Key instruction
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(key));
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
Signature signature = Signature.getInstance(ALGORITHM_RSA_SIGN);
signature.initSign(privateKey);
signature.update(data.getBytes(CHARSET));
return Base64.getEncoder().encodeToString(signature.sign());
} catch (Exception e) {
throw new RuntimeException("An error occurred while signing the string [" + data + "]", e);
}
}
/**
* RSA Algorithm Public Key Signature Verification
*
* @param data The plain text string that was signed
* @param key RSA public key string
* @param sign The Base64-encoded signature string obtained from RSA signing
* @return true--signature verified, false--signature verification failed
*/
public static boolean buildRSAverifyByPublicKey(String data, String key, String sign) {
try {
// Get the public key object through X509-encoded Key instruction
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(key));
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
Signature signature = Signature.getInstance(ALGORITHM_RSA_SIGN);
signature.initVerify(publicKey);
signature.update(data.getBytes(CHARSET));
return signature.verify(Base64.getDecoder().decode(sign));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* RSA Algorithm for Chunked Encryption/Decryption of Data
*
* @param cipher The javax.crypto.Cipher object initialized with the encryption/decryption mode
* @param opmode The operation mode (Cipher.ENCRYPT_MODE / Cipher.DECRYPT_MODE)
* @return The byte array of encrypted or decrypted data
*/
private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas) {
int maxBlock = 0;
if (opmode == Cipher.DECRYPT_MODE) {
maxBlock = ALGORITHM_RSA_PRIVATE_KEY_LENGTH / 8;
} else {
maxBlock = ALGORITHM_RSA_PRIVATE_KEY_LENGTH / 8 - 11;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] buff;
int i = 0;
try {
while (datas.length > offSet) {
if (datas.length - offSet > maxBlock) {
buff = cipher.doFinal(datas, offSet, maxBlock);
} else {
buff = cipher.doFinal(datas, offSet, datas.length - offSet);
}
out.write(buff, 0, buff.length);
i++;
offSet = i * maxBlock;
}
} catch (Exception e) {
throw new RuntimeException("An error occurred while encrypting/decrypting data with the threshold [" + maxBlock + "]", e);
}
byte[] resultDatas = out.toByteArray();
IOUtils.closeQuietly(out);
return resultDatas;
}
}