Jasypt: Java Simplified Encryption
本笔记介绍使用Jasypt: Java Simplified Encryption做非对称加密。
非对称加密算法
非对称加密算法使用公钥(public key)对数据进行加密;使用对应的私钥(private key)进行解密。因为加密和解密使用的是两个不同的密钥,所以这种算法叫作非对称加密算法。
生成私钥、公钥
代码:
public String generateKeyPair() {
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(this.applicationConfig.getEncryptionAlgorithm());
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
String keyPairString = new StringBuilder()
.append("-----BEGIN PRIVATE KEY-----\n")
.append(Base64.getMimeEncoder().encodeToString(keyPair.getPrivate().getEncoded()))
.append("\n")
.append("-----END PRIVATE KEY-----\n")
.append("\n")
.append("-----BEGIN PUBLIC KEY-----\n")
.append(Base64.getMimeEncoder().encodeToString(keyPair.getPublic().getEncoded()))
.append("\n")
.append("-----END PUBLIC KEY-----\n")
.toString();
return keyPairString;
} catch (NoSuchAlgorithmException e) {
throw new ApplicationException("No such algorithm: " + this.applicationConfig.getEncryptionAlgorithm(), e);
}
}
结果:
加密
代码:
public String encrypt(String message) {
SimpleAsymmetricConfig config = new SimpleAsymmetricConfig();
config.setPublicKey(this.applicationConfig.getPublicKeyString());
config.setKeyFormat(AsymmetricCryptography.KeyFormat.PEM);
StringEncryptor encryptor = new SimpleAsymmetricStringEncryptor(config);
return encryptor.encrypt(message);
}
结果:
解密
代码:
public String decrypt(String encryptedMessage) {
SimpleAsymmetricConfig config = new SimpleAsymmetricConfig();
config.setPrivateKey(this.privateKeyString);
config.setKeyFormat(AsymmetricCryptography.KeyFormat.PEM);
SimpleAsymmetricByteEncryptor encryptor = new SimpleAsymmetricByteEncryptor(config);
return new String(encryptor.decrypt(Base64.getDecoder().decode(encryptedMessage)), StandardCharsets.UTF_8);
}
结果: