extract method to compute the totp code based on a pre-computed hmac
This will make it easier to add support for differen hmac algorithms, because we can reuse the method.
This commit is contained in:
15
src/main.zig
15
src/main.zig
@@ -99,16 +99,21 @@ const Authenticator = struct {
|
||||
|
||||
//debug("intervalNumber: {d}\n", .{intervalNumber});
|
||||
|
||||
var out: [std.crypto.auth.hmac.HmacSha1.mac_length]u8 = undefined;
|
||||
std.crypto.auth.hmac.HmacSha1.create(out[0..], &intervalAsU8Array, secret);
|
||||
//debug("hmac: {X}\n", .{out});
|
||||
if (std.mem.eql(u8, self.url.algorithm, "SHA1")) {
|
||||
var hmac: [std.crypto.auth.hmac.HmacSha1.mac_length]u8 = undefined;
|
||||
std.crypto.auth.hmac.HmacSha1.create(hmac[0..], &intervalAsU8Array, secret);
|
||||
return try self.generateTotp(allocator, &hmac);
|
||||
}
|
||||
unreachable;
|
||||
}
|
||||
|
||||
fn generateTotp(self: Authenticator, allocator: Allocator, hmac: []const u8) ![]const u8 {
|
||||
// take the 4 least significant bits of the hash and use them as byte offset
|
||||
const leastSignificantByte = out[std.crypto.auth.hmac.HmacSha1.mac_length - 1];
|
||||
const leastSignificantByte = hmac[hmac.len - 1];
|
||||
const byteIndex = leastSignificantByte & 0b1111;
|
||||
//debug("index: {d}\n", .{byteIndex});
|
||||
|
||||
const x: [4]u8 = [4]u8{ out[byteIndex], out[byteIndex + 1], out[byteIndex + 2], out[byteIndex + 3] };
|
||||
const x: [4]u8 = [4]u8{ hmac[byteIndex], hmac[byteIndex + 1], hmac[byteIndex + 2], hmac[byteIndex + 3] };
|
||||
|
||||
const tokenBase = std.mem.readInt(i32, &x, .big) & 0x7fffffff;
|
||||
//debug("tokenBase: {d}\n", .{tokenBase});
|
||||
|
||||
Reference in New Issue
Block a user