From 404d6a18006346cbc32b82dca3f74d3e99ed5c1e Mon Sep 17 00:00:00 2001 From: Emil Lerch Date: Thu, 6 Jan 2022 14:34:45 -0800 Subject: [PATCH] fix memory corruption --- src/crypt.zig | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/crypt.zig b/src/crypt.zig index 3ef5095..33661fb 100644 --- a/src/crypt.zig +++ b/src/crypt.zig @@ -53,18 +53,20 @@ pub fn encryptWithKey(allocator: std.mem.Allocator, key: [key_size]u8, data: []u // deal with final block, PKCS#7 padding { - in = @ptrCast(*[block_size]u8, data[(total_blocks * block_size)..]); + // We can't just ptrcast into data as we are likely to run over the end + // of the data memory. We'll declare a new input buffer + var in_last: [block_size]u8 = undefined; const padding: u8 = @intCast(u8, block_size - (data.len % block_size)); var inx: u8 = 0; for (data[(total_blocks * block_size)..]) |b| { - in[inx] = b; + in_last[inx] = b; inx += 1; } while (inx < out.len) { - in[inx] = padding; + in_last[inx] = padding; inx += 1; } - ctx.encrypt(out[0..], in[0..]); + ctx.encrypt(out[0..], in_last[0..]); encrypted.appendSliceAssumeCapacity(out[0..]); } return encrypted.toOwnedSlice();