Are there any functions in the standard library to encrypt/decrypt data?

I’m planning on restarting a project which was originally written in go. I’m wondering if there’s a way to encrypt and decrypt data since it’s required for that project. It would be preferable if it’s a standard library function.

Yes, that is in the std.crypto module. (The name’s a little leery, but it’s cryptography, not apes.)


This might be too much to ask but can you give me little example? I don’t know much about the concepts of it.

To generate nonce use: std.crypt.random.bytes.
Use NaCl Secret Box to seal a message (encrypt) and open a box (decrypt).
If you want asymmetric keys use the NaCl Box or the libsodium SealedBox from std.crypto.nacl.

The video A tour of std.crypto have more in depth information.

1 Like

I’m gonna try it. Thank you so much.

I got this error when I tried it

error: root struct of file 'crypto' has no member named 'salsa20';

this is the version I use

>zig version
const std = @import("std");

test "crypto" {

    // key: generate once and share between parties
    const key_length = std.crypto.nacl.SecretBox.key_length;
    var key: [key_length]u8 = undefined;

    // nonce: generate unique each time
    const nonce_length = std.crypto.nacl.SecretBox.nonce_length;
    var nonce: [nonce_length]u8 = undefined;

    const message = "Hello World";

    // encrypt message
    const tag_length = std.crypto.nacl.SecretBox.tag_length;
    var cipher: [message.len + tag_length]u8 = undefined;
    std.crypto.nacl.SecretBox.seal(&cipher, message, nonce, key);

    // send cipher & nonce

    // decrypt msg
    var msg: [cipher.len - tag_length]u8 = undefined;
    try, &cipher, nonce, key);

    try std.testing.expectEqualStrings(message, &msg);

If you add cipher[0] = cipher[1]; to tamper between encrypt and decrypt the test fails:

1/1 test.test.crypto...FAIL (AuthenticationFailed)
/home/din/zig-0.13.0/lib/std/crypto/salsa20.zig:426:13: 0x1041da2 in decrypt (test)
            return error.AuthenticationFailed;
/home/din/zig-0.13.0/lib/std/crypto/salsa20.zig:461:9: 0x104021b in open (test)
        return XSalsa20Poly1305.decrypt(m, c[tag_length..], c[0..tag_length].*, "", npub, k);
/home/din/test.zig:27:5: 0x103fb16 in test.crypto (test)
    try, &cipher, nonce, key);