blob: 83160a9e8f041aca4fbdf3d82876eb2222aba9f9 (
plain)
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
|
/*
* Copyright 2014 Jesse Morgan
*/
package com.p4square.grow.backend;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.codec.binary.Hex;
import org.restlet.security.SecretVerifier;
import com.p4square.grow.model.UserRecord;
import com.p4square.grow.provider.Provider;
/**
* Verify the given credentials against the users with backend access.
*/
public class BackendVerifier extends SecretVerifier {
private final Provider<String, UserRecord> mUserProvider;
public BackendVerifier(Provider<String, UserRecord> userProvider) {
mUserProvider = userProvider;
}
@Override
public int verify(String identifier, char[] secret) {
if (identifier == null) {
throw new IllegalArgumentException("Null identifier");
}
if (secret == null) {
throw new IllegalArgumentException("Null secret");
}
// Does the user exist?
UserRecord user;
try {
user = mUserProvider.get(identifier);
if (user == null) {
return RESULT_UNKNOWN;
}
} catch (IOException e) {
return RESULT_UNKNOWN;
}
// Does the user have a backend password?
String storedHash = user.getBackendPasswordHash();
if (storedHash == null) {
// This user doesn't have access
return RESULT_INVALID;
}
// Validate the password.
try {
String hashedInput = hashPassword(secret);
if (hashedInput.equals(storedHash)) {
return RESULT_VALID;
}
} catch (NoSuchAlgorithmException e) {
return RESULT_UNSUPPORTED;
}
// If all else fails, fail.
return RESULT_INVALID;
}
/**
* Hash the given secret.
*/
public static String hashPassword(char[] secret) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-1");
// Convert the char[] to byte[]
// FIXME This approach is incorrectly truncating multibyte
// characters.
byte[] b = new byte[secret.length];
for (int i = 0; i < secret.length; i++) {
b[i] = (byte) secret[i];
}
md.update(b);
byte[] hash = md.digest();
return new String(Hex.encodeHex(hash));
}
}
|