当前位置:网站首页>Share an RSA encryption and decryption tool class, including public key encryption, private key decryption, private key encryption, public key decryption, private key signature, public key verificatio
Share an RSA encryption and decryption tool class, including public key encryption, private key decryption, private key encryption, public key decryption, private key signature, public key verificatio
2022-06-11 05:32:00 【Trace】
test :
public static void main(String[] args) {
try {
// Generate public key and private key
Map<String, Object> map = RSAUtil.initKey(2048);
String PrivateKey = RSAUtil.getPrivateKey(map);
String PublicKey = RSAUtil.getPublicKey(map);
System.out.println("PrivateKey:" + PrivateKey);
System.out.println("PublicKey:" + PublicKey);
// Plaintext
String data = "hello rsa!";
// Public key encryption private key decryption
byte[] encData = RSAUtil.encryptByPublicKey(data.getBytes(), PublicKey);
byte[] decData = RSAUtil.decryptByPrivateKey(encData, PrivateKey);
System.out.println(new String(decData));
// Private key encryption public key decryption
byte[] encData1 = RSAUtil.encryptByPrivateKey(data.getBytes(), PrivateKey);
byte[] decData1 = RSAUtil.decryptByPublicKey(encData1, PublicKey);
System.out.println(new String(decData1));
// Private key signature public key signature verification
String signStr = RSAUtil.sign(data.getBytes(), PrivateKey);
boolean verify = RSAUtil.verify(data.getBytes(), PublicKey, signStr);
System.out.println(signStr + verify);
} catch (Exception e) {
// Key mismatch
e.printStackTrace();
}
}
Output
"C:\Program Files\Java\jdk1.8.0_221\bin\java.exe" "-javaagent:D:\Program Files\JetBrains\IntelliJ IDEA 2020.2\lib\idea_rt.jar=52263:D:\Program Files\JetBrains\IntelliJ IDEA 2020.2\bin" -Dfile.encoding=UTF-8 -classpath "E:\javaproj\rsa-demo\bin;C:\Program Files\Java\jdk1.8.0_221\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_221\jre\lib\rt.jar;E:\javaproj\rsa-demo\lib\commons-codec-1.10.jar" com.wjs.rsaDemo.RSAUtil
PrivateKey:MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC4RzF0kVMItCUy2brRPpl9sv1zdza0Xn5/kAUqE7Ykm3zU92tFZpCX9YrsKp4cxEC8uwotEibE3qbh8lGN+G1pa55t7YmX0lOW6L7x5z5eMSx2J8oQ7qpAA3pPRquZg85ke8thJJJpnCLgYJAZhlTSgKvBzwECy998RpV8eqRDlr60BH+GcgCa5yLyO7O/l9hzTgipkCkdXKx4X74LilfADFPhVgC5y/03RQnFXcmrfjbOlLxIyef4Z56WeXo7zAuxSG2YR1xyt3rupxF1uIBn8XbuL7jdt4wgQF0JVxmGB1SWM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GBAMMKuwTj1wh8CCFIjdePpImhQguh530pVgShqujXxB8W2l0wUlxjsrLG/guKNcgPfHLHVwpis0YuIBpwzk04hj4psnAYPu5wGl6KceLYdfRYrJoQbhrc08xPogc4DhQOatVHn9kKI//wpR3a59yPyY3tMd18e9bNgsW4CPT7Tmxr
PublicKey:MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuEcxdJFTCLQlMtm60T6ZfbL9c3c2tF5+f5AFKhO2JJt81PdrRWaQl/WK7CqeHMRAvLsKLRImxN6m4fJRjfhtaWuebe2Jl9JTlui+8ec+XjEsdifKEO6qQAN6T0armYPOZHvLYSSSaZwi4GCQGYZU0oCrwc8BAsvffEaVfHqkQ5a+tAR/hnIAmuci8juzv5fYc04IqZApHVyseF++C4pXwAxT4VYAucv9N0UJxV3Jq342zpS8SMnn+Geelnl6O8wLsUhtmEdccrd67qcRdbiAZ/F27i+43beMIEBdCVcZhgdUljMxu69y8sTyG5xDAIgP/4jUlHygjUbmTiMmpcjmkQIDAQAB
hello rsa!
hello rsa!
CCnsnslB08p1E4aMdK5BNi9ZwRkGPj1bvnMrIn0LNsiTmc4r06rE5lbB9Tz3C9W50jnQBHyMI6TBFkU6cyUeDAAFzHI/PLgKw2hCd76DX0o7BuknNTUZ6yuHmQQEyFp0CMrb1sUkKtUv0aq+4nqJwGbZ9v3LLoPmKl/oD/LYD0tciWBkskoGOKxF2izosY71lWyFZV6OtQYQbdo39TcHJh9eeqM1/4JeLFm2+wnnOF+1j2AR+Ki1WNeAtXcDAQHqz1GmKgg46FlycD/xlxzoWgega6BpjyiHIh1vIMK24PztP9PwibmsZliBUB3V4+iyaTTVXTUkatFo0RALNs902A==true
Process finished with exit code 0
Tool class RSAUtil
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.*;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
/** * RSA encryption Tool class */
public abstract class RSAUtil {
public static final String KEY_ALGORITHM = "RSA";
public static final String SIGNATURE_ALGORITHM = "SHA1WithRSA";
public static final String PUBLIC_KEY = "RSAPublicKey";
public static final String PRIVATE_KEY = "RSAPrivateKey";
public static String sign(byte[] data, String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException, SignatureException, InvalidKeyException {
// Decryption by base64 Encoded private key
byte[] keyBytes = Base64.getDecoder().decode(privateKey);
// structure PKCS8EncodedKeySpec object
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
// KEY_ALGORITHM Specified encryption algorithm
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
// Take private key object
PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
// Use private key to generate digital signature for information
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(priKey);
signature.update(data);
return Base64.getEncoder().encodeToString(signature.sign());
}
/** * Verify digital signature */
public static boolean verify(byte[] data, String publicKey, String sign)
throws Exception {
// Decryption by base64 Encoded public key
byte[] keyBytes = Base64.getDecoder().decode(publicKey);
// structure X509EncodedKeySpec object
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
// KEY_ALGORITHM Specified encryption algorithm
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
// Take the public key object
PublicKey pubKey = keyFactory.generatePublic(keySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(pubKey);
signature.update(data);
// Verify that the signature is OK
return signature.verify(Base64.getDecoder().decode(sign));
}
/** * Decrypt <br> * Decrypt with private key */
public static byte[] decryptByPrivateKey(byte[] data, String key)
throws Exception {
byte[] decryptedData = null;
// Decrypt the key
byte[] keyBytes = Base64.getDecoder().decode(key);
// Get private key
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
// Decrypt data
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
int maxDecryptBlockSize = getMaxDencryptBytesByPrivate(keyFactory, privateKey);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
try {
int dataLength = data.length;
for (int i = 0; i < dataLength; i += maxDecryptBlockSize) {
int decryptLength = Math.min(dataLength - i, maxDecryptBlockSize);
byte[] doFinal = cipher.doFinal(data, i, decryptLength);
bout.write(doFinal);
}
decryptedData = bout.toByteArray();
} finally {
bout.close();
}
return decryptedData;
}
/** * take Base64 The encoded ciphertext is decrypted into a string */
public static String decryptByPrivateKeyToString(String base64Str, String key) throws Exception {
byte[] data = Base64.getDecoder().decode(base64Str);
byte[] oriData = decryptByPrivateKey(data, key);
return new String(oriData);
}
/** * Get the maximum data byte length that can be encrypted by public key encryption */
private static int getMaxEncryptBytesByPublicKey(KeyFactory keyFactory, Key key) throws InvalidKeySpecException {
return getPublicKeyBitLength(keyFactory, key) / 8 - 11;
}
/** * Get the byte length of each block decrypted by the public key */
private static int getMaxDencryptBytesByPrivate(KeyFactory keyFactory, Key key) throws InvalidKeySpecException {
return getPrivateKeyBitLength(keyFactory, key) / 8;
}
/** * Get the maximum data byte length that can be encrypted by public key encryption */
private static int getMaxEncryptBytesByPrivate(KeyFactory keyFactory, Key key) throws InvalidKeySpecException {
return getPrivateKeyBitLength(keyFactory, key) / 8 - 11;
}
/** * Get the byte length of each block decrypted by the public key */
private static int getMaxDencryptBytesByPublicKey(KeyFactory keyFactory, Key key) throws InvalidKeySpecException {
return getPublicKeyBitLength(keyFactory, key) / 8;
}
/** * Get the byte length of the public key */
private static int getPublicKeyBitLength(KeyFactory keyFactory, Key key) throws InvalidKeySpecException {
RSAPublicKeySpec publicKeySpec = keyFactory.getKeySpec(key, RSAPublicKeySpec.class);
return publicKeySpec.getModulus().bitLength();
}
/** * Get the byte length of the private key */
private static int getPrivateKeyBitLength(KeyFactory keyFactory, Key key) throws InvalidKeySpecException {
RSAPrivateKeySpec publicKeySpec = keyFactory.getKeySpec(key, RSAPrivateKeySpec.class);
return publicKeySpec.getModulus().bitLength();
}
/** * Decrypt <br> * Decryption with public key */
public static byte[] decryptByPublicKey(byte[] data, String key)
throws Exception {
byte[] decryptedData = null;
// Decrypt the key
byte[] keyBytes = Base64.getDecoder().decode(key);
// Get the public key
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicKey = keyFactory.generatePublic(x509KeySpec);
// Decrypt data
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicKey);
int maxDecryptBlockSize = getMaxDencryptBytesByPublicKey(keyFactory, publicKey);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
try {
int dataLength = data.length;
for (int i = 0; i < dataLength; i += maxDecryptBlockSize) {
int decryptLength = Math.min(dataLength - i, maxDecryptBlockSize);
byte[] doFinal = cipher.doFinal(data, i, decryptLength);
bout.write(doFinal);
}
decryptedData = bout.toByteArray();
} finally {
bout.close();
}
return decryptedData;
}
/** * encryption <br> * Encrypt with a public key */
public static byte[] encryptByPublicKey(byte[] data, String key)
throws Exception {
byte[] encryptedData = null;
// Decrypt the public key
byte[] keyBytes = Base64.getDecoder().decode(key);
// Get the public key
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicKey = keyFactory.generatePublic(x509KeySpec);
// Encrypt data
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
int maxEncryptBlockSize = getMaxEncryptBytesByPublicKey(keyFactory, publicKey);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
try {
int dataLength = data.length;
for (int i = 0; i < data.length; i += maxEncryptBlockSize) {
int encryptLength = Math.min(dataLength - i, maxEncryptBlockSize);
byte[] doFinal = cipher.doFinal(data, i, encryptLength);
bout.write(doFinal);
}
encryptedData = bout.toByteArray();
} finally {
bout.close();
}
return encryptedData;
}
/** * encryption <br> * Encrypt with private key */
public static byte[] encryptByPrivateKey(byte[] data, String key)
throws Exception {
byte[] encryptedData = null;
// Decrypt the key
byte[] keyBytes = Base64.getDecoder().decode(key);
// Get private key
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
// Encrypt data
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
int maxEncryptBlockSize = getMaxEncryptBytesByPrivate(keyFactory, privateKey);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
try {
int dataLength = data.length;
for (int i = 0; i < data.length; i += maxEncryptBlockSize) {
int encryptLength = Math.min(dataLength - i, maxEncryptBlockSize);
byte[] doFinal = cipher.doFinal(data, i, encryptLength);
bout.write(doFinal);
}
encryptedData = bout.toByteArray();
} finally {
bout.close();
}
return encryptedData;
}
/** * Get private key */
public static String getPrivateKey(Map<String, Object> keyMap)
throws Exception {
Key key = (Key) keyMap.get(PRIVATE_KEY);
return Base64.getEncoder().encodeToString(key.getEncoded());
}
/** * Get the public key */
public static String getPublicKey(Map<String, Object> keyMap)
throws Exception {
Key key = (Key) keyMap.get(PUBLIC_KEY);
return Base64.getEncoder().encodeToString(key.getEncoded());
}
/** * Initialize key */
public static Map<String, Object> initKey() throws Exception {
return initKey(1024);
}
public static Map<String, Object> initKey(int keySize) throws Exception {
KeyPairGenerator keyPairGen = KeyPairGenerator
.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(keySize);
KeyPair keyPair = keyPairGen.generateKeyPair();
// Public key
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
// Private key
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
Map<String, Object> keyMap = new HashMap<String, Object>(2);
keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);
return keyMap;
}
/** * test */
public static void main(String[] args) {
try {
// Generate public key and private key
Map<String, Object> map = RSAUtil.initKey(2048);
String PrivateKey = RSAUtil.getPrivateKey(map);
String PublicKey = RSAUtil.getPublicKey(map);
System.out.println("PrivateKey:" + PrivateKey);
System.out.println("PublicKey:" + PublicKey);
// Plaintext
String data = "hello rsa!";
// Public key encryption private key decryption
byte[] encData = RSAUtil.encryptByPublicKey(data.getBytes(), PublicKey);
byte[] decData = RSAUtil.decryptByPrivateKey(encData, PrivateKey);
System.out.println(new String(decData));
// Private key encryption public key decryption
byte[] encData1 = RSAUtil.encryptByPrivateKey(data.getBytes(), PrivateKey);
byte[] decData1 = RSAUtil.decryptByPublicKey(encData1, PublicKey);
System.out.println(new String(decData1));
// Private key signature public key signature verification
String signStr = RSAUtil.sign(data.getBytes(), PrivateKey);
boolean verify = RSAUtil.verify(data.getBytes(), PublicKey, signStr);
System.out.println(signStr + verify);
} catch (Exception e) {
// Key mismatch
e.printStackTrace();
}
}
}
边栏推荐
- Take stock of the AI black technologies in the Beijing Winter Olympic Games, and Shenzhen Yancheng Technology
- lower_ Personal understanding of bound function
- Introduction to coordinate system in navigation system
- 使用acme.sh自动申请免费SSL证书
- Handle double quotation mark escape in JSON string
- Share 𞓜 jointly pre training transformers on unpaired images and text
- MySQL string to array, merge result set, and convert to array
- 22、生成括号
- 初步了解多任务学习
- jvm调优六:GC日志分析和常量池详解
猜你喜欢

Cocoapods installation error

Take stock of the AI black technologies in the Beijing Winter Olympic Games, and Shenzhen Yancheng Technology

BERT知识蒸馏

Linked list de duplication

mysql字符串转数组,合并结果集,转成数组

Analyze while doing experiments -ndk article -jni uses registernatives for explicit method registration

Vins fusion GPS fusion part

PCB走線到底能承載多大電流

微信小程序,购买商品属性自动换行,固定div个数,超出部分自动换行

Sealem finance builds Web3 decentralized financial platform infrastructure
随机推荐
Poverty has nothing to do with suffering
Analyzing while experimenting - memory leakage caused by non static inner classes
Preliminary understanding of multi task learning
Use acme SH automatically apply for a free SSL certificate
Some details about memory
[NIPS2021]MLP-Mixer: An all-MLP Architecture for Vision
Number of atoms (easy to understand)
Linked list de duplication
PCB走線到底能承載多大電流
English digital converter
[project - what are the supporting materials in the annexes? (18 kinds of 2000 word summary)] project plan of innovation and entrepreneurship competition and supporting materials of Challenge Cup entr
PageHelper page 2 collections in the same interface
jvm调优六:GC日志分析和常量池详解
Section I: classification and classification of urban roads
How to make lamps intelligent? How to choose single fire and zero fire intelligent switches!
Bert knowledge distillation
KD-Tree and LSH
【项目篇- 附件佐证材料放什么?(十八种两千字总结)】创新创业竞赛项目计划书、挑战杯创业计划竞赛佐证材料
Get the third-party interface
Opencv learning path (2-4) -- Deep parsing cvtcolor function