跳转到内容

std.crypto.codecs.asn1.der.Decoder

标准库Zig 0.17.0官方原文
源码std/crypto/codecs/asn1/der/Decoder.zig

第 1 行

安全的 DER 解析器,具有以下特性:

  • 优先调用 fn decodeDer(self: @This(), decoder: *der.Decoder)。
  • 不分配内存。若需解析列表,可以通过不透明类型惰性处理。
  • 不读取 bytes 之外的内存。
  • 不返回切片超出 bytes 范围的元素。
  • 对不符合 DER 规则的值报错,包括:
    • 本可以使用更短形式表示的长度。
    • 不为 0xff 或 0x00 的布尔值。

字段

bytes: []const u8
index: Index = 0
field_tag: ?FieldTag = null

最近访问字段的字段标签。 这是必要的,因为可能会访问具有 fn decodeDer 的隐式标记容器。

std.crypto.codecs.asn1.der.Decoder.any

函数

第 17 行

预期为值。

pub fn any(self: *Decoder, comptime T: type) !T

参数

self: *Decoder
T: type

std.crypto.codecs.asn1.der.Decoder.asn1

别名

第 191 行

别名目标 std.crypto.codecs.asn1

std.crypto.codecs.asn1.der.Decoder.builtin

常量

第 190 行

std.crypto.codecs.asn1.der.Decoder.Decoder

别名

第 196 行

别名目标 std.crypto.codecs.asn1.der.Decoder

std.crypto.codecs.asn1.der.Decoder.element

函数

第 88 行

/ 预期一个元素。

pub fn element( self: *Decoder, expected: ExpectedTag, ) (error{ EndOfStream, UnexpectedElement } || Element.DecodeError)!Element

参数

self: *Decoder
expected: ExpectedTag

std.crypto.codecs.asn1.der.Decoder.Element

别名

第 201 行

别名目标 std.crypto.codecs.asn1.Element

std.crypto.codecs.asn1.der.Decoder.ExpectedTag

别名

第 200 行

别名目标 std.crypto.codecs.asn1.ExpectedTag

std.crypto.codecs.asn1.der.Decoder.expectEqual

别名

第 194 行

别名目标 std.testing.expectEqual

std.crypto.codecs.asn1.der.Decoder.expectError

别名

第 195 行

别名目标 std.testing.expectError

std.crypto.codecs.asn1.der.Decoder.FieldTag

别名

第 199 行

别名目标 std.crypto.codecs.asn1.FieldTag

std.crypto.codecs.asn1.der.Decoder.Index

别名

第 197 行

别名目标 std.crypto.codecs.asn1.Index

std.crypto.codecs.asn1.der.Decoder.int

函数

第 113 行

fn int(comptime T: type, value: []const u8) error{ NonCanonical, LargeValue }!T

参数

T: type
value: []const u8

错误

LargeValue
NonCanonical

用法示例

test int {
    try expectEqual(@as(u8, 1), try int(u8, &[_]u8{1}));
    try expectError(error.NonCanonical, int(u8, &[_]u8{ 0, 1 }));
    try expectError(error.NonCanonical, int(u8, &[_]u8{ 0xff, 0xff }));

    const big = [_]u8{ 0xef, 0xff };
    try expectError(error.LargeValue, int(u8, &big));
    try expectError(error.LargeValue, int(u16, &big));
    try expectEqual(@as(i16, -4097), try int(i16, &big));

    try expectEqual(@as(u16, 255), try int(u16, &.{ 0x00, 0xff }));
    try expectEqual(@as(u16, 0x8000), try int(u16, &.{ 0x00, 0x80, 0x00 }));

    try expectEqual(@as(i8, -1), try int(i8, &.{0xff}));
    try expectEqual(@as(i16, -1), try int(i16, &.{0xff}));
    try expectEqual(@as(i16, -128), try int(i16, &.{0x80}));
    try expectEqual(@as(i16, -129), try int(i16, &.{ 0xff, 0x7f }));
    try expectEqual(@as(i16, 255), try int(i16, &.{ 0x00, 0xff }));
    try expectEqual(@as(i32, 0x7fffffff), try int(i32, &.{ 0x7f, 0xff, 0xff, 0xff }));

    try expectError(error.LargeValue, int(i8, &.{ 0x00, 0xff }));
    try expectError(error.LargeValue, int(i16, &.{ 0x00, 0x80, 0x00 }));
    try expectError(error.LargeValue, int(i32, &.{ 0x00, 0x80, 0x00, 0x00, 0x00 }));

    try expectError(error.LargeValue, int(u8, &.{0xff}));
    try expectError(error.LargeValue, int(u16, &.{0x80}));
    try expectError(error.LargeValue, int(u32, &.{ 0x80, 0x00, 0x00, 0x00 }));
}

std.crypto.codecs.asn1.der.Decoder.Oid

别名

第 192 行

别名目标 std.crypto.codecs.asn1.Oid

std.crypto.codecs.asn1.der.Decoder.sequence

函数

第 83 行

/ 预期为序列。

pub fn sequence(self: *Decoder) !Element

参数

self: *Decoder

std.crypto.codecs.asn1.der.Decoder.std

别名

第 189 行

别名目标 std

std.crypto.codecs.asn1.der.Decoder.Tag

别名

第 198 行

别名目标 std.crypto.codecs.asn1.Tag

std.crypto.codecs.asn1.der.Decoder.view

函数

第 109 行

元素字节的视图。

pub fn view(self: Decoder, elem: Element) []const u8

参数

self: Decoder
elem: Element
源码

std/crypto/codecs/asn1/der/Decoder.zig

//! 安全的 DER 解析器,具有以下特性:
//! - 优先调用 `fn decodeDer(self: @This(), decoder: *der.Decoder)`。
//! - 不分配内存。若需解析列表,可以通过不透明类型惰性处理。
//! - 不读取 `bytes` 之外的内存。
//! - 不返回切片超出 `bytes` 范围的元素。
//! - 对不符合 DER 规则的值报错,包括:
//!   - 本可以使用更短形式表示的长度。
//!   - 不为 0xff 或 0x00 的布尔值。
//!
bytes: []const u8,
index: Index = 0,
/// 最近访问字段的字段标签。
/// 这是必要的,因为可能会访问具有 `fn decodeDer` 的隐式标记容器。
field_tag: ?FieldTag = null,

/// 预期为值。
pub fn any(self: *Decoder, comptime T: type) !T {
    if (std.meta.hasFn(T, "decodeDer")) return try T.decodeDer(self);

    const tag = Tag.fromZig(T).toExpected();
    switch (@typeInfo(T)) {
        .@"struct" => |info| {
            const ele = try self.element(tag);
            defer self.index = ele.slice.end; // 不强制解析所有字段

            var res: T = undefined;

            inline for (info.field_names, info.field_types, info.field_attrs) |f_name, f_type, f_attrs| {
                self.field_tag = FieldTag.fromContainer(T, f_name);

                if (self.field_tag) |ft| {
                    if (ft.explicit) {
                        const seq = try self.element(ft.toTag().toExpected());
                        self.index = seq.slice.start;
                        self.field_tag = null;
                    }
                }

                @field(res, f_name) = self.any(f_type) catch |err| brk: {
                    if (f_attrs.defaultValue(f_type)) |d| {
                        break :brk d;
                    }
                    return err;
                };
                // DER 通过跳过 null 值对其编码。
                if (@typeInfo(f_type) == .optional and @field(res, f_name) == null) {
                    if (f_attrs.defaultValue(f_type)) |d| @field(res, f_name) = d;
                }
            }

            return res;
        },
        .bool => {
            const ele = try self.element(tag);
            const bytes = self.view(ele);
            if (bytes.len != 1) return error.InvalidBool;

            return switch (bytes[0]) {
                0x00 => false,
                0xff => true,
                else => error.InvalidBool,
            };
        },
        .int => {
            const ele = try self.element(tag);
            const bytes = self.view(ele);
            return try int(T, bytes);
        },
        .@"enum" => |e| {
            const ele = try self.element(tag);
            const bytes = self.view(ele);
            if (@hasDecl(T, "oids")) {
                return T.oids.oidToEnum(bytes) orelse return error.UnknownOid;
            }
            return @fromBackingInt(@intCast(try int(e.tag_type, bytes)));
        },
        .optional => |o| return self.any(o.child) catch return null,
        else => @compileError("cannot decode type " ++ @typeName(T)),
    }
}

/// / 预期为序列。
pub fn sequence(self: *Decoder) !Element {
    return try self.element(ExpectedTag.init(.sequence, true, .universal));
}

/// / 预期一个元素。
pub fn element(
    self: *Decoder,
    expected: ExpectedTag,
) (error{ EndOfStream, UnexpectedElement } || Element.DecodeError)!Element {
    if (self.index >= self.bytes.len) return error.EndOfStream;

    const res = try Element.decode(self.bytes, self.index);
    var e = expected;
    if (self.field_tag) |ft| {
        e.number = @fromBackingInt(@intCast(ft.number));
        e.class = ft.class;
    }
    if (!e.match(res.tag)) {
        return error.UnexpectedElement;
    }

    self.index = if (res.tag.constructed) res.slice.start else res.slice.end;
    return res;
}

/// 元素字节的视图。
pub fn view(self: Decoder, elem: Element) []const u8 {
    return elem.slice.view(self.bytes);
}

fn int(comptime T: type, value: []const u8) error{ NonCanonical, LargeValue }!T {
    const info = @typeInfo(T).int;
    if (info.bits % 8 != 0) @compileError("T must be byte aligned");

    if (value.len == 0) return error.NonCanonical;
    if (value.len >= 2) {
        if (value[0] == 0x00 and value[1] & 0x80 == 0) return error.NonCanonical;
        if (value[0] == 0xff and value[1] & 0x80 != 0) return error.NonCanonical;
    }

    const had_sign_byte = value.len >= 2 and value[0] == 0x00;
    const bytes = if (had_sign_byte) value[1..] else value;
    const der_negative = !had_sign_byte and bytes[0] & 0x80 != 0;

    switch (info.signedness) {
        .unsigned => {
            if (der_negative) return error.LargeValue;
            if (bytes.len > @sizeOf(T)) return error.LargeValue;
        },
        .signed => {
            const max_len: usize = if (had_sign_byte) @sizeOf(T) - 1 else @sizeOf(T);
            if (bytes.len > max_len) return error.LargeValue;
        },
    }

    var buf: [@sizeOf(T)]u8 = @splat(if (der_negative) 0xff else 0);
    @memcpy(buf[buf.len - bytes.len ..], bytes);
    return std.mem.readInt(T, &buf, .big);
}

test int {
    try expectEqual(@as(u8, 1), try int(u8, &[_]u8{1}));
    try expectError(error.NonCanonical, int(u8, &[_]u8{ 0, 1 }));
    try expectError(error.NonCanonical, int(u8, &[_]u8{ 0xff, 0xff }));

    const big = [_]u8{ 0xef, 0xff };
    try expectError(error.LargeValue, int(u8, &big));
    try expectError(error.LargeValue, int(u16, &big));
    try expectEqual(@as(i16, -4097), try int(i16, &big));

    try expectEqual(@as(u16, 255), try int(u16, &.{ 0x00, 0xff }));
    try expectEqual(@as(u16, 0x8000), try int(u16, &.{ 0x00, 0x80, 0x00 }));

    try expectEqual(@as(i8, -1), try int(i8, &.{0xff}));
    try expectEqual(@as(i16, -1), try int(i16, &.{0xff}));
    try expectEqual(@as(i16, -128), try int(i16, &.{0x80}));
    try expectEqual(@as(i16, -129), try int(i16, &.{ 0xff, 0x7f }));
    try expectEqual(@as(i16, 255), try int(i16, &.{ 0x00, 0xff }));
    try expectEqual(@as(i32, 0x7fffffff), try int(i32, &.{ 0x7f, 0xff, 0xff, 0xff }));

    try expectError(error.LargeValue, int(i8, &.{ 0x00, 0xff }));
    try expectError(error.LargeValue, int(i16, &.{ 0x00, 0x80, 0x00 }));
    try expectError(error.LargeValue, int(i32, &.{ 0x00, 0x80, 0x00, 0x00, 0x00 }));

    try expectError(error.LargeValue, int(u8, &.{0xff}));
    try expectError(error.LargeValue, int(u16, &.{0x80}));
    try expectError(error.LargeValue, int(u32, &.{ 0x80, 0x00, 0x00, 0x00 }));
}

test Decoder {
    var parser = Decoder{ .bytes = @embedFile("./testdata/id_ecc.pub.der") };
    const seq = try parser.sequence();

    {
        const seq2 = try parser.sequence();
        _ = try parser.element(ExpectedTag.init(.oid, false, .universal));
        _ = try parser.element(ExpectedTag.init(.oid, false, .universal));

        try std.testing.expectEqual(parser.index, seq2.slice.end);
    }
    _ = try parser.element(ExpectedTag.init(.bitstring, false, .universal));

    try std.testing.expectEqual(parser.index, seq.slice.end);
    try std.testing.expectEqual(parser.index, parser.bytes.len);
}

const std = @import("std");
const builtin = @import("builtin");
const asn1 = @import("../../asn1.zig");
const Oid = @import("../Oid.zig");

const expectEqual = std.testing.expectEqual;
const expectError = std.testing.expectError;
const Decoder = @This();
const Index = asn1.Index;
const Tag = asn1.Tag;
const FieldTag = asn1.FieldTag;
const ExpectedTag = asn1.ExpectedTag;
const Element = asn1.Element;