Verification code generation tool google authenticator

Table of contents

1. Define the seed key

2. Generate a private key

3. Obtain verification on the app application according to the private key

4. Verify verification code


Application scenario: log in by generating a verification code through google authenticator

Principle: This article will not state anymore, refer to the online search results

Process: Define the seed secret key --> generate a private key --> obtain verification on the app according to the private key --> verify the verification code

app: ios and andriod apps will have certain differences, you can find them online, and ios can go to the app store to search for them

1. Define the seed key

The seed key defines a high-complexity key according to the project itself

this code

public static final String SEED = "F583513762484929976ED25B18FDE6B4";

The following tools are completed: define seed key --> generate private key

@Slf4j
public class GoogleAuthenticatorUtils {


    public static final int SECRET_SIZE = 10;//From Google documentation, no need to modify
    public static final String SEED = "F583513762484929976ED25B18FDE6B4";// Generate the seed seed key of the key One private key can generate multiple, in the main method
    public static final String RANDOM_NUMBER_ALGORITHM = "SHA1PRNG";//Secure Hash Algorithm
    private static Integer window_size = 3;//Shiftable time -- 3*30 seconds verification time (the client generates a verification code every 30 seconds)

    /**
     * generate key
     *
     * @return
     */
    public static String generateSecretKey() {
        SecureRandom sr;
        try {
            sr = SecureRandom.getInstance(RANDOM_NUMBER_ALGORITHM);
            sr.setSeed(Base64.decodeBase64(SEED));
            byte[] buffer = sr.generateSeed(SECRET_SIZE);
            Base32 codec = new Base32();
            byte[] bEncodedKey = codec.encode(buffer);
            return new String(bEncodedKey);
        } catch (Exception e) {
            log.error("generateSecretKey:" + e.getMessage(), e);
        }
        return null;
    }

    /**
     * Verification verification code
     *
     * @param secret
     * @param code
     * @param timeMsec
     * @return
     */
    public static Boolean check_code(String secret, long code, long timeMsec) {
        Base32 codec = new Base32();
        byte[] decodedKey = codec.decode(secret);
        long t = (timeMsec / 1000L) / 30L;
        for (int i = -window_size; i <= window_size; ++i) {
            long hash;
            try {
                hash = verify_code(decodedKey, t + i);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                throw new RuntimeException("Check exception");
            }
            if (hash == code) {
                return true;
            }
        }
        return false;
    }

    /**
     * Generate verification code
     *
     * @param key
     * @param t
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     */
    private static int verify_code(byte[] key, long t) throws NoSuchAlgorithmException, InvalidKeyException {
        byte[] data = new byte[8];
        long value = t;
        for (int i = 8; i-- > 0; value >>>= 8) {
            data[i] = (byte) value;
        }
        SecretKeySpec signKey = new SecretKeySpec(key, "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signKey);
        byte[] hash = mac.doFinal(data);
        int offset = hash[20 - 1] & 0xF;
        long truncatedHash = 0;
        for (int i = 0; i < 4; ++i) {
            truncatedHash <<= 8;
            truncatedHash |= (hash[offset + i] & 0xFF);
        }
        truncatedHash &= 0x7FFFFFFF;
        truncatedHash %= 1000000;
        return (int) truncatedHash;
    }

    public static void main(String[] args) {
        String secretKey = generateSecretKey();
        System.out.println(secretKey);
        Boolean aBoolean = check_code("KISNJ4O2OMHKB73F", Long.valueOf("943952"), System.currentTimeMillis());
        System.out.println(aBoolean);
    }

}

2. Generate a private key

String secretKey = generateSecretKey(); Generate a private key. The generated private key is configured in the app. The name is random, and the secret key is generated. In actual use, you may use the interface api or scan method to call the interface to obtain

3. Obtain verification on the app application according to the private key

     The generated private key is configured in the app, the name is random, the secret key is generated, and it can be obtained immediately

4. Verify verification code

Login verification is the core of this section, taking the private key configured by the user + the 6-digit verification code passed over

check_code("KISNJ4O2OMHKB73F", Long.valueOf("943952"), System.currentTimeMillis());

Regarding the private key, the QR code generation can be obtained through the online QR code generation tool, and the private key is configured in the database for subsequent login verification (that is, the actual verification result in the main method)

Search a bunch on the Internet: Online QR code generation tool can be generated and downloaded; for code, please refer to search for other related QR code generation tool codes

Guess you like

Origin blog.csdn.net/haohaounique/article/details/127031593