-
Notifications
You must be signed in to change notification settings - Fork 129
Expand file tree
/
Copy pathQrData.java
More file actions
104 lines (88 loc) · 2.99 KB
/
QrData.java
File metadata and controls
104 lines (88 loc) · 2.99 KB
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
package dev.samstevens.totp.qr;
import dev.samstevens.totp.code.HashingAlgorithm;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
@SuppressWarnings("WeakerAccess")
public final class QrData {
private final String type;
private final String label;
private final String secret;
private final String issuer;
private final String algorithm;
private final int digits;
private final int period;
/**
* Force use of builder to create instances.
*/
private QrData(String type, String label, String secret, String issuer, String algorithm, int digits, int period) {
this.type = type;
this.label = label;
this.secret = secret;
this.issuer = issuer;
this.algorithm = algorithm;
this.digits = digits;
this.period = period;
}
/**
* @return The URI/message to encode into the QR image, in the format specified here:
* https://github.com/google/google-authenticator/wiki/Key-Uri-Format
*/
public String getUri() {
return "otpauth://" +
uriEncode(type) + "/" +
uriEncode(label) + "?" +
"secret=" + uriEncode(secret) +
"&issuer=" + uriEncode(issuer) +
"&algorithm=" + uriEncode(algorithm) +
"&digits=" + digits +
"&period=" + period;
}
private String uriEncode(String text) {
// Null check
if (text == null) {
return "";
}
try {
return URLEncoder.encode(text, StandardCharsets.UTF_8.toString()).replaceAll("\\+", "%20");
} catch (UnsupportedEncodingException e) {
// This should never throw, as we are certain the charset specified (UTF-8) is valid
throw new RuntimeException("Could not URI encode QrData.");
}
}
public static class Builder {
private String label;
private String secret;
private String issuer;
private HashingAlgorithm algorithm = HashingAlgorithm.SHA1;
private int digits = 6;
private int period = 30;
public Builder label(String label) {
this.label = label;
return this;
}
public Builder secret(String secret) {
this.secret = secret;
return this;
}
public Builder issuer(String issuer) {
this.issuer = issuer;
return this;
}
public Builder algorithm(HashingAlgorithm algorithm) {
this.algorithm = algorithm;
return this;
}
public Builder digits(int digits) {
this.digits = digits;
return this;
}
public Builder period(int period) {
this.period = period;
return this;
}
public QrData build() {
return new QrData("totp", label, secret, issuer, algorithm.getFriendlyName(), digits, period);
}
}
}