Google OTP Generation Java
<p>I am currently trying to recreate a Google One Time Password generator. I use a shared secret generated when I setup Google Authenticator.
I tried looking into the Google Authenticator sources and all around the internet really and I find a lot of similarities with my code but I can't really find where i'm wrong.
The first part seems correct. As for the hmac, I don't think I could mess up here but I might be wrong. The truncating part is still a bit blurry for me and I tried a lot of different implementations but I just cannot get a working OTP. (I'm using Google Authenticator to compare the results)</p>

<pre><code>private String truncateHash(byte[] hash) {
    int offset = hash[hash.length - 1] &amp; 0xF;

    long truncatedHash = 0;
    for (int i = 0; i &lt; 4; ++i) {
        truncatedHash &lt;&lt;= 8;
        truncatedHash |= (hash[offset + i] &amp; 0xFF);
    }

    truncatedHash &amp;= 0x7FFFFFFF;
    truncatedHash %= 1000000;

    int code = (int) truncatedHash;
    String result = Integer.toString(code);
    for (int i = result.length(); i &lt; 6; i++) {
        result = "0" + result;
    }
    return result;
}

private byte[] hmacSha1(byte[] value, byte[] keyBytes) {
    try {
        Mac mac = HmacUtils.getHmacSha1(keyBytes);

        byte[] rawHmac = mac.doFinal(value);

        return new Hex().encode(rawHmac);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

public String GoogleAuthenticatorCode(String secret) throws UnsupportedEncodingException {
    Base32 base = new Base32();
    byte[] key = base.decode(secret);

    //Update from Andrew Rueckert's response
    long value = new Date().getTime() / TimeUnit.SECONDS.toMillis(30);

    byte[] data = new byte[8];
    for (int i = 8; i-- &gt; 0; value &gt;&gt;&gt;= 8) {
        data[i] = (byte) value;
    }
    //

    System.out.println("Time remaining : " + new Date().getTime() / 1000 % 30);

    byte[] hash = hmacSha1(data, key);

    return truncateHash(hash);
}
</code></pre>

<p><strong>UPDATE</strong> :
I tried copying and pasting the code from Andrew Rueckert's response's link as well as this one <code>https://github.com/wstrange/GoogleAuth/blob/master/src/main/java/com/warrenstrange/googleauth/GoogleAuthenticator.java</code> and the one from <code>RFC 4226</code>. Neither of these give me a correct OTP</p>

<p>Can anyone enlighten me please?</p>