diff options
author | Rutger Broekhoff | 2021-05-28 19:24:32 +0200 |
---|---|---|
committer | Rutger Broekhoff | 2021-05-28 19:24:32 +0200 |
commit | c68d1064921234bf6f0f8a69b3043b765ac4ae50 (patch) | |
tree | 10bc5407cee62683060bba06ee115af4acf157bd | |
parent | 31cc713dccab3e547169c790e8a3be694f1280b0 (diff) | |
download | zig-nkeys-c68d1064921234bf6f0f8a69b3043b765ac4ae50.tar.gz zig-nkeys-c68d1064921234bf6f0f8a69b3043b765ac4ae50.zip |
Prevent overflow calculating Base32-decoded size
-rw-r--r-- | src/base32.zig | 13 |
1 files 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 { | |||
155 | 155 | ||
156 | /// Calculate the size of a Base32-encoded array of bytes. | 156 | /// Calculate the size of a Base32-encoded array of bytes. |
157 | pub fn calcSize(source_len: usize) usize { | 157 | pub fn calcSize(source_len: usize) usize { |
158 | const source_len_bits = source_len * 5; | 158 | return safeMulDiv(source_len, 5, 8); |
159 | return source_len_bits / 8; | ||
160 | } | 159 | } |
161 | 160 | ||
162 | /// Decode a slice of Base32-encoded data. | 161 | /// Decode a slice of Base32-encoded data. |
@@ -231,6 +230,16 @@ pub const Decoder = struct { | |||
231 | } | 230 | } |
232 | }; | 231 | }; |
233 | 232 | ||
233 | // Taken from std.time. | ||
234 | // Calculate (a * b) / c without risk of overflowing too early because of the | ||
235 | // multiplication. | ||
236 | fn safeMulDiv(a: u64, b: u64, c: u64) u64 { | ||
237 | const q = a / c; | ||
238 | const r = a % c; | ||
239 | // (a * b) + (r * b) / c; | ||
240 | return (q * b) + (r * b) / c; | ||
241 | } | ||
242 | |||
234 | test { | 243 | test { |
235 | const encoded = "ORUGS4ZANFZSAYJAORSXG5A"; | 244 | const encoded = "ORUGS4ZANFZSAYJAORSXG5A"; |
236 | const decoded = "this is a test"; | 245 | const decoded = "this is a test"; |