E不小心

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Zig 中做Md5 和 Sha1 之类的Hash 非常简单的,现在支持Hash 算法有,blanke2Blanke3GimliMd5Sha1sha2sha3,还有一个 组合 composition

Md5

pub fn md5() void {
    const Md5 = std.crypto.hash.Md5;

    var out: [Md5.digest_length]u8 = undefined;

    const input = "1234567890";

    Md5.hash(input, &out, .{});

    std.debug.print("\"{s}\" md5 code is {s}\n", .{ input, std.fmt.fmtSliceHexLower(out[0..]) });
}

"1234567890" md5 code is e807f1fcf82d132f9bb018ca6738a19f

Sha1

pub fn sha1() void {
    const Sha1 = std.crypto.hash.Sha1;

    var out: [Sha1.digest_length]u8 = undefined;

    const input = "1234567890";

    Sha1.hash(input, &out, .{});

    std.debug.print("\"{s}\" sha1 code is {s}\n", .{ input, std.fmt.fmtSliceHexLower(out[0..]) });
}

"1234567890" sha1 code is 01b307acba4f54f55aafc33bb06bbbf6ca803e9a

Composition

组合可以把两相同 api 的 hash 进行组合计算,默认提供了 Sha256oSha256、Sha384oSha384、Sha512oSha512。

我们可以试试来组合 Md5 和 Sha1,

pub fn composition() void {
    const Md5oSha1 = std.crypto.hash.composition.Composition(std.crypto.hash.Md5, std.crypto.hash.Sha1);

    var out: [Md5oSha1.digest_length]u8 = undefined;

    const input = "1234567890";

    Md5oSha1.hash(input, &out, .{});

    std.debug.print("\"{s}\" Md5oSha1 code is {s}\n", .{ input, std.fmt.fmtSliceHexLower(out[0..]) });
}

"1234567890" Md5oSha1 code is 1e0a1082ef56d0586330c3c46c5d46d1

这个组件的操作会先计算 Sha1 ,得到的结果再进行 Md5 计算。就相当于下面的代码:

pub fn md5OSha1() void {
    const Md5 = std.crypto.hash.Md5;
    const Sha1 = std.crypto.hash.Sha1;

    const input = "1234567890";

    var out: [Sha1.digest_length]u8 = undefined;
    var dest: [Md5.digest_length]u8 = undefined;

    Sha1.hash(input, &out, .{});

    Md5.hash(&out, &dest, .{});

    std.debug.print("\"{s}\" same Md5oSha1 code is {s}\n", .{ input, std.fmt.fmtSliceHexLower(dest[0..]) });
}
posted on 2022-08-10 20:55  E不小心  阅读(233)  评论(0编辑  收藏  举报