Sample code for 30+ languages & platforms
Zig

BIP39 Compute Binary Seed from Mnemonic

See more Encryption Examples

Creates a binary seed from a mnemonic. Uses the PBKDF2 function with a mnemonic sentence (in UTF-8 NFKD) used as the password and the string "mnemonic" + passphrase (again in UTF-8 NFKD) used as the salt. The iteration count is set to 2048 and HMAC-SHA512 is used as the pseudo-random function. The length of the derived key is 512 bits (= 64 bytes).

Chilkat Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    // This example assumes the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    const crypt = try chilkat.Crypt2.init();
    defer crypt.deinit();

    // Test with the test vectors at https://github.com/trezor/python-mnemonic/blob/master/vectors.json

    // This is the 2nd test vector..
    const mnemonic = "legal winner thank year wave sausage worth useful legal winner thank yellow";
    const passphrase = "TREZOR";
    const expected_seed = "2e8905819b8723fe2c1d161860e5ee1830318dbf49a83bd451cfb8440c28bd6fa457fe1296106559a3c80937a1c1069be3a3a5bd381ee6260e8d9739fce1f607";
    const expected_master_key = "xprv9s21ZrQH143K2gA81bYFHqU68xz1cX2APaSq5tt6MFSLeXnCKV1RVUJt9FWNTbrrryem4ZckN8k4Ls1H6nwdvDTvnV7zEXs2HgPezuVccsq";

    // The mnemonic sentence (in UTF-8 NFKD) used as the password.
    // The string "mnemonic" + passphrase (again in UTF-8 NFKD) used as the salt.
    // The iteration count is set to 2048 and HMAC-SHA512 is used as the pseudo-random function.
    // The length of the derived key is 512 bits (= 64 bytes).

    // We want the computed seed to be lowercase hex, therefore our salt must also be hex.
    // The seed is the keyword "mnemonic" + passphrase (in this case is "TREZOR") converted to hex.
    const bd_salt = try chilkat.BinData.init();
    defer bd_salt.deinit();
    bd_salt.appendString("mnemonic", "utf-8") catch {};
    bd_salt.appendString(passphrase, "utf-8") catch {};

    const computed_seed = try crypt.pbkdf2(alloc, mnemonic, "utf-8", "sha512", try bd_salt.getEncoded(alloc, "hex_lower"), 2048, 512, "hex_lower");

    std.debug.print("Expected: {s}\n", .{expected_seed});
    std.debug.print("Computed: {s}\n", .{computed_seed});

    // To compute the hd_master_key, duplicate this Python code:

    //     def to_hd_master_key(seed: bytes, testnet: bool = False) -> str:
    //         if len(seed) != 64:
    //             raise ValueError("Provided seed should have length of 64")
    //
    //         # Compute HMAC-SHA512 of seed
    //         seed = hmac.new(b"Bitcoin seed", seed, digestmod=hashlib.sha512).digest()
    //
    //         # Serialization format can be found at: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#Serialization_format
    //         xprv = b"\x04\x88\xad\xe4"  # Version for private mainnet
    //         if testnet:
    //             xprv = b"\x04\x35\x83\x94"  # Version for private testnet
    //         xprv += b"\x00" * 9  # Depth, parent fingerprint, and child number
    //         xprv += seed[32:]  # Chain code
    //         xprv += b"\x00" + seed[:32]  # Master key
    //
    //         # Double hash using SHA256
    //         hashed_xprv = hashlib.sha256(xprv).digest()
    //         hashed_xprv = hashlib.sha256(hashed_xprv).digest()
    //
    //         # Append 4 bytes of checksum
    //         xprv += hashed_xprv[:4]
    //
    //         # Return base58
    //         return b58encode(xprv)

    // First compute the HMAC-SHA512 of the computedSeed
    const bd_seed = try chilkat.BinData.init();
    defer bd_seed.deinit();
    bd_seed.appendEncoded(computed_seed, "hex_lower") catch {};
    crypt.setEncodingMode("hex_lower");
    crypt.setHashAlgorithm("sha512");
    crypt.setMacKeyString("Bitcoin seed") catch {};
    const hmac_sha512_hex = try crypt.macBdENC(alloc, bd_seed);

    const bd_hmac = try chilkat.BinData.init();
    defer bd_hmac.deinit();
    bd_hmac.appendEncoded(hmac_sha512_hex, "hex_lower") catch {};

    const bd_xprv = try chilkat.BinData.init();
    defer bd_xprv.deinit();
    bd_xprv.appendEncoded("0488ade4", "hex_lower") catch {};
    bd_xprv.appendEncoded("000000000000000000", "hex_lower") catch {};
    bd_xprv.appendEncoded(try bd_hmac.getEncodedChunk(alloc, 32, 32, "hex_lower"), "hex_lower") catch {};
    bd_xprv.appendByte(0) catch {};
    bd_xprv.appendEncoded(try bd_hmac.getEncodedChunk(alloc, 0, 32, "hex_lower"), "hex_lower") catch {};

    // Double hash using SHA256
    crypt.setEncodingMode("hex_lower");
    crypt.setHashAlgorithm("sha256");

    const bd_hash = try chilkat.BinData.init();
    defer bd_hash.deinit();
    bd_hash.appendEncoded(try crypt.hashBdENC(alloc, bd_xprv), "hex_lower") catch {};
    const second_hash = try crypt.hashBdENC(alloc, bd_hash);
    bd_hash.clear() catch {};
    bd_hash.appendEncoded(second_hash, "hex_lower") catch {};

    // Append the 1st 4 bytes of the bdHash to bdXprv.
    bd_xprv.appendEncoded(try bd_hash.getEncodedChunk(alloc, 0, 4, "hex_lower"), "hex_lower") catch {};

    // Base58 encode bdXprv
    const computed_master_key = try bd_xprv.getEncoded(alloc, "base58");

    std.debug.print("Expected Master Key: {s}\n", .{expected_master_key});
    std.debug.print("Computed Master Key: {s}\n", .{computed_master_key});
}