JAVA加密解密字符串
import lombok.extern.slf4j.Slf4j;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
/**
* @author 孙永潮
* @date 2022/10/26
*/
@Slf4j
public class JasyptUtil {
/**
* Jasypt生成加密结果
*
* @param salt 配置文件中设定的加密盐值
* @param value 加密值
* @return
*/
public static String encryptPwd(String salt, String value) {
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
encryptor.setConfig(cryPTor(salt));
String result = encryptor.encrypt(value);
return result;
}
/**
* 解密
*
* @param salt 配置文件中设定的加密盐值
* @param value 解密密文
* @return
*/
public static String decyptPwd(String salt, String value) {
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
encryptor.setConfig(cryPTor(salt));
String result = encryptor.decrypt(value);
return result;
}
public static SimpleStringPBEConfig cryPTor(String password) {
SimpleStringPBEConfig config = new SimpleStringPBEConfig();
config.setPassword(password);
config.setAlgorithm("PBEWithMD5AndDES");
config.setKeyObtentionIterations("1000");
config.setPoolSize("1");
config.setProviderName("SunJCE");
config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
config.setStringOutputType("base64");
return config;
}
//盐可以自己设置(中文好像不能用)
private static final String SALT = "^&zzz.com";
//随便写个main方法试试
public static void main(String[] args) {
// 加密
String encPwd = JasyptUtil.encryptPwd(SALT, "12345678");
log.info("加密后的值为: {}", encPwd);
// 解密
String decPwd = JasyptUtil.decyptPwd(SALT, "fI8z1zmuUk3Qk9uwFcu+tJtOFEeE6i7F9RSutYW4zXvQuX/Xx7echxiJXUjXf3XGqV19fj7FFvI=");
log.info("解密后的值为: {}", decPwd);
}
}
pom文件
<!-- jasypt加解密 -->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
BCrypt 单向加密
package 报名.路径.demo;
import cn.dev33.satoken.secure.BCrypt;
/**
* @Date: 2024/03/18/10:40
*/
public class BCryptDemo {
public static void main(String[] args) {
String password = "123456";
System.out.println("假设原密码为:" + password);
//用BCrypt 哈希加密(哈希加密是一种单向加密算法,即无法通过哈希值还原出原始的明文密码)
String hashPassword = BCrypt.hashpw(password);
System.out.println("加密后 结果为:" + hashPassword);
//用户输入的密码
String inputPassword = "123456";
String inputPw2 = "12345678";
//用BCrypt 验证(若密码正确,则返回 true)
boolean boo = BCrypt.checkpw(inputPassword, hashPassword);
boolean bool = BCrypt.checkpw(inputPw2, hashPassword);
if (boo) {
System.out.println(inputPassword + " 密码正确");
}
if (!bool) {
System.out.println(inputPw2 + " 密码错误");
}
}
}