1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.shiro.authc.credential;
20
21 import org.apache.shiro.authc.AuthenticationInfo;
22 import org.apache.shiro.authc.AuthenticationToken;
23 import org.apache.shiro.authc.SimpleAuthenticationInfo;
24 import org.apache.shiro.authc.UsernamePasswordToken;
25 import org.apache.shiro.crypto.SecureRandomNumberGenerator;
26 import org.apache.shiro.crypto.hash.Sha1Hash;
27 import org.apache.shiro.subject.PrincipalCollection;
28 import org.apache.shiro.subject.SimplePrincipalCollection;
29 import org.apache.shiro.util.ByteSource;
30 import org.junit.Test;
31
32 import static org.junit.Assert.assertTrue;
33
34
35
36
37 public class HashedCredentialsMatcherTest {
38
39
40
41
42
43 @Test
44 public void testSaltedAuthenticationInfo() {
45
46 HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(Sha1Hash.ALGORITHM_NAME);
47
48
49 ByteSource salt = new SecureRandomNumberGenerator().nextBytes();
50 Object hashedPassword = new Sha1Hash("password", salt);
51 SimpleAuthenticationInfo account = new SimpleAuthenticationInfo("username", hashedPassword, salt, "realmName");
52
53
54 AuthenticationToken token = new UsernamePasswordToken("username", "password");
55
56
57 assertTrue(matcher.doCredentialsMatch(token, account));
58 }
59
60
61
62
63
64 @Test
65 public void testBackwardsCompatibleUnsaltedAuthenticationInfo() {
66 HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(Sha1Hash.ALGORITHM_NAME);
67
68
69 final String username = "username";
70 final String password = "password";
71 final Object hashedPassword = new Sha1Hash(password).getBytes();
72 AuthenticationInfo account = new AuthenticationInfo() {
73 public PrincipalCollection getPrincipals() {
74 return new SimplePrincipalCollection(username, "realmName");
75 }
76
77 public Object getCredentials() {
78 return hashedPassword;
79 }
80 };
81
82
83 AuthenticationToken token = new UsernamePasswordToken("username", "password");
84
85
86 assertTrue(matcher.doCredentialsMatch(token, account));
87 }
88
89
90
91
92
93 @Test
94 public void testBackwardsCompatibleSaltedAuthenticationInfo() {
95 HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(Sha1Hash.ALGORITHM_NAME);
96
97 matcher.setHashSalted(true);
98
99
100
101 final String username = "username";
102 final String password = "password";
103 final Object hashedPassword = new Sha1Hash(password, username).getBytes();
104 AuthenticationInfo account = new AuthenticationInfo() {
105 public PrincipalCollection getPrincipals() {
106 return new SimplePrincipalCollection(username, "realmName");
107 }
108
109 public Object getCredentials() {
110 return hashedPassword;
111 }
112 };
113
114
115 AuthenticationToken token = new UsernamePasswordToken("username", "password");
116
117
118 assertTrue(matcher.doCredentialsMatch(token, account));
119 }
120 }