【Zig】Zig 中 Hash 的使用,如 Md5、Sha1

2022/8/11 6:26:51

本文主要是介绍【Zig】Zig 中 Hash 的使用,如 Md5、Sha1,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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..]) });
}


这篇关于【Zig】Zig 中 Hash 的使用,如 Md5、Sha1的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程