密码加密的方法

本文介绍使用Hutool和Spring Boot进行密码加密的方法,包括使用AES加密算法和BCryptPasswordEncoder加密用户密码,以及如何在注册和登录过程中应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一种,使用hutool
第一步导入pom

<dependency>
			<groupId>cn.hutool</groupId>
			<artifactId>hutool-all</artifactId>
			<version>4.1.19</version>
</dependency>

这个就是加密

package com.test;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;

public class test5 {
	public static void main(String[] args) {
		String content = "test中文";
		// 随机生成密钥
		//byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();\
		String str="64asf64asf4asdf5";
		byte[] key=str.getBytes();
		// 构建
		AES aes = SecureUtil.aes(key);
		// 加密为16进制表示
		String encryptHex = aes.encryptHex(content);
		// 解密为原字符串
		String decryptStr = aes.decryptStr(encryptHex);
		System.out.println(encryptHex);
	}
}

这个就是解密
str就是盐,到时候写配置文件里

package com.test;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;

public class test6 {
	public static void main(String[] args) {
		String encryptHex="36d6feef484e85fee9ff282b4c1c9eb9";
		// 随机生成密钥
	//	byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
		String str="64asf64asf4asdf5";
		byte[] key=str.getBytes();
		// 构建
		AES aes = SecureUtil.aes(key);
		// 解密为原字符串
		String decryptStr = aes.decryptStr(encryptHex);
		System.out.println(decryptStr);
	}
}

还有一种方法是spring的

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
// 启动类里加

@Bean
public BCryptPasswordEncoder encoder(){
	return new BCryptPasswordEncoder();
}
// 用的时候引入

	@Autowired
	private BCryptPasswordEncoder encoder;
	// 注册时这样就加密了
	user.setPassword(encoder.encode(user.getPassword()));
	// 登录时校验密码
	encoder.matches(password, user.getPassword())

也可以始终这种动态的盐

package com.test;

import org.apache.commons.lang3.RandomStringUtils;

import cn.hutool.crypto.SecureUtil;

public class test7 {

	public static void main(String[] args) {

		String phonenum = "13578942677";

		String password = "wodemimashi123456";

		String random = RandomStringUtils.randomAscii(10);// .randomNumeric(10);

		System.out.println(random);

		String data = phonenum + password + random;

		String zuizhongmima = SecureUtil.md5(data);

		System.out.println(zuizhongmima);
		// 30c4f092608b5c93b8e49080393f35e4
	}

}

组成密码的字段可以动态组合,注册时把盐存储到用户的数据里,每次登录的时候取出来用来校验
hutool里有很多关于密码的处理的工具类都可以使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值