架构师训练营第十一周作业 - 命题作业
请用你熟悉的编程语言写一个用户密码验证函数,Boolean checkPW(String 用户 ID,String 密码明文,String 密码密文),返回密码是否正确 boolean 值,密码加密算法使用你认为合适的加密算法。
package com.example.demo.user;
import lombok.Data;
import javax.persistence.*;
/**
* 用户类
* @author wuyd
*
*/
@Entity
@Table(name="user")
@Data
public class User {
@Id
private String username;
@Column
private String fullname;
@Column
private String password;
}
package com.example.demo.user;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
/**
* 持久层
* @author wuyd
*
*/
@Repository
public interface UserRepository extends CrudRepository<User,String> {
}
package com.example.demo;
import java.io.UnsupportedEncodingException;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.DigestUtils;
import com.example.demo.user.User;
import com.example.demo.user.UserRepository;
/**
* 测试类
* @author wuyd
*
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserTest {
@Autowired
private UserRepository userRepository;
/**
* 注册请求
*/
@Test
public void register() {
executeRegister("zhangsan","张三","123456");
System.out.println(executeLogin("zhangsan","1234567"));
}
/**
* 执行注册
* @param username
* @param fullname
* @param password
*/
public void executeRegister(String username,String fullname,String password) {
User user=new User();
user.setUsername(username);
user.setFullname(fullname);
try {
user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
userRepository.save(user);
}
/**
* 执行登录
* @param username
* @param password
* @return
*/
public String executeLogin(String username,String password) {
User user=userRepository.findById(username).get();
if(user!=null) {
try {
if(DigestUtils.md5DigestAsHex(password.getBytes("UTF-8")).equals(user.getPassword())){
return "success";
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}else {
System.out.println("用户未找到!");
}
return "failure";
}
}
评论