Class RsaUtil
java.lang.Object
com.sure.tool.crypto.RsaUtil
RSA 加解密工具类(RSA/ECB/OAEPWithSHA-256AndMGF1Padding),无状态静态方法、线程安全,参考 Hutool 的
RSA 设计。
安全设计(2026-09-10 升级,随 CodeQL 安全扫描告警修复):
- 采用 OAEP-SHA256 填充(替代 PKCS#1 v1.5,消除 Bleichenbacher padding oracle 风险);
- 密钥长度强制不低于 2048 位(拒绝 1024 及以下的弱密钥)。
- Since:
- 0.1.0
- Author:
- suretool
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final int默认密钥位数static final int允许的最小密钥位数(低于此值直接拒绝,弱密钥) -
Method Summary
Modifier and TypeMethodDescriptionstatic byte[]RSA 解密(OAEP-SHA256)。static StringdecryptBase64(String base64, PrivateKey privateKey) 私钥解密 Base64 密文。static StringdecryptHex(String hex, PrivateKey privateKey) 私钥解密十六进制密文。static byte[]RSA 加密(OAEP-SHA256)。static StringencryptBase64(String data, PublicKey publicKey) 公钥加密为 Base64。static StringencryptHex(String data, PublicKey publicKey) 公钥加密为十六进制。static KeyPair生成密钥对(2048 位)。static KeyPairgenerateKeyPair(int keySize) 生成密钥对。static StringgetPrivateKeyBase64(KeyPair keyPair) 私钥转 Base64(PKCS#8)。static StringgetPublicKeyBase64(KeyPair keyPair) 公钥转 Base64(X.509)。static PrivateKeyparsePrivateKey(String base64) Base64 解析私钥。static PublicKeyparsePublicKey(String base64) Base64 解析公钥。static Stringsign(String data, PrivateKey privateKey) RSA 签名(SHA256withRSA,Base64 输出)。static byte[]signBytes(String data, PrivateKey privateKey) RSA 签名,返回原始字节。static StringsignHex(String data, PrivateKey privateKey) RSA 签名(SHA256withRSA,Hex 输出)。static booleanRSA 验签(SHA256withRSA,Base64 输入)。static booleanverifyBytes(String data, PublicKey publicKey, byte[] signature) RSA 验签,字节输入。static booleanRSA 验签(SHA256withRSA,Hex 输入)。
-
Field Details
-
DEFAULT_KEY_SIZE
public static final int DEFAULT_KEY_SIZE默认密钥位数- See Also:
-
MIN_KEY_SIZE
public static final int MIN_KEY_SIZE允许的最小密钥位数(低于此值直接拒绝,弱密钥)- See Also:
-
-
Method Details
-
generateKeyPair
-
generateKeyPair
生成密钥对。- Parameters:
keySize- 密钥位数(强制不小于MIN_KEY_SIZE,推荐 2048 及以上)- Returns:
- 密钥对
- Throws:
IllegalArgumentException- keySize 小于 2048
-
encrypt
RSA 加密(OAEP-SHA256)。- Parameters:
data- 明文key- 公钥或私钥- Returns:
- 密文字节
-
decrypt
RSA 解密(OAEP-SHA256)。- Parameters:
data- 密文字节key- 与加密相反的公钥或私钥- Returns:
- 明文字节
-
encryptBase64
-
decryptBase64
私钥解密 Base64 密文。- Parameters:
base64- Base64 密文privateKey- 私钥- Returns:
- 明文(UTF-8)
-
encryptHex
-
decryptHex
私钥解密十六进制密文。- Parameters:
hex- 十六进制密文privateKey- 私钥- Returns:
- 明文(UTF-8)
-
getPublicKeyBase64
-
getPrivateKeyBase64
-
parsePublicKey
-
parsePrivateKey
Base64 解析私钥。- Parameters:
base64- Base64 私钥- Returns:
- 私钥
-
sign
RSA 签名(SHA256withRSA,Base64 输出)。- Parameters:
data- 原文privateKey- 私钥- Returns:
- Base64 签名
-
verify
-
signHex
RSA 签名(SHA256withRSA,Hex 输出)。- Parameters:
data- 原文privateKey- 私钥- Returns:
- Hex 签名
-
verifyHex
-
signBytes
RSA 签名,返回原始字节。- Parameters:
data- 原文privateKey- 私钥- Returns:
- 签名字节
-
verifyBytes
-