MCPcopy Create free account
hub / github.com/027xiguapi/code-box / generateTOTPAtCounter

Method generateTOTPAtCounter

utils/totp.ts:34–56  ·  view source on GitHub ↗

* Generate TOTP at a specific counter value * @param secret Base32 encoded secret key * @param counter Time counter * @returns TOTP code

(
    secret: string,
    counter: number
  )

Source from the content-addressed store, hash-verified

32 * @returns TOTP code
33 */
34 private static generateTOTPAtCounter(
35 secret: string,
36 counter: number
37 ): string {
38 const decodedSecret = this.base32ToHex(secret)
39 const timeHex = this.leftPad(counter.toString(16), 16)
40
41 // Convert hex to WordArray for crypto-js
42 const key = CryptoJS.enc.Hex.parse(decodedSecret)
43 const message = CryptoJS.enc.Hex.parse(timeHex)
44
45 // Calculate HMAC-SHA1
46 const hmac = CryptoJS.HmacSHA1(message, key)
47 const hmacResult = hmac.toString()
48
49 const offset = parseInt(hmacResult.slice(-1), 16)
50 const code = parseInt(hmacResult.substr(offset * 2, 8), 16) & 0x7fffffff
51
52 return this.leftPad(
53 (code % Math.pow(10, this.DIGITS)).toString(),
54 this.DIGITS
55 )
56 }
57
58 /**
59 * Convert Base32 string to hexadecimal

Callers 1

generateTOTPMethod · 0.95

Calls 2

base32ToHexMethod · 0.95
leftPadMethod · 0.95

Tested by

no test coverage detected