-
Notifications
You must be signed in to change notification settings - Fork 28
/
SecretGenerator.java
51 lines (41 loc) · 1.27 KB
/
SecretGenerator.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
package com.bastiaanjansen.otp;
import org.apache.commons.codec.binary.Base32;
import java.security.SecureRandom;
/**
* A secret generator to generate OTP secrets
*
* @author Bastiaan Jansen
*/
public class SecretGenerator {
private SecretGenerator() {}
/**
* Default amount of bits for secret generation
*/
public static final int DEFAULT_BITS = 160;
private static final SecureRandom random = new SecureRandom();
/**
* Generate an OTP base32 secret with default amount of bits
*
* @return generated secret
*/
public static byte[] generate() {
return generate(DEFAULT_BITS);
}
/**
* Generate an OTP base32 secret
*
* @param bits length, this should be greater than or equal to the length of the HMAC algorithm type:
* SHA1: 160 bits
* SHA256: 256 bits
* SHA512: 512 bits
* @return generated secret
*/
public static byte[] generate(final int bits) {
if (bits <= 0)
throw new IllegalArgumentException("Bits must be greater than or equal to 0");
byte[] bytes = new byte[bits / Byte.SIZE];
random.nextBytes(bytes);
Base32 encoder = new Base32();
return encoder.encode(bytes);
}
}