/** * This method creates a new random byte buffer from which a new scratch code is generated. This * function is invoked if a scratch code generated from the main buffer is invalid because it does * not satisfy the scratch code restrictions. * * @return A valid scratch code. */ private int generateScratchCode() { while (true) { byte[] scratchCodeBuffer = new byte[BYTES_PER_SCRATCH_CODE]; secureRandom.nextBytes(scratchCodeBuffer); int scratchCode = calculateScratchCode(scratchCodeBuffer); if (scratchCode != SCRATCH_CODE_INVALID) { return scratchCode; } } }
@Override public GoogleAuthenticatorKey createCredentials() { // Allocating a buffer sufficiently large to hold the bytes required by // the secret key and the scratch codes. byte[] buffer = new byte[SECRET_BITS / 8 + SCRATCH_CODES * BYTES_PER_SCRATCH_CODE]; secureRandom.nextBytes(buffer); // Extracting the bytes making up the secret key. byte[] secretKey = Arrays.copyOf(buffer, SECRET_BITS / 8); String generatedKey = calculateSecretKey(secretKey); // Generating the verification code at time = 0. int validationCode = calculateValidationCode(secretKey); // == calculateCode(secretKey, 0) // Calculate scratch codes List<Integer> scratchCodes = calculateScratchCodes(buffer); // List<Integer> scratchCodes = null; // System.out.println(generatedKey); // System.out.println(validationCode); return new GoogleAuthenticatorKey(generatedKey, validationCode, scratchCodes); }