例子 1:字节加密
import org.springframework.security.crypto.encrypt.BytesEncryptor;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.security.crypto.keygen.KeyGenerators;
/**
* <p> 字节加密
* <p> 参考:https://docs.spring.io/spring-security/site/docs/5.2.1.RELEASE/reference/htmlsingle/#spring-security-crypto-encryption-bytes
* <p> 参考:https://docs.spring.io/spring-security/site/docs/5.2.1.RELEASE/reference/htmlsingle/#spring-security-crypto-keygenerators
* @author mk
*
*/
public class BytesEncryptorTests {
public static void main(String[] args) {
// generates a random 8-byte salt that is then hex-encoded
String salt = KeyGenerators.string().generateKey();
//
String password = "your password";
// Use the Encryptors.standard factory method to construct a "standard" BytesEncryptor
BytesEncryptor bytesEncryptor = Encryptors.standard(password, salt);
byte[] text = "0123456789中文汉字,这是待加密的文字。".getBytes();
byte[] encrypted = bytesEncryptor.encrypt(text); // 加密
System.out.println(new String(encrypted)); // 密文
byte[] decrypted = bytesEncryptor.decrypt(encrypted); // 解密
System.out.println(new String(decrypted)); // 明文
}
}
例子 2:文本加密
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.security.crypto.encrypt.TextEncryptor;
import org.springframework.security.crypto.keygen.KeyGenerators;
/**
* <p> 文本加密
* <p> 参考:https://docs.spring.io/spring-security/site/docs/5.2.1.RELEASE/reference/htmlsingle/#spring-security-crypto-encryption-text
* <p> 参考:https://docs.spring.io/spring-security/site/docs/5.2.1.RELEASE/reference/htmlsingle/#spring-security-crypto-keygenerators
* @author mk
*
*/
public class TextEncryptorTests {
public static void main(String[] args) {
// generates a random 8-byte salt that is then hex-encoded
String salt = KeyGenerators.string().generateKey();
//
String password = "your password";
// Use the Encryptors.text factory method to construct a standard TextEncryptor
TextEncryptor textEncryptor = Encryptors.text(password, salt);
// A TextEncryptor uses a standard BytesEncryptor to encrypt text data. Encrypted results are returned as hex-encoded strings for easy storage on the filesystem or in the database.
String text = "0123456789中文汉字,这是待加密的文字。";
String encrypted = textEncryptor.encrypt(text); // 加密
System.out.println(encrypted); // 密文
String decrypted = textEncryptor.decrypt(encrypted); // 解密
System.out.println(decrypted); // 明文
}
}