1. 用spring security里的加密方式

  1. <dependency>
  2. <groupId>org.springframework.security</groupId>
  3. <artifactId>spring-security-core</artifactId>
  4. <version>4.1.3.RELEASE</version>
  5. </dependency>

例子

  1. @SpringBootTest
  2. @RunWith(SpringRunner.class)
  3. public class PasswordEncoderTest {
  4. // 从配置文件中获得
  5. private static final String secretKey = "ff4314b2a07c9604d8cb25b9f08ccd22c8e";
  6. private static final PasswordEncoder encoder = new StandardPasswordEncoder(secretKey);
  7. /**
  8. * 加密
  9. * @param rawPassword 原始密码
  10. */
  11. public static String encrypt(String rawPassword) {
  12. return encoder.encode(rawPassword);
  13. }
  14. /**
  15. * 匹配密码
  16. * @param rawPassword 原始密码
  17. * @param password 匹配密码
  18. */
  19. public static boolean match(String rawPassword, String password) {
  20. return encoder.matches(rawPassword, password);
  21. }
  22. @Test
  23. public void test() throws ParseException {
  24. System.out.println(PasswordEncoderTest.encrypt("test"));
  25. System.out.println(PasswordEncoderTest.encrypt("test"));
  26. System.out.println(PasswordEncoderTest.encrypt("test"));
  27. System.out.println(PasswordEncoderTest.match("test", PasswordEncoderTest.encrypt("test")));
  28. System.out.println(PasswordEncoderTest.match("taUlJhIxRks", "5616b8181eea5281386522fec74a060ac765110db9be14f722b41e312dced928fe3b18e78ba676b1"));
  29. }
  30. }

输出
cc88d67ded09c6fda80984f6402244b8537adaad295cdbc0e649d7824b8942a8e5d8108f27b4cbfc
06973b058341190c7220560030c1ebdd76a184abde5dfad56bf188c535d48f477ab2720dd61a2c83
fe848b2db9759262288704e832a2e965320451bb8df432fa6c9165f42f38053027947f5f68d84fa2
true
true