com.outerspacecat.util.Totp.java Source code

Java tutorial

Introduction

Here is the source code for com.outerspacecat.util.Totp.java

Source

/**
 * Copyright 2011 Caleb Richardson
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.outerspacecat.util;

import com.google.common.base.Strings;

/**
 * Defines methods for working with the TOTP algorithm defined by <a
 * href="http://tools.ietf.org/html/rfc6238">RFC 6238</a>
 * 
 * @author Caleb Richardson
 */
public final class Totp {
    private Totp() {
    }

    /**
     * Generates a six digit time-based one-time password using the TOTP
     * algorithm.
     * 
     * @param k the secret key to use for the HMAC with SHA1 function. Must be non
     *        {@code null}, may be any length.
     * @param t a timestamp in seconds relative to the UNIX epoch
     * @return a six digit one-time password. Never {@code null}.
     */
    public static String totp(final byte[] k, final long t) {
        long steps = t / 30;

        byte[] c = new byte[] { (byte) (steps >>> 56), (byte) (steps >>> 48), (byte) (steps >>> 40),
                (byte) (steps >>> 32), (byte) (steps >>> 24), (byte) (steps >>> 16), (byte) (steps >>> 8),
                (byte) steps };

        byte[] hs = Utils.hmacSha1(c, k);

        int offset = 0x0F & hs[hs.length - 1];

        int binary = ((0x7F & hs[offset]) << 24) | ((0xFF & hs[offset + 1]) << 16) | ((0xFF & hs[offset + 2]) << 8)
                | (0xFF & hs[offset + 3]);

        int ret = binary % 1000000;

        return Strings.padStart(String.valueOf(ret), 6, '0');
    }
}