基于 JWE (JSON Web Encryption,JSON 网络加密) 规范,对数据传输进行加密的工具类,推荐使用。
JWE 包含了消息的加密、摘要、认证、签名等多个方面以确保数据安全。
本工具类依赖第三方 Nimbus JOSE + JWT 库,并支持:
参考文档:
示例:import bropen.toolkit.utils.security.JweEncryptor
String payload = "hello world.";
JweEncryptor encryptor = new JweEncryptor(JweEncryptor.AES);
String aesKey = encryptor.generateAesKey(); // 生成测试秘钥
encryptor.setAesKey(aesKey);
// 加密
String encrypted = encryptor.encrypt(payload);
System.out.println("AES: " + encrypted);
// 解密
String decrypted = encryptor.decrypt(encrypted);
assert payload.equals(decrypted);
encryptor = new JweEncryptor(JweEncryptor.RSA);
Map<String, String> rsaKeys = encryptor.generateRsaKeys(); // 生成测试密钥对,可能有点慢
// 加密
encrypted = encryptor.setRsaPublicKey(rsaKeys.get("public")).encrypt(payload);
System.out.println("RSA: " + encrypted);
// 解密
decrypted = encryptor.setRsaPrivateKey(rsaKeys.get("private")).decrypt(encrypted);
assert payload.equals(decrypted);
| Constructor and description |
|---|
JweCryptor
(String encryptMethod)构造方法 |
| Type | Name and description |
|---|---|
protected static javax.crypto.SecretKey |
decodeAesKey(String key) |
protected static byte[] |
decodeKey(String key) |
protected static java.security.interfaces.RSAPrivateKey |
decodeRsaPrivateKey(String key) |
protected static java.security.interfaces.RSAPublicKey |
decodeRsaPublicKey(String key) |
String |
decrypt(String jweString)解密接口数据 |
protected static String |
encodeKey(java.security.Key key) |
String |
encrypt(CharSequence payload)加密数据 |
String |
generateAesKey()生成一个 base64 编码后的 AES 秘钥 |
Map<String, String> |
generateRsaKeys()生成一对 base64 编码后的 RSA 秘钥 |
JweCryptor |
setAesKey(String encryptionKey)加解密前,设置 AES 秘钥 |
JweCryptor |
setAesKeysize(int keysize)生成 AES 秘钥或加解密前,设置 AES 秘钥大小,默认为 256 |
JweCryptor |
setRsaKeysize(int keysize)生成 RSA 秘钥对前,设置 RSA 秘钥大小,默认 2048 |
JweCryptor |
setRsaPrivateKey(String encryptionKey)解密前,设置 RSA 私钥 |
JweCryptor |
setRsaPublicKey(String encryptionKey)加密前,设置 RSA 公钥 |
| Methods inherited from class | Name |
|---|---|
class Object |
Object#wait(long, int), Object#wait(long), Object#wait(), Object#equals(Object), Object#toString(), Object#hashCode(), Object#getClass(), Object#notify(), Object#notifyAll() |
构造方法
仅支持 AES 对称加密和 RSA 非对称加密。
encryptMethod - 加解密算法,AES 或 RSA解密接口数据
如果是 RSA,则使用私钥进行解密。
jweString - 加密字符串加密数据
如果是 RSA,则使用公钥进行加密。
payload - 需要加密的数据(如 json 字符串)生成一个 base64 编码后的 AES 秘钥
生成一对 base64 编码后的 RSA 秘钥
[public: xxxx, private: xxxx]加解密前,设置 AES 秘钥
encryptionKey - Base64 编码的秘钥生成 AES 秘钥或加解密前,设置 AES 秘钥大小,默认为 256
keysize - 可选 128 或 256生成 RSA 秘钥对前,设置 RSA 秘钥大小,默认 2048
keysize - 可选 1024、2048、4096解密前,设置 RSA 私钥
encryptionKey - Base64 编码的 RSA 私钥加密前,设置 RSA 公钥
encryptionKey - Base64 编码的 RSA 公钥BROPEN Documentation, 2020-04-21 10:53