当前位置:网站首页>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();
}
}
}
边栏推荐
- Number of atoms (easy to understand)
- Big meal count (time complexity) -- leetcode daily question
- Wechat applet uploads the data obtained from database 1 to database 2
- WinForm (II) advanced WinForm and use of complex controls
- 微信自定义组件---样式--插槽
- PCB走線到底能承載多大電流
- Tencent X5 kernel initialization failed tbsreaderview not support by:***
- JVM tuning V: JVM tuning tools and tuning practice
- Feynman learning method
- Section II: structural composition characteristics of asphalt pavement (2) structural layer and performance requirements
猜你喜欢

How much current can PCB wiring carry

Deep learning distributed training

Number of atoms (easy to understand)
![[NIPS2021]MLP-Mixer: An all-MLP Architecture for Vision](/img/89/66c30ea8d7969fef76785da1627ce5.jpg)
[NIPS2021]MLP-Mixer: An all-MLP Architecture for Vision

1. use alicloud object OSS (basic)

Wechat applet uploads the data obtained from database 1 to database 2

Zed2 camera calibration -- binocular, IMU, joint calibration

Technology | image motion drive interpretation of first order motion model

微信小程序text内置组件换行符不换行的原因-wxs处理换行符,正则加段首空格

高斯白噪声(white Gaussian noise,WGN)
随机推荐
[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
微信自定义组件---样式--插槽
Recursively process data accumulation
27、移除元素
Cocoapods installation error
Preliminary test of running vins-fusion with zed2 binocular camera
Tightly coupled laser vision inertial navigation slam system: paper notes_ S2D. 66_ ICRA_ 2021_ LVI-SAM
PCB走线到底能承载多大电流
Analyzing while experimenting - memory leakage caused by non static inner classes
jvm调优五:jvm调优工具和调优实战
Poverty has nothing to do with suffering
The programmers of a large factory after 95 were dissatisfied with the department leaders, and were sentenced for deleting the database and running away
Common methods of tool class objectutil
Analysis while experiment - a little optimization of memory leakage in kotlin
如何让灯具智能化,单火、零火智能开关怎么选!
WinForm (I) introduction to WinForm and use of basic controls
高斯白噪声(white Gaussian noise,WGN)
Bert knowledge distillation
Big meal count (time complexity) -- leetcode daily question
MySQL nested sorting: first sort and filter the latest data, and then customize the sorting of this list