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:
2024-09-09 15:08:05 +02:00
parent 0f5fd3f561
commit 8b452af848

View File

@@ -99,16 +99,21 @@ const Authenticator = struct {
//debug("intervalNumber: {d}\n", .{intervalNumber}); //debug("intervalNumber: {d}\n", .{intervalNumber});
var out: [std.crypto.auth.hmac.HmacSha1.mac_length]u8 = undefined; if (std.mem.eql(u8, self.url.algorithm, "SHA1")) {
std.crypto.auth.hmac.HmacSha1.create(out[0..], &intervalAsU8Array, secret); var hmac: [std.crypto.auth.hmac.HmacSha1.mac_length]u8 = undefined;
//debug("hmac: {X}\n", .{out}); 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 // 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; const byteIndex = leastSignificantByte & 0b1111;
//debug("index: {d}\n", .{byteIndex}); //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; const tokenBase = std.mem.readInt(i32, &x, .big) & 0x7fffffff;
//debug("tokenBase: {d}\n", .{tokenBase}); //debug("tokenBase: {d}\n", .{tokenBase});