增加Rsa加密方法

This commit is contained in:
wanggeng 2022-09-04 15:13:02 +08:00
parent 4d08282c8f
commit 2d0a21e70e

View File

@ -0,0 +1,207 @@
package ink.wgink.util.security;
import org.springframework.util.Base64Utils;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
/**
* @ClassName: RsaUtil
* @Description: Rsa工具
* @Author: wanggeng
* @Date: 2022/9/2 15:00
* @Version: 1.0
*/
public class RsaUtil {
private static final String RSA_ALGORITHM = "RSA";
/**
* 公钥加密
**/
public static byte[] encryptWithPublicKey(final byte[] data, RSAPublicKey publicKey) {
return doRSA(publicKey, Cipher.ENCRYPT_MODE, data);
}
/**
* 公钥解密
**/
public static byte[] decryptByPublicKey(final byte[] data, RSAPublicKey publicKey) {
return doRSA(publicKey, Cipher.DECRYPT_MODE, data);
}
/**
* 私钥加密
**/
public static byte[] encryptWithPrivateKey(byte[] data, RSAPrivateKey privateKey) {
return doRSA(privateKey, Cipher.ENCRYPT_MODE, data);
}
/**
* 私钥解密
**/
public static byte[] decryptWithPrivateKey(byte[] data, RSAPrivateKey privateKey) {
return doRSA(privateKey, Cipher.DECRYPT_MODE, data);
}
private static byte[] doRSA(RSAKey key, int mode, byte[] data) {
try {
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(mode, (Key) key);
return doRSA(cipher, mode, data, key.getModulus().bitLength());
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
private static byte[] doRSA(Cipher cipher, int mode, byte[] data, int keySize) throws IOException, BadPaddingException, IllegalBlockSizeException {
int maxBlock;
if (mode == Cipher.DECRYPT_MODE) {
maxBlock = keySize / 8;
} else {
maxBlock = keySize / 8 - 11;
}
int length = data.length;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
int offset = 0;
byte[] buf;
int i = 0;
// 对数据分段加密
while (length - offset > 0) {
if (length - offset > maxBlock) {
buf = cipher.doFinal(data, offset, maxBlock);
} else {
buf = cipher.doFinal(data, offset, length - offset);
}
baos.write(buf, 0, buf.length);
i++;
offset = i * maxBlock;
}
baos.flush();
return baos.toByteArray();
} finally {
baos.close();
}
}
/**
* 创建公钥
*
* @param publicKey
* @return
*/
public static RSAPublicKey generatePublicKey(String publicKey) {
try {
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64Utils.decodeFromString(publicKey));
return (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
} catch (Exception e) {
throw new IllegalArgumentException("generate publicKey caught error", e);
}
}
/**
* 创建私钥
*
* @param privateKey
* @return
*/
public static RSAPrivateKey generatePrivateKey(String privateKey) {
try {
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64Utils.decodeFromString(privateKey));
return (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
} catch (Exception e) {
throw new IllegalArgumentException("generate privateKey caught error", e);
}
}
/**
* 获取公钥字符串
*
* @param publicKey
* @return
*/
public static String getPublicKeyString(PublicKey publicKey) {
return Base64Utils.encodeToString(publicKey.getEncoded());
}
/**
* 获取私钥字符串
*
* @param privateKey
* @return
*/
public static String getPrivateKeyString(PrivateKey privateKey) {
return Base64Utils.encodeToString(privateKey.getEncoded());
}
/**
* 生成公私钥对
*
* @return
* @throws NoSuchAlgorithmException
*/
public static KeyPair generateKeyPair(int keySize) throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA_ALGORITHM);
keyPairGenerator.initialize(keySize);
return keyPairGenerator.genKeyPair();
}
public static void main(String[] args) throws NoSuchAlgorithmException {
KeyPair keyPair = RsaUtil.generateKeyPair(512);
PublicKey pubKey = keyPair.getPublic();
PrivateKey priKey = keyPair.getPrivate();
String publicKey = RsaUtil.getPublicKeyString(pubKey);
String privateKey = RsaUtil.getPrivateKeyString(priKey);
System.out.println("公钥:" + publicKey);
System.out.println("私钥:" + privateKey);
System.out.println();
String content = "站在大明门前守卫的禁卫军事先没有接到有关的命令。hello world!";
byte[] data = content.getBytes(StandardCharsets.UTF_8);
System.out.println("明文:" + content);
System.out.println("明文大小:" + data.length);
//公钥加密
byte[] encodeBuf = RsaUtil.encryptWithPublicKey(data, RsaUtil.generatePublicKey(publicKey));
System.out.println("密文:" + Base64Utils.encodeToString(encodeBuf));
System.out.println("密文大小:" + encodeBuf.length);
//私钥解密
byte[] decodeBuf = RsaUtil.decryptWithPrivateKey(encodeBuf, RsaUtil.generatePrivateKey(privateKey));
System.out.println("解密后文字:" + new String(decodeBuf, StandardCharsets.UTF_8));
// 私钥加密
System.out.println();
String content2 = "我是中国人";
byte[] data2 = content2.getBytes(StandardCharsets.UTF_8);
System.out.println("明文:" + content2);
// 私钥加密
byte[] privateEncodeBuf = RsaUtil.encryptWithPrivateKey(data2, RsaUtil.generatePrivateKey(privateKey));
System.out.println("密文:" + Base64Utils.encodeToString(privateEncodeBuf));
System.out.println("密文大小:" + privateEncodeBuf.length);
// 公钥解密
byte[] publicDecodeBuf = RsaUtil.decryptByPublicKey(privateEncodeBuf, RsaUtil.generatePublicKey(publicKey));
System.out.println("解密后文字:" + new String(publicDecodeBuf, StandardCharsets.UTF_8));
}
}