import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.SignatureException;
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.Arrays;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
public class RSATool {
// *********************************************************************************************
/**
* @param key 用于加密的密钥,可以是公钥也可以是私钥,用公钥加密那叫做加密,用私钥加密那叫做签名
* @param beforeEncryptData 加密前的数据,该数据的字节最多为117
* 注意:此处被加密的数据的数据类型是字节数组类型,所以我们需要记住该字节数组类型的数据是通过哪种解码(utf-8、utf-16等)方式获取的,
* 如此我们才能在解密数据得到字节数组类型的数据后,根据对应的编码(utf-8、utf-16)方式将字节数组类型的数据还原为字符串
* @return 返回加密后的数据
* 注意:注意:加密后的数据我们一般将其进行Base64编码转为字符串,而不是使用utf-8、utf-16等编码方式,如此可以避免字符串中出现具有特殊用途的字符
*/
public static byte[] encrypt(Key key, byte[] beforeEncryptData){
try {
// 创建加密解密工具
Cipher cipher = Cipher.getInstance("RSA");
// 初始化加密解密工具
cipher.init(Cipher.ENCRYPT_MODE, key);
// 正式开始加密解密
return cipher.doFinal(beforeEncryptData);
// 注意:加密完后的数据不要直接转为字符串,因为直接转为字符串后,字符串中有可能会有特殊字符,从而导致再次转为字节数组时,会数据错乱
} catch (NoSuchAlgorithmException e) {
e.printStackTrace(); // 创建加密解密工具失败,因为没有这个加密解密算法
} catch (NoSuchPaddingException e) {
e.printStackTrace(); // 创建加密解密工具失败
} catch (InvalidKeyException e) {
e.
RSA 密钥对生成 加密解密 签名验签
最新推荐文章于 2025-06-14 11:09:34 发布