private boolean checkCode ( String secret , long code , long timestamp , int window ) { byte [ ] decodedKey = decodeSecret ( secret ) ; // convert unix time into a 30 second "window" as specified by the // TOTP specification. Using Google's default interval of 30 seconds. final long timeWindow = getTimeWindowFromTime ( timestamp ) ; // Calculating the verification code of the given key in each of the // time intervals and returning true if the provided code is equal to // one of them. for ( int i = - ( ( window - 1 ) / 2 ) ; i <= window / 2 ; ++ i ) { // Calculating the verification code for the current time interval. long hash = calculateCode ( decodedKey , timeWindow + i ) ; // Checking if the provided code is equal to the calculated one. if ( hash == code ) { // The verification code is valid. return true ; } } // The verification code is invalid. return false ; }
This method implements the algorithm specified in RFC 6238 to check if a validation code is valid in a given instant of time for the given secret key .