RSA非对称加密
时间:2023-06-10 20:07:00
package com.example; import javax.crypto.Cipher; import java.io.ByteArrayOutputStream; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.security.*; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Base64; /** * @author lkz * @describe RSA * @date 2022/1/9 19:58 */ public class RSAUtil { public static final String SIGN_ALGORITHMS = "SHA256WithRSA"; public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8; /** RSA最大加密明文大小 */ private static final int MAX_ENCRYPT_BLOCK = 117; /** RSA最大解密文大小 */ private static final int MAX_DECRYPT_BLOCK = 128; public static KeyPair getKeyPair() throws Exception { KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(1024); return generator.generateKeyPair(); } /** * 签名 * * @param content * @param privateKey * @return */ public static String sign(String content, String privateKey) { try { PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey)); KeyFactory keyf = KeyFactory.getInstance("RSA"); PrivateKey priKey = keyf.generatePrivate(priPKCS8); Signature signature = Signature.getInstance(SIGN_ALGORITHMS); signature.initSign(priKey); signature.update(content.getBytes(DEFAULT_CHARSET)); byte[] signed = signature.sign(); return Base64.getEncoder().encodeToString(signed); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 验签 * * @param content * @param sign * @param publicKey * @return */ public static boolean verify(String content, String sign, String publicKey) { try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); byte[] encodedKey = Base64.getDecoder().decode(publicKey); PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey)); Signature signature = Signature.getInstance(SIGN_ALGORITHMS); signature.initVerify(pubKey); signature.update(content.getBytes(DEFAULT_CHARSET)); return signature.verify(Base64.getDecoder().decode(sign)); } catch (Exception e) { e.printStackTrace(); } return false; } public static PublicKey getPublicKey(String key) throws Exception { byte[] keyBytes = Base64.getDecoder().decode(key); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey = keyFactory.generatePublic(keySpec); return publicKey; } public static PrivateKey getPrivateKey(String key) throws Exception { byte[] keyBytes = Base64.getDecoder().decode(key); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PrivateKey privateKey = keyFactory.generatePrivate(keySpec); return privateKey; } /** * 公钥分段加密 * * @param content * @param publicKeyStr * @return * @throws Exception */ public static String publicEncrpyt(String content, String publicKeyStr) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(1, getPublicKey(publicKeyStr)); byte[] bytes = content.getBytes(DEFAULT_CHARSET); int inputLen = bytes.length; int offSet = 0; byte[] cache; ByteArrayOutputStream out = new ByteArrayOutputStream(); int i = 0; // 加密数据分段 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { cache = cipher.doFinal(bytes, offSet, MAX_ENCRYPT_BLOCK); } else { cache = cipher.doFinal(bytes, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i ; offSet = i * MAX_ENCRYPT_BLOCK; } byte[] encryptedData = out.toByteArray(); out.close(); return Base64.getEncoder().encodeToString(encryptedData); } /** * 私钥分段加密 * * @param content * @param privateKeyStr * @return * @throws Exception */ public static String privateEncrpyt(String content, String privateKeyStr) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(1, getPrivateKey(privateKeyStr)); byte[] bytes = content.getBytes(DEFAULT_CHARSET); int inputLen = bytes.length; int offSet = 0; byte[] cache
ByteArrayOutputStream out = new ByteArrayOutputStream();
int i = 0;
// 对数据分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(bytes, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(bytes, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return Base64.getEncoder().encodeToString(encryptedData);
}
/**
* 私钥分段解密
*
* @param content
* @param privateKeyStr
* @return
* @throws Exception
*/
public static String privateDecrypt(String content, String privateKeyStr) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(2, getPrivateKey(privateKeyStr));
byte[] bytes = Base64.getDecoder().decode(content);
int inputLen = bytes.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(bytes, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(bytes, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return new String(decryptedData);
}
/**
* 公钥分段解密
*
* @param content
* @param publicKeyStr
* @return
* @throws Exception
*/
public static String publicDecrypt(String content, String publicKeyStr) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(2, getPublicKey(publicKeyStr));
byte[] bytes = Base64.getDecoder().decode(content);
int inputLen = bytes.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(bytes, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(bytes, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
out.close();
return out.toString();
}
public static void main(String[] args) throws Exception {
String content = "lkz";
// 公钥
String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDJDb6ICsTaC3jCZrkAHO3UicY0" +
"kwzN/L7stGrfdlaxFwzFbe7/Ak5Vn8va2jPHuBS35TmjQTeqESfTow17rST7ZQuk" +
"RAknMxUMIk4rKY/pgTQxKd5SJjvArj/+dmCvqx5uAhGsRvZO84UZwfQAmJ0Sjrcc" +
"2wdR75+HI/STEcKrTQIDAQAB";
// 私钥
String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMkNvogKxNoLeMJm" +
"uQAc7dSJxjSTDM38vuy0at92VrEXDMVt7v8CTlWfy9raM8e4FLflOaNBN6oRJ9Oj" +
"DXutJPtlC6RECSczFQwiTispj+mBNDEp3lImO8CuP/52YK+rHm4CEaxG9k7zhRnB" +
"9ACYnRKOtxzbB1Hvn4cj9JMRwqtNAgMBAAECgYAFOj5B+0WzBalWJKWawyXL6Okm" +
"ZMxobrHoJajBtqn6YMcMOxeDueOfhlAemJ3QC5E+Vs9w1zlDSr7mWc738ECN3Pmw" +
"4iOSQXmHbWIRPi2LXLOIH7X+gRFTa/7M+uo+DEt5eEM/Jq5vMmI7pdPyggKuAE97" +
"GecaI6ulMuguLIgdYQJBAPARhzERwGDY8n9jaN5Zvt4DuZi9I5TV94gkJHamhqSf" +
"/za38PH7RlUlVc3CG03LUHndPbRwD2uT+MEPL2OMdZcCQQDWZWcD3+fdr1hMKELb" +
"nn+iJ1Q5rN4u3oA8nE5SxgjLX4URjYAmeFkFhVHELj1WDw1ZvIOZo9+LltfrGhwP" +
"0iq7AkAkDk3itcrSAONy9IhElPAQwjh20zlr2jMCNINxepNQWGNpYXkDrvyiPyhC" +
"7ftR1M5ybyMcXZRDUQcUX+Z7KhZjAkBH4O9MqUC/Xg4oWkcwAk+gObdPLtm+tPIh" +
"X/YSYjqIlJm0bNBOFYMjCrODJk2CEMHVGBK26+4CiqwRMku+MiQJAkEA6EDhK4Zj" +
"fBcWX8zggd3knLRKTtqzjKYd2bgcbx5ot3u1fTA0a2A0MN9WYGFlNwoQs+iXNxyY" +
"dE97Cdo7n+4vQg==";
/*String s = publicEncrpyt(content, publicKey);
System.out.println("公钥加密后" + s);
String s1 = privateDecrypt(s, privateKey);
System.out.println("解密后" + s1);*/
// 公钥加密-->私钥签名-->公钥验签-->私钥解密
String s = publicEncrpyt(content, publicKey);
System.out.println("公钥加密后"+s);
//签名 Authorization
String sign = sign(s, privateKey);
System.out.println("私钥签名后:"+sign);
//验签
boolean verify = verify(s, sign, publicKey);
System.out.println("用公钥验签后"+verify);
String s1 = privateDecrypt(s, privateKey);
System.out.println("解密后"+s1 );
}
}