174 lines
7.3 KiB
Java
174 lines
7.3 KiB
Java
![]() |
package com.sf.vertx.security;
|
|||
|
|
|||
|
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.interfaces.RSAPrivateKey;
|
|||
|
import java.security.interfaces.RSAPublicKey;
|
|||
|
import java.security.spec.InvalidKeySpecException;
|
|||
|
import java.security.spec.PKCS8EncodedKeySpec;
|
|||
|
import java.security.spec.X509EncodedKeySpec;
|
|||
|
import java.util.Base64;
|
|||
|
import java.util.HashMap;
|
|||
|
import java.util.Map;
|
|||
|
|
|||
|
import javax.crypto.Cipher;
|
|||
|
|
|||
|
import lombok.extern.slf4j.Slf4j;
|
|||
|
|
|||
|
@Slf4j
|
|||
|
public class RSAUtil {
|
|||
|
|
|||
|
public static final String KEY_ALGORITHM = "RSA";
|
|||
|
|
|||
|
private static final String PUBLIC_KEY = "RSAPublicKey";
|
|||
|
|
|||
|
private static final String PRIVATE_KEY = "RSAPrivateKey";
|
|||
|
|
|||
|
// 1024 bits 的 RSA 密钥对,最大加密明文大小
|
|||
|
private static final int MAX_ENCRYPT_BLOCK = 117;
|
|||
|
|
|||
|
// 1024 bits 的 RSA 密钥对,最大解密密文大小
|
|||
|
private static final int MAX_DECRYPT_BLOCK = 128;
|
|||
|
|
|||
|
// 生成密钥对
|
|||
|
public static Map<String, Object> initKey(int keysize) throws Exception {
|
|||
|
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
|
|||
|
// 设置密钥对的 bit 数,越大越安全
|
|||
|
keyPairGen.initialize(keysize);
|
|||
|
KeyPair keyPair = keyPairGen.generateKeyPair();
|
|||
|
|
|||
|
// 获取公钥
|
|||
|
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
|
|||
|
// 获取私钥
|
|||
|
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
|
|||
|
Map<String, Object> keyMap = new HashMap<>(2);
|
|||
|
keyMap.put(PUBLIC_KEY, publicKey);
|
|||
|
keyMap.put(PRIVATE_KEY, privateKey);
|
|||
|
return keyMap;
|
|||
|
}
|
|||
|
|
|||
|
// 获取公钥字符串
|
|||
|
public static String getPublicKeyStr(Map<String, Object> keyMap) {
|
|||
|
// 获得 map 中的公钥对象,转为 key 对象
|
|||
|
Key key = (Key) keyMap.get(PUBLIC_KEY);
|
|||
|
// 编码返回字符串
|
|||
|
return encryptBASE64(key.getEncoded());
|
|||
|
}
|
|||
|
|
|||
|
// 获取私钥字符串
|
|||
|
public static String getPrivateKeyStr(Map<String, Object> keyMap) {
|
|||
|
// 获得 map 中的私钥对象,转为 key 对象
|
|||
|
Key key = (Key) keyMap.get(PRIVATE_KEY);
|
|||
|
// 编码返回字符串
|
|||
|
return encryptBASE64(key.getEncoded());
|
|||
|
}
|
|||
|
|
|||
|
// 获取公钥
|
|||
|
public static PublicKey getPublicKey(String publicKeyString) throws NoSuchAlgorithmException, InvalidKeySpecException {
|
|||
|
byte[] publicKeyByte = Base64.getDecoder().decode(publicKeyString);
|
|||
|
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyByte);
|
|||
|
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
|
|||
|
return keyFactory.generatePublic(keySpec);
|
|||
|
}
|
|||
|
|
|||
|
// 获取私钥
|
|||
|
public static PrivateKey getPrivateKey(String privateKeyString) throws Exception {
|
|||
|
byte[] privateKeyByte = Base64.getDecoder().decode(privateKeyString);
|
|||
|
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyByte);
|
|||
|
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
|
|||
|
return keyFactory.generatePrivate(keySpec);
|
|||
|
}
|
|||
|
|
|||
|
/**
|
|||
|
* BASE64 编码返回加密字符串
|
|||
|
*
|
|||
|
* @param key 需要编码的字节数组
|
|||
|
* @return 编码后的字符串
|
|||
|
*/
|
|||
|
public static String encryptBASE64(byte[] key) {
|
|||
|
return new String(Base64.getEncoder().encode(key));
|
|||
|
}
|
|||
|
|
|||
|
/**
|
|||
|
* BASE64 解码,返回字节数组
|
|||
|
*
|
|||
|
* @param key 待解码的字符串
|
|||
|
* @return 解码后的字节数组
|
|||
|
*/
|
|||
|
public static byte[] decryptBASE64(String key) {
|
|||
|
return Base64.getDecoder().decode(key);
|
|||
|
}
|
|||
|
|
|||
|
/**
|
|||
|
* 公钥加密
|
|||
|
*
|
|||
|
* @param text 待加密的明文字符串
|
|||
|
* @param publicKeyStr 公钥
|
|||
|
* @return 加密后的密文
|
|||
|
*/
|
|||
|
public static String encrypt1(String text, String publicKeyStr) {
|
|||
|
try {
|
|||
|
log.info("明文字符串为:[{}]", text);
|
|||
|
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
|
|||
|
cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(publicKeyStr));
|
|||
|
byte[] tempBytes = cipher.doFinal(text.getBytes("UTF-8"));
|
|||
|
return Base64.getEncoder().encodeToString(tempBytes);
|
|||
|
} catch (Exception e) {
|
|||
|
throw new RuntimeException("加密字符串[" + text + "]时遇到异常", e);
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
/**
|
|||
|
* 私钥解密
|
|||
|
*
|
|||
|
* @param secretText 待解密的密文字符串
|
|||
|
* @param privateKeyStr 私钥
|
|||
|
* @return 解密后的明文
|
|||
|
*/
|
|||
|
public static String decrypt1(String secretText, String privateKeyStr) {
|
|||
|
try {
|
|||
|
// 生成私钥
|
|||
|
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
|
|||
|
cipher.init(Cipher.DECRYPT_MODE, getPrivateKey(privateKeyStr));
|
|||
|
// 密文解码
|
|||
|
byte[] secretTextDecoded = Base64.getDecoder().decode(secretText.getBytes("UTF-8"));
|
|||
|
byte[] tempBytes = cipher.doFinal(secretTextDecoded);
|
|||
|
return new String(tempBytes);
|
|||
|
} catch (Exception e) {
|
|||
|
throw new RuntimeException("解密字符串[" + secretText + "]时遇到异常", e);
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
public static void main(String[] args) throws Exception {
|
|||
|
Map<String, Object> keyMap;
|
|||
|
String cipherText;
|
|||
|
// 原始明文
|
|||
|
String content = "{\"data\":{\"a\":1,\"b\":\"dd\"},\"divideHttpUrl\":{\"company\":{\"aesKey\":\"dadddsdfadfadsfa33323223\"}}}\n"
|
|||
|
+ "";
|
|||
|
|
|||
|
// 生成密钥对
|
|||
|
keyMap = initKey(1024);
|
|||
|
String publicKey = getPublicKeyStr(keyMap);
|
|||
|
log.info("公钥:[{}],长度:[{}]", publicKey, publicKey.length());
|
|||
|
String privateKey = getPrivateKeyStr(keyMap);
|
|||
|
log.info("私钥:[{}],长度:[{}]", privateKey, privateKey.length());
|
|||
|
|
|||
|
publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCuIBxYMYWgIau1BKjTpM/9JhIHRnO4QoaiOrVJk+OFWAJFpFrZoDj3JYQF4ywD8uWOx28EBf+g+U8UIE0pS93IEvm/O47VOwSqSvc5tpXmrxHTVgHSqcXqXkm4+q64c525N5bhUbReXI/CSKU62EH7MWapjHD7vPKGVCwjg8RHCQIDAQAB";
|
|||
|
privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAK4gHFgxhaAhq7UEqNOkz/0mEgdGc7hChqI6tUmT44VYAkWkWtmgOPclhAXjLAPy5Y7HbwQF/6D5TxQgTSlL3cgS+b87jtU7BKpK9zm2leavEdNWAdKpxepeSbj6rrhznbk3luFRtF5cj8JIpTrYQfsxZqmMcPu88oZULCODxEcJAgMBAAECgYAA+yU4/xgPny6Sm97ChoD80k6pzpubAP6URKJMXSQcFBaxtPnZivfU005qNY7qGApXBj69Otw8pC8YvsP+KEsHAmPS78AmzAlh6rojkwl+A1F3a23CyxWKDik/HWsXJ1WSl5ljw/+rW6/38YVfPEKZSOWOTwfYxFWI553j05CVKQJBALkhR60uwGaGpV1ApHwcuaSN6rVQ46D67qmkKG3rLkZJyDziFBabl685UCKiDXqwRoX3UWI0FDqDUhSqoBo/LJUCQQDwyGJiUIAI8bTj6q4+1LxeHMlcJWXaRvOK0BocH+6KpybMKf0R478ziYTtNiaSY45syaDQKofVyE8kzTN37J+lAkAs9EHdcd7ShpudG1dVs/v4U2XNBYlgy84sb2pJ1rPz6XKwJg3Ot5WLvRUSc9tmEWvul/GxMQhAdSb3Ub9y4ChJAkEA7Wj3MO8kvyzr6gpcklEaBkWl+TharBVnTwiPpgmKH6ZeZ9JC2B/SR9OhgG7zK0YEiZlo+bflxVHDT4sQ438pjQJBALIQpdg34BQwWMTx4MxP0Wji51JDZM7h24SReb0RktfsY9s6ZU6mbu3oJNnInD+GQkRJkYNkK4DPrczIxnMpddE=";
|
|||
|
// 加密
|
|||
|
cipherText = encrypt1(content, publicKey);
|
|||
|
log.info("加密后的密文:[{}],长度:[{}]", cipherText, cipherText.length());
|
|||
|
|
|||
|
// 解密
|
|||
|
cipherText = "DaztB3mXoFSZ6wtu4K1mpnFryyeBckeIa0RoLpejCltFj9UZWP3FwTw50SeFlK5dqWE/J0jQUBSRZDJ8qZ2/vnuNqaUxn+JcaUTqlShYV8wbYoqr8tCSFJ0PoHLMdkjS1xFcADqsgRTSsB67dd4qth3K5vU1iQQR30QHPv3I6nY=";
|
|||
|
String plainText = decrypt1(cipherText, privateKey);
|
|||
|
log.info("解密后明文:[{}]", plainText);
|
|||
|
}
|
|||
|
}
|
|||
|
|