Zig 中常量时间操作的长期计划,请参阅这项已接受的提案:https://github.com/ziglang/zig/issues/1776
std.crypto.timing_safe.add
函数
以常量时间将两个序列化为同大小数组的整数相加。
结果存入 result;若发生溢出,则返回 true。
pub fn add(comptime T: type, a: []const T, b: []const T, result: []T, endian: Endian) bool
参数
std.crypto.timing_safe.assert
别名
别名目标 std.debug.assert
std.crypto.timing_safe.classify
函数
将值标记为敏感或秘密数据,以帮助检测潜在的侧信道漏洞。
启用 Valgrind 时,此函数可检测依赖秘密或由秘密派生数据的条件跳转及查找。Valgrind 会将这些违规行为报告为依赖未初始化值的操作。
禁用 Valgrind 时,此函数无效。
使用此函数验证密码学操作对敏感数据执行常数时间算术,从而保护秘密的机密性,并防止通过侧信道泄露信息。
pub fn classify(ptr: anytype) void
用法示例
test classify {
const io = std.testing.io;
const expect = std.testing.expect;
var secret: [32]u8 = undefined;
io.random(&secret);
// 哈希函数的输入被标记为秘密数据。
classify(&secret);
var out: [32]u8 = undefined;
std.crypto.hash.sha3.TurboShake128(null).hash(&secret, &out, .{});
// 哈希函数的输出源自秘密数据,
// 因此也会自动视为秘密。但可以将其
// 解除保密;输入本身仍视为秘密。
declassify(&out);
// 以非常数时间比较公开数据可以接受。
const zeroes: [out.len]u8 = @splat(0);
try expect(!std.mem.eql(u8, &out, &zeroes));
// 比较秘密数据必须采用常量时间。
// 比较结果也视为秘密。
var res = std.crypto.timing_safe.eql([32]u8, out, secret);
// 若要根据秘密数据进行条件跳转,
// 必须先解除其保密标记。
declassify(&res);
try expect(!res);
// 秘密被解密级后,可以进行非常量时间比较。
//
declassify(&secret);
try expect(!std.mem.eql(u8, &out, &secret));
}
std.crypto.timing_safe.compare
函数
以常量时间比较两个序列化为相同大小数组的整数。 a<b 返回 .lt,a>b 返回 .gt,a=b 返回 .eq
pub fn compare(comptime T: type, a: []const T, b: []const T, endian: Endian) Order
参数
用法示例
test compare {
const expectEqual = std.testing.expectEqual;
var a: [32]u8 = @splat(10);
var b: [32]u8 = @splat(10);
try expectEqual(compare(u8, &a, &b, .big), .eq);
try expectEqual(compare(u8, &a, &b, .little), .eq);
a[31] = 1;
try expectEqual(compare(u8, &a, &b, .big), .lt);
try expectEqual(compare(u8, &a, &b, .little), .lt);
a[0] = 20;
try expectEqual(compare(u8, &a, &b, .big), .gt);
try expectEqual(compare(u8, &a, &b, .little), .lt);
}
std.crypto.timing_safe.declassify
函数
将值标记为非敏感或公开数据,表示可以安全地处理而不必担心侧信道攻击。
表明值已经过安全处理,不再保密,因此可放宽处理要求,无需担心通过条件跳转或查找泄露信息。
pub fn declassify(ptr: anytype) void
std.crypto.timing_safe.Endian
别名
别名目标 std.lang.Endian
std.crypto.timing_safe.eql
函数
以恒定时间(给定长度)比较两个数组,并返回它们是否相等。 此函数旨在比较短小的密码学秘密(MAC、签名)。 其他所有用途请改用 mem.eql()。
pub fn eql(comptime T: type, a: T, b: T) bool
参数
T: type
a: T
b: T
用法示例
test eql {
const io = std.testing.io;
const expect = std.testing.expect;
var a: [100]u8 = undefined;
var b: [100]u8 = undefined;
io.random(&a);
io.random(&b);
try expect(!eql([100]u8, a, b));
a = b;
try expect(eql([100]u8, a, b));
}
std.crypto.timing_safe.markSecret
函数
fn markSecret(ptr: anytype, comptime action: enum { classify, declassify }) void
参数
action: enum { classify, declassify }
std.crypto.timing_safe.Order
别名
别名目标 std.math.Order
std.crypto.timing_safe.std
别名
别名目标 std
std.crypto.timing_safe.sub
函数
以常数时间对序列化为等长数组的两个整数作减法。
结果存入 result;若发生下溢,则返回 true。
pub fn sub(comptime T: type, a: []const T, b: []const T, result: []T, endian: Endian) bool
参数
源码
std/crypto/timing_safe.zig
//! Zig 中常量时间操作的长期计划,请参阅这项已接受的提案:https://github.com/ziglang/zig/issues/1776
//!
const std = @import("../std.zig");
const assert = std.debug.assert;
const Endian = std.builtin.Endian;
const Order = std.math.Order;
/// 以恒定时间(给定长度)比较两个数组,并返回它们是否相等。
/// 此函数旨在比较短小的密码学秘密(MAC、签名)。
/// 其他所有用途请改用 mem.eql()。
pub fn eql(comptime T: type, a: T, b: T) bool {
switch (@typeInfo(T)) {
.array => |info| {
const C = info.child;
if (@typeInfo(C) != .int) {
@compileError("Elements to be compared must be integers");
}
var acc = @as(C, 0);
for (a, 0..) |x, i| {
acc |= x ^ b[i];
}
const s = @typeInfo(C).int.bits;
const Cu = @Int(.unsigned, s);
const Cext = @Int(.unsigned, s + 1);
return @as(bool, @bitCast(@as(u1, @truncate((@as(Cext, @as(Cu, @bitCast(acc))) -% 1) >> s))));
},
.vector => |info| {
const C = info.child;
if (@typeInfo(C) != .int) {
@compileError("Elements to be compared must be integers");
}
const acc = @reduce(.Or, a ^ b);
const s = @typeInfo(C).int.bits;
const Cu = @Int(.unsigned, s);
const Cext = @Int(.unsigned, s + 1);
return @as(bool, @bitCast(@as(u1, @truncate((@as(Cext, @as(Cu, @bitCast(acc))) -% 1) >> s))));
},
else => {
@compileError("Only arrays and vectors can be compared");
},
}
}
/// 以常量时间比较两个序列化为相同大小数组的整数。
/// a<b 返回 .lt,a>b 返回 .gt,a=b 返回 .eq
pub fn compare(comptime T: type, a: []const T, b: []const T, endian: Endian) Order {
assert(a.len == b.len);
const bits = switch (@typeInfo(T)) {
.int => |cinfo| if (cinfo.signedness != .unsigned) @compileError("Elements to be compared must be unsigned") else cinfo.bits,
else => @compileError("Elements to be compared must be integers"),
};
const Cext = @Int(.unsigned, bits + 1);
var gt: T = 0;
var eq: T = 1;
if (endian == .little) {
var i = a.len;
while (i != 0) {
i -= 1;
const x1 = a[i];
const x2 = b[i];
gt |= @as(T, @truncate((@as(Cext, x2) -% @as(Cext, x1)) >> bits)) & eq;
eq &= @as(T, @truncate((@as(Cext, (x2 ^ x1)) -% 1) >> bits));
}
} else {
for (a, 0..) |x1, i| {
const x2 = b[i];
gt |= @as(T, @truncate((@as(Cext, x2) -% @as(Cext, x1)) >> bits)) & eq;
eq &= @as(T, @truncate((@as(Cext, (x2 ^ x1)) -% 1) >> bits));
}
}
if (gt != 0) {
return Order.gt;
} else if (eq != 0) {
return Order.eq;
}
return Order.lt;
}
/// 以常量时间将两个序列化为同大小数组的整数相加。
/// 结果存入 `result`;若发生溢出,则返回 `true`。
pub fn add(comptime T: type, a: []const T, b: []const T, result: []T, endian: Endian) bool {
const len = a.len;
assert(len == b.len and len == result.len);
var carry: u1 = 0;
if (endian == .little) {
var i: usize = 0;
while (i < len) : (i += 1) {
const ov1 = @addWithOverflow(a[i], b[i]);
const ov2 = @addWithOverflow(ov1[0], carry);
result[i] = ov2[0];
carry = ov1[1] | ov2[1];
}
} else {
var i: usize = len;
while (i != 0) {
i -= 1;
const ov1 = @addWithOverflow(a[i], b[i]);
const ov2 = @addWithOverflow(ov1[0], carry);
result[i] = ov2[0];
carry = ov1[1] | ov2[1];
}
}
return @as(bool, @bitCast(carry));
}
/// 以常数时间对序列化为等长数组的两个整数作减法。
/// 结果存入 `result`;若发生下溢,则返回 `true`。
pub fn sub(comptime T: type, a: []const T, b: []const T, result: []T, endian: Endian) bool {
const len = a.len;
assert(len == b.len and len == result.len);
var borrow: u1 = 0;
if (endian == .little) {
var i: usize = 0;
while (i < len) : (i += 1) {
const ov1 = @subWithOverflow(a[i], b[i]);
const ov2 = @subWithOverflow(ov1[0], borrow);
result[i] = ov2[0];
borrow = ov1[1] | ov2[1];
}
} else {
var i: usize = len;
while (i != 0) {
i -= 1;
const ov1 = @subWithOverflow(a[i], b[i]);
const ov2 = @subWithOverflow(ov1[0], borrow);
result[i] = ov2[0];
borrow = ov1[1] | ov2[1];
}
}
return @as(bool, @bitCast(borrow));
}
fn markSecret(ptr: anytype, comptime action: enum { classify, declassify }) void {
const t = @typeInfo(@TypeOf(ptr));
if (t != .pointer) @compileError("Pointer expected - Found: " ++ @typeName(@TypeOf(ptr)));
const p = t.pointer;
if (p.attrs.@"allowzero") @compileError("A nullable pointer is always assumed to leak information via side channels");
const child = @typeInfo(p.child);
switch (child) {
.void, .null, .comptime_int, .comptime_float => return,
.pointer => {
if (child.pointer.size == .Slice) {
@compileError("Found pointer to pointer. If the intent was to pass a slice, maybe remove the leading & in the function call");
}
@compileError("A pointer value is always assumed leak information via side channels");
},
else => {
const mem8: *const [@sizeOf(@TypeOf(ptr.*))]u8 = @ptrCast(@constCast(ptr));
if (action == .classify) {
std.valgrind.memcheck.makeMemUndefined(mem8);
} else {
std.valgrind.memcheck.makeMemDefined(mem8);
}
},
}
}
/// 将值标记为敏感或秘密数据,以帮助检测潜在的侧信道漏洞。
///
/// 启用 Valgrind 时,此函数可检测依赖秘密或由秘密派生数据的条件跳转及查找。Valgrind 会将这些违规行为报告为依赖未初始化值的操作。
///
/// 禁用 Valgrind 时,此函数无效。
///
/// 使用此函数验证密码学操作对敏感数据执行常数时间算术,从而保护秘密的机密性,并防止通过侧信道泄露信息。
///
///
///
pub fn classify(ptr: anytype) void {
markSecret(ptr, .classify);
}
/// 将值标记为非敏感或公开数据,表示可以安全地处理而不必担心侧信道攻击。
///
/// 表明值已经过安全处理,不再保密,因此可放宽处理要求,无需担心通过条件跳转或查找泄露信息。
///
pub fn declassify(ptr: anytype) void {
markSecret(ptr, .declassify);
}
test eql {
const io = std.testing.io;
const expect = std.testing.expect;
var a: [100]u8 = undefined;
var b: [100]u8 = undefined;
io.random(&a);
io.random(&b);
try expect(!eql([100]u8, a, b));
a = b;
try expect(eql([100]u8, a, b));
}
test "eql (vectors)" {
const io = std.testing.io;
const expect = std.testing.expect;
var a: [100]u8 = undefined;
var b: [100]u8 = undefined;
io.random(&a);
io.random(&b);
const v1: @Vector(100, u8) = a;
const v2: @Vector(100, u8) = b;
try expect(!eql(@Vector(100, u8), v1, v2));
const v3: @Vector(100, u8) = a;
try expect(eql(@Vector(100, u8), v1, v3));
}
test compare {
const expectEqual = std.testing.expectEqual;
var a: [32]u8 = @splat(10);
var b: [32]u8 = @splat(10);
try expectEqual(compare(u8, &a, &b, .big), .eq);
try expectEqual(compare(u8, &a, &b, .little), .eq);
a[31] = 1;
try expectEqual(compare(u8, &a, &b, .big), .lt);
try expectEqual(compare(u8, &a, &b, .little), .lt);
a[0] = 20;
try expectEqual(compare(u8, &a, &b, .big), .gt);
try expectEqual(compare(u8, &a, &b, .little), .lt);
}
test "add and sub" {
const io = std.testing.io;
const expectEqual = std.testing.expectEqual;
const expectEqualSlices = std.testing.expectEqualSlices;
const len = 32;
var a: [len]u8 = undefined;
var b: [len]u8 = undefined;
var c: [len]u8 = undefined;
const zero: [len]u8 = @splat(0);
var iterations: usize = 100;
while (iterations != 0) : (iterations -= 1) {
io.random(&a);
io.random(&b);
const endian = if (iterations % 2 == 0) Endian.big else Endian.little;
_ = sub(u8, &a, &b, &c, endian); // a-b
_ = add(u8, &c, &b, &c, endian); // (a-b)+b
try expectEqualSlices(u8, &c, &a);
const borrow = sub(u8, &c, &a, &c, endian); // ((a-b)+b)-a
try expectEqualSlices(u8, &c, &zero);
try expectEqual(borrow, false);
}
}
test classify {
const io = std.testing.io;
const expect = std.testing.expect;
var secret: [32]u8 = undefined;
io.random(&secret);
// 哈希函数的输入被标记为秘密数据。
classify(&secret);
var out: [32]u8 = undefined;
std.crypto.hash.sha3.TurboShake128(null).hash(&secret, &out, .{});
// 哈希函数的输出源自秘密数据,
// 因此也会自动视为秘密。但可以将其
// 解除保密;输入本身仍视为秘密。
declassify(&out);
// 以非常数时间比较公开数据可以接受。
const zeroes: [out.len]u8 = @splat(0);
try expect(!std.mem.eql(u8, &out, &zeroes));
// 比较秘密数据必须采用常量时间。
// 比较结果也视为秘密。
var res = std.crypto.timing_safe.eql([32]u8, out, secret);
// 若要根据秘密数据进行条件跳转,
// 必须先解除其保密标记。
declassify(&res);
try expect(!res);
// 秘密被解密级后,可以进行非常量时间比较。
//
declassify(&secret);
try expect(!std.mem.eql(u8, &out, &secret));
}