powered by simpleCommunicator - 2.0.49     © 2025 Programmizd 02
Форумы / Java [игнор отключен] [закрыт для гостей] / Bcrypt шифрование
15 сообщений из 15, страница 1 из 1
Bcrypt шифрование
    #39851470
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Всем привет в моем проекте когда заходишь на сайт через админа или простого юзера, он сохраняет пароли не зашифрованными. Я хочу сделать Bcrypt шифрование, чтобы пароли в базе данных MySQL были шифрованными. Когда запускаю проект Томкат ругается.


Security Config
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                    .antMatchers("/admin/**").hasRole("ADMIN")
                    .antMatchers("/user/**").hasRole("USER")
                    .antMatchers("/**").permitAll()
                    .and()
                    .formLogin()
                    .loginPage("/login")
                    .defaultSuccessUrl("/allStudents")
                    .and()
                    .logout()
                    .and()
                    .csrf().disable();
        }
    
       @Bean
        public PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
    
    }
    
            
 



Admin Controller
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
    @Controller
    @RequestMapping("/admin")
    public class AdminController {
    
        @Autowired
        private StudentService studentService;
        @Autowired
        private UserService userService;
    
        @GetMapping("/allStudentsAdmin")
        public ModelAndView allStudentsForUser() {
            ModelAndView mv = new ModelAndView();
            List<Student> studentList = studentService.getAllStudents();
            mv.addObject("studentList", studentList);
            mv.setViewName("allStudentsAdmin");
            return mv;
        }
    
        @GetMapping(value = "/deleteStudent/{id}")
        public ModelAndView deleteUserById(@PathVariable Long id) {
            studentService.deleteStudentById(id);
            ModelAndView mv = new ModelAndView("redirect:/admin/allStudentsAdmin");
            return mv;
        }
    
        @GetMapping(value = "/editStudent/{id}")
        public ModelAndView displayEditUserForm(@PathVariable Long id) {
            ModelAndView mv = new ModelAndView("adminEditStudent");
            Student student = studentService.getStudentById(id);
            mv.addObject("headerMessage", "Редактирование студента");
            mv.addObject("student", student);
            return mv;
        }
    
        @PostMapping(value = "/editStudent")
        public String saveEditedUser(
        @RequestParam("id") Long id,
        @RequestParam("name") String name,
        @RequestParam("surname") String surname,
        @RequestParam("avatar") MultipartFile file) {
            try {
                studentService.updateStudent(name, surname, file, studentService.getStudentById(id));
            } catch (FileSystemException ex) {
                ex.printStackTrace();
            } catch (IOException e) {
                return "redirect:/errors";
            }
    
            return "redirect:/admin/allStudentsAdmin";
        }
    
        @GetMapping(value = "/addStudentAdmin")
        public ModelAndView displayNewUserForm() {
            ModelAndView mv = new ModelAndView("addStudentAdmin");
            mv.addObject("headerMessage", "Add Student Details");
            mv.addObject("student", new Student());
            return mv;
        }
    
        @PostMapping(value = "/addStudentAdmin")
        public String saveNewStudent(@RequestParam("name") @NonNull String name,
        @RequestParam("surname") @NonNull String surname,
        @RequestParam("avatar") MultipartFile file)
        throws IOException {
    
            Student student = new Student();
            student.setSurname(surname);
            student.setName(name);
    
            if (file != null && !file.isEmpty()) {
                student.setAvatar(studentService.saveAvatarImage(file).getName());
            }
            studentService.saveStudent(student);
            return "redirect:/admin/allStudentsAdmin";
        }
    
        @GetMapping(value = "/addUser")
        public ModelAndView displayAddUserForm() {
            ModelAndView mv = new ModelAndView("addUser");
    
            mv.addObject("user", new User());
            return mv;
        }
    
        @PostMapping(value = "/addUser", consumes = "multipart/form-data")
        public String saveNewUser(@ModelAttribute User user) {
            userService.saveUser(user);
            return "redirect:/admin/allUsers";
        }
    
        @GetMapping("/allUsers")
        public ModelAndView allUsers(@ModelAttribute User user) {
            ModelAndView mv = new ModelAndView("allUsers");
            List<User> users = userService.getAll();
            mv.addObject("users", users);
            return mv;
        }
    
        @GetMapping("/editUser/{id}")
        public ModelAndView editUser(@PathVariable Long id) {
            Optional<User> user = userService.findUser(id);
            if (user.isPresent()) {
                ModelAndView mv = new ModelAndView("editUser");
                mv.addObject("user", user.get());
                return mv;
            }
            return new ModelAndView("redirect:/admin/allUsers");
        }
    
        @PostMapping("/editUser")
        public String saveEditedUser(@ModelAttribute User user) {
            userService.updateUser(user);
            return "redirect:/admin/allUsers";
        }
        
        
         @GetMapping(value = "/deleteUser/{id}")
        public ModelAndView deleteClientById(@PathVariable Long id) {
            userService.deleteAccountById(id);
            ModelAndView mv = new ModelAndView("redirect:/admin/allUsers");
            return mv;
        }
    }
        
    
    


UserService

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
 public interface UserService {
        User saveUser(User user);
        List<User> getAll();
    
        Optional<User> findUser(Long id);
    
        User updateUser(User user);
        
        boolean deleteAccountById(Long id);
    
    }    
           



UserServiceImpl

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
 @Service
    @Transactional
    public class UserServiceImpl implements UserService {
    
        @Autowired
        private UserRepository repository;
    
    
        @Autowired
        public UserServiceImpl(UserRepository repository) {
            super();
            this.repository = repository;
        }
    
        @Override
        public List<User> getAll() {
            return (List<User>) repository.findAll();
        }
    
        @Override
        public Optional<User> findUser(Long id) {
            return repository.findById(id);
        }
    
        @Override
        public User saveUser(User user) {
            return repository.save(user);
        }
        
        @Override
        public boolean deleteAccountById(Long id) {
            try {
                repository.deleteById(id);
                return true;
            } catch (Exception ex) {
                return false;
            }
    
        }
    
        @Override
        public User updateUser(User user) {
            User targetUser = repository.findById(user.getId()).get();
    
            if (user.getLogin() != null) {
                targetUser.setLogin(user.getLogin());
            }
    
            if (user.getRole() != null) {
                targetUser.setRole(user.getRole());
            }
            
            if (user.getPassword() != null) {
                targetUser.setPassword(user.getPassword());
                
            }
            return repository.save(targetUser);
        
    
        }
    }



User.JAVA

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
  @Entity
    @Table(name = "users")
    public class User implements Serializable, UserDetails {
    
        @Id
        @GeneratedValue
        private Long id;
    
        private String login;
        private String password;
        private String role;
        public Long getId() {
            return id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
        public void setId(long id) {
            this.id = id;
        }
    
        public String getLogin() {
            return login;
        }
    
        public void setLogin(String login) {
            this.login = login;
        }
    
        @Override
        public Collection<? extends GrantedAuthority> getAuthorities() {
            return Collections.singleton(new SchoolAuthority(role));
        }
    
        @Override
        public String getPassword() {
            return password;
        }
    
        @Override
        public String getUsername() {
            return login;
        }
    
        @Override
        public boolean isAccountNonExpired() {
            return true;
        }
    
        @Override
        public boolean isAccountNonLocked() {
            return true;
        }
    
        @Override
        public boolean isCredentialsNonExpired() {
            return true;
        }
    
        @Override
        public boolean isEnabled() {
            return true;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public String getRole() {
            return role;
        }
    
        public void setRole(String role) {
            this.role = role;
        }
    
        class SchoolAuthority implements GrantedAuthority {
    
            String role;
    
            public SchoolAuthority(String role) {
                this.role = role;
            }
    
            @Override
            public String getAuthority() {
                return role;
            }
        }
    
        @Override
        public String toString() {
            return "User{" +
            "id=" + id +
            ", login='" + login + '\'' +
            ", password='" + password + '\'' +
            ", role='" + role + '\'' +
            '}';
        }
    }



Authorization Controller
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
    @Controller
    public class AuthorizationController {
    
        private static final String ROLE_ADMIN = "ROLE_ADMIN";
        private static final String ROLE_USER = "ROLE_USER";
        @Autowired
        StudentService studentService;
    
        @RequestMapping(value = "/login", method = RequestMethod.GET)
        public String loginPage(@RequestParam(value = "error", required = false) String error,
                @RequestParam(value = "logout", required = false) String logout,
                Model model) {
            String errorMessage = null;
            if (error != null) {
                errorMessage = "Username or Password is incorrect !!";
            }
            if (logout != null) {
                errorMessage = "You have been successfully logged out !!";
            }
            model.addAttribute("errorMessage", errorMessage);
            return "login";
        }
    
        @RequestMapping(value = "/logout", method = RequestMethod.GET)
        public String logoutPage(HttpServletRequest request, HttpServletResponse response) {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            if (auth != null) {
                new SecurityContextLogoutHandler().logout(request, response, auth);
            }
            return "redirect:/";
        }
    
        @RequestMapping(value = {"/allStudents", "/"},  method = {RequestMethod.GET, RequestMethod.POST})
        public ModelAndView displayAllStudents() {
            Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication()
                    .getAuthorities();
            if(containRole(authorities, ROLE_ADMIN)){
                return new ModelAndView("redirect:/admin/allStudentsAdmin");
            }
            if(containRole(authorities, ROLE_USER)){
                return new ModelAndView("redirect:/user/allStudentsUser");
            }
            ModelAndView mv = new ModelAndView("allStudents");
            mv.addObject("studentList", studentService.getAllStudents());
            return mv;
        }
    
        @GetMapping("/addStudent")
        public ModelAndView editStudent(){
            Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication()
                    .getAuthorities();
            if(containRole(authorities, ROLE_ADMIN)){
                return new ModelAndView("redirect:/admin/addStudentAdmin");
            }
            if(containRole(authorities, ROLE_USER)){
                return new ModelAndView("redirect:/user/addStudentUser");
            }
            ModelAndView mv = new ModelAndView("allStudents");
            mv.addObject("studentList", studentService.getAllStudents());
            return mv;
        }
    
        private boolean containRole(Collection<? extends GrantedAuthority> authorities, String role){
            for (GrantedAuthority grantedAuthority : authorities) {
                if (grantedAuthority.getAuthority().equals(role)) {
                    return true;
                }
            }
            return false;
        }
    }
        




AddUser.JSP

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
    <body>
    
    <div class="add">
        <br>
        <br>
        <br>
    
        <br>
        <center>
            <form:form method="POST" action="${pageContext.request.contextPath}/admin/addUser"
                       enctype="multipart/form-data">
                <table>
                    <tr>
                        <td><label path="Login">Login</label></td>
                        <td><input type="text" name="login"/></td>
                    </tr>
                    <tr>
                        <td><label path="Password">Password</label></td>
                        <td><input type="text" name="password"/></td>
                    </tr>
                    <tr>
                        <td><label path="Role">Выберите роль</label></td>
                        <td>
                            <select path="role" name="role" required>
                                <option>ROLE_ADMIN</option>
                                <option selected>ROLE_USER</option>
                            </select>
                        </td>
    
    
                        <td><input class="btn btn-primary" type="submit" value="Submit"></td>
                    </tr>
    
                </table>
            </form:form>
        </center>
    </div>
    </body>
...
Рейтинг: 0 / 0
Bcrypt шифрование
    #39851471
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
fallen2019,

Пароли должны здесь быть зашифрованными
...
Рейтинг: 0 / 0
Bcrypt шифрование
    #39851495
Фотография mayton
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
fallen2019, а почему ты решил что BCrypt-шифрование - это правильный способ?
...
Рейтинг: 0 / 0
Bcrypt шифрование
    #39851502
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
mayton,

Просто мне сказали, чтобы пароли не были видны. Чтобы за место допустим у одного пользователя пароль - 1234, в базе он был виден как - $2a$10$hLflI7in25Bw/sQJCFKLH.7ISyABaMVqlpxMiyC8ZAtSQTCkOErNS
...
Рейтинг: 0 / 0
Bcrypt шифрование
    #39851506
Фотография mayton
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
fallen2019, тебе правильно сказали. Но обычно пароли не шифруют а хешируют длинным хешом типа MD5 или SHA160.

Посмотри как тут https://docs.oracle.com/javase/8/docs/api/java/security/MessageDigest.html

И Bcrypt не нужен.
...
Рейтинг: 0 / 0
Bcrypt шифрование
    #39851507
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
mayton,

Просто мне сказали только Bcrypt использовать больше ничего
...
Рейтинг: 0 / 0
Bcrypt шифрование
    #39851510
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
fallen2019,

Может я не правильно написал, там просто надо чтобы пароли не были видны в бащзе данных они должны быть хэшированы BCrypt-ом
...
Рейтинг: 0 / 0
Bcrypt шифрование
    #39851512
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
mayton,

Можете посмотреть в коде, что я не правильно написал
...
Рейтинг: 0 / 0
Bcrypt шифрование
    #39851514
Фотография mayton
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
...
Рейтинг: 0 / 0
Bcrypt шифрование
    #39851528
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
mayton,

Я прочитал, можете помочь как правильно написать. Я многие методы посмотрел включая то как делал Mkyoung, но не получилось
...
Рейтинг: 0 / 0
Bcrypt шифрование
    #39851536
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
mayton,

А все получилось спасибо))
...
Рейтинг: 0 / 0
Bcrypt шифрование
    #39851660
Фотография SQL2008
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
fallen2019mayton,

Я прочитал, можете помочь как правильно написать. Я многие методы посмотрел включая то как делал Mkyoung, но не получилось

Опоздал я со ссылкой :(
...
Рейтинг: 0 / 0
Bcrypt шифрование
    #39851898
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
SQL2008,

Спасибо за отклик))ценю)
...
Рейтинг: 0 / 0
Bcrypt шифрование
    #39852132
Фотография asv79
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
в чем там автор завис непонятно,там дел 2 строчки кода

сам тока что шифрование добавил
создаешь такой бин
Код: java
1.
2.
3.
4.
  @Bean
   public PasswordEncoder getPasswordEncoder(){
       return new BCryptPasswordEncoder(8);
   }



и потом добавляешь когда пароль сохраняешь
Код: java
1.
user.setPassword(passwordEncoder.encode(user.getPassword()))
...
Рейтинг: 0 / 0
Bcrypt шифрование
    #39852136
Фотография asv79
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
админконтроллер конечно вырви глаз))
...
Рейтинг: 0 / 0
15 сообщений из 15, страница 1 из 1
Форумы / Java [игнор отключен] [закрыт для гостей] / Bcrypt шифрование
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]