-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathPasscodeGenerator.java
75 lines (63 loc) · 2.29 KB
/
PasscodeGenerator.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
package 双向认证;
import java.io.ByteArrayInputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
/**
* Created by linSir
* date at 2017/8/8.
* describe: 算法的核心类
*/
public class PasscodeGenerator {
private static final int MAX_PASSCODE_LENGTH = 9;
private static final int[] DIGITS_POWER
// 0 1 2 3 4 5 6 7 8 9
= {1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000};
private final Signer signer;
private final int codeLength;
interface Signer {
byte[] sign(byte[] data) throws GeneralSecurityException;
}
public PasscodeGenerator(Signer signer, int passCodeLength) {
if ((passCodeLength < 0) || (passCodeLength > MAX_PASSCODE_LENGTH)) {
throw new IllegalArgumentException(
"PassCodeLength must be between 1 and " + MAX_PASSCODE_LENGTH
+ " digits.");
}
this.signer = signer;
this.codeLength = passCodeLength;
}
private String padOutput(int value) {
String result = Integer.toString(value);
for (int i = result.length(); i < codeLength; i++) {
result = "0" + result;
}
return result;
}
public String generateResponseCode(long state)
throws GeneralSecurityException {
byte[] value = ByteBuffer.allocate(8).putLong(state).array();
return generateResponseCode(value);
}
public String generateResponseCode(byte[] challenge)
throws GeneralSecurityException {
byte[] hash = signer.sign(challenge);
int offset = hash[hash.length - 1] & 0xF;
int truncatedHash = hashToInt(hash, offset) & 0x7FFFFFFF;
int pinValue = truncatedHash % DIGITS_POWER[codeLength];
return padOutput(pinValue);
}
private int hashToInt(byte[] bytes, int start) {
DataInput input = new DataInputStream(
new ByteArrayInputStream(bytes, start, bytes.length - start));
int val;
try {
val = input.readInt();
} catch (IOException e) {
throw new IllegalStateException(e);
}
return val;
}
}