From c68d1064921234bf6f0f8a69b3043b765ac4ae50 Mon Sep 17 00:00:00 2001 From: Rutger Broekhoff Date: Fri, 28 May 2021 19:24:32 +0200 Subject: Prevent overflow calculating Base32-decoded size --- src/base32.zig | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/base32.zig b/src/base32.zig index 339566d..7beb43e 100644 --- a/src/base32.zig +++ b/src/base32.zig @@ -155,8 +155,7 @@ pub const Decoder = struct { /// Calculate the size of a Base32-encoded array of bytes. pub fn calcSize(source_len: usize) usize { - const source_len_bits = source_len * 5; - return source_len_bits / 8; + return safeMulDiv(source_len, 5, 8); } /// Decode a slice of Base32-encoded data. @@ -231,6 +230,16 @@ pub const Decoder = struct { } }; +// Taken from std.time. +// Calculate (a * b) / c without risk of overflowing too early because of the +// multiplication. +fn safeMulDiv(a: u64, b: u64, c: u64) u64 { + const q = a / c; + const r = a % c; + // (a * b) + (r * b) / c; + return (q * b) + (r * b) / c; +} + test { const encoded = "ORUGS4ZANFZSAYJAORSXG5A"; const decoded = "this is a test"; -- cgit v1.2.3