Standard library · Security and cryptography

tls

Secure TLS 1.3 and 1.2 connections and public key cryptography tools, with no OpenSSL needed.

import tls

The tls package is a complete implementation of TLS 1.2 and 1.3 written in Salam, with no outside library. A client connects with Dial and checks the server certificate against the system roots; a server reads its certificate and key with NewServerConfig and secures each accepted socket with WrapServer. Most programs never call it directly: net.http, net.email and net.websocket use it for https, SMTPS and wss. For code written in the OpenSSL style (a context, SSL_connect, SSL_read), ssl offers that interface on top of this package.

The cryptography tools here are also useful for protocols and storage of your own: the two sides make a shared secret with ECDH, derive a key from it with HKDF, and encrypt and seal the message with AES-GCM; P-256 signs and verifies. Keys and data are passed around as base64 text, which keeps binary bytes safe inside a str.

Things to know:

•

Check ConnOk after Dial. A failed handshake or a bad certificate gives a closed connection, and ConnError says why.

•

Read returns a str, which stops at a zero byte. For binary data use ReadBytes and WriteBytes with your own buffer.

•

Clients cannot present a certificate (no mutual TLS), and a Conn is passed by reference and belongs to one thread at a time.

•

Never repeat an AES-GCM nonce under one key; the sealing section shows a counter that avoids it.

•

AES-GCM runs on the processor's AES instructions when it has them: AES-NI and PCLMULQDQ on x86-64, the Crypto Extensions on AArch64, in every build made with the LLVM backend, which includes all releases. This covers AeadNew, the one shot AesGcmSealRaw and AesGcmOpenRaw and the TLS record layer, so the proxy and VPN protocols get it with no change. Other backends, and processors without the instructions, use the table based code, which gives the same bytes. cpu tells which path is in use and can force the software one.

Connect to a server and handle a bad certificate

Dial does the whole handshake and checks the certificate chain against the system roots and the name in NewConfig. When something is wrong, the connection is not open and ConnError says why: the certificate expired, it was issued for another name, or it does not chain to a trusted root. Always check ConnOk before you write. The program below tries a working site and three of the deliberately broken hosts at badssl.com.

tls-https-check.salam
import tls

func probe(host: str):
    cfg := tls.NewConfig(host)
    mut conn := tls.Dial(host, 443, cfg)
    if not tls.ConnOk(conn):
        println host, "refused:", tls.ConnError(conn)
        ret
    end
    println host, tls.Version(conn), tls.CipherName(conn), tls.PeerCertCount(conn), "certificates"
    tls.Close(conn)
end

func main:
    probe("www.salamlang.ir")
    probe("expired.badssl.com")
    probe("wrong.host.badssl.com")
    probe("self-signed.badssl.com")
end

It needs network access, so it is only checked here. When it was run, it printed the lines below; the cipher and the number of certificates depend on the server.

www.salamlang.ir TLS1.3 TLS_CHACHA20_POLY1305_SHA256 3 certificates
expired.badssl.com refused: certificate verification failed: certificate expired
wrong.host.badssl.com refused: certificate verification failed: hostname does not match certificate
self-signed.badssl.com refused: certificate verification failed: no trusted issuer found

For a private server with its own certificate authority, set ca_file in the config to that CA's PEM file. insecure_skip_verify turns the check off; use it only for a quick local test, never in a program others rely on.

Encrypt records with AES-GCM

AesGcmSeal encrypts a text and adds a tag, so that AesGcmOpen notices any change: a wrong key, a wrong nonce or a changed byte all make ok false instead of returning garbage. The key is 32 random bytes as base64; make it once with RandomSalt(32) and keep it secret. The nonce must never repeat under one key. The simple rule is a counter: GcmNonce(0) for the first message, GcmNonce(1) for the next, and the counter is stored next to the record so that it can be opened later.

tls-sealed-records.salam
import tls

func main:
    key := "q1V0kA8mY8l3R9m0bJvT0F6c0w2f5yYQ1aZt3pK8sXo="
    records := ["balance=120", "balance=95", "balance=310"]

    mut sealed := Vector {} as Vector<str>
    mut ok := false
    each i, r in records:
        sealed.Push(tls.AesGcmSeal(key, tls.GcmNonce(i as i64), r, ok))
    end
    println "sealed", sealed.Len(), "records:", ok
    println "first one:", sealed.Get(0)

    each i, s in sealed:
        plain := tls.AesGcmOpen(key, tls.GcmNonce(i as i64), s, ok)
        println "record", i, "->", plain, ok
    end

    _ := tls.AesGcmOpen(key, tls.GcmNonce(1), sealed.Get(0), ok)
    println "opened with the wrong nonce:", ok
    _ := tls.AesGcmOpen(
        "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=", tls.GcmNonce(0), sealed.Get(0), ok
    )
    println "opened with the wrong key:", ok
end
Output
sealed 3 records: true
first one: q/F2IqBhzaLO/CFJROFcuA2GEUtg3H4MyDU5
record 0 -> balance=120 true
record 1 -> balance=95 true
record 2 -> balance=310 true
opened with the wrong nonce: false
opened with the wrong key: false

With a fixed key and nonce the output is always the same, which is why the program can print it. That is also the danger: the same nonce for two different texts lets an attacker learn about both, so never reset the counter while the key stays the same.

A shared key from public keys

Two programs that have never met can agree on a key without sending it. Each makes an ECDH key pair with EcdhP256Generate and sends the other only its public key. EcdhP256Shared then gives both the same secret, and HkdfSha256 turns it into a key for AES-GCM. Someone who saw both public keys still cannot compute the secret. The info text names what the key is for, so one secret can safely give separate keys for separate uses.

tls-secure-channel.salam
import tls

struct Party:
    pub private_key: str = ""
    pub public_key: str = ""
end

func new_party(): Party:
    mut p := Party {}
    _ := tls.EcdhP256Generate(p.private_key, p.public_key)
    ret p
end

func session_key(me: Party, peer_public: str, salt: str): str:
    mut ok := false
    shared := tls.EcdhP256Shared(me.private_key, peer_public, ok)
    ret tls.HkdfSha256(shared, salt, "notes app v1 session", 32, ok)
end

func main:
    alice := new_party()
    bob := new_party()
    salt := tls.RandomSalt(16)

    alice_key := session_key(alice, bob.public_key, salt)
    bob_key := session_key(bob, alice.public_key, salt)
    println "both sides derived the same key:", alice_key == bob_key

    mut ok := false
    wire := tls.AesGcmSeal(alice_key, tls.GcmNonce(0), "meet at the station at nine", ok)
    println "alice sent", wire.Len(), "base64 characters"
    println "bob reads:", tls.AesGcmOpen(bob_key, tls.GcmNonce(0), wire, ok)

    eve := new_party()
    eve_key := session_key(eve, alice.public_key, salt)
    _ := tls.AesGcmOpen(eve_key, tls.GcmNonce(0), wire, ok)
    println "eve, with only the public keys, can read it:", ok
end
Output
both sides derived the same key: true
alice sent 60 base64 characters
bob reads: meet at the station at nine
eve, with only the public keys, can read it: false

ECDH alone does not tell you who is on the other side. In a real protocol, sign the public key, or check it against one you already know, or someone in the middle can make a key with each side.

Sign and verify with P-256

P256Sign signs a SHA-256 digest with a private key, and anyone with the public point can check it with P256Verify. It suits licence files, update manifests and messages that must be checked by many readers but written by one. The signature follows RFC 6979, so the same key and digest always give the same signature and no random number generator is involved.

tls-signed-license.salam
import tls
import crypto
import encoding
import mem

func digest_of(text: str): str:
    out := mem.Allocate(32 as u64)
    crypto.Sha256Bytes(text as void*, text.Len(), out)
    d := encoding.Base64EncodeBytes(out, 32)
    mem.Free(out)
    ret d
end

func main:
    vendor_private := "cqXpGz8zHwUzjEQonZMVMh4K9+jyX3zMfzeFP0025Rk="
    vendor_public := tls.EcdhP256PublicPoint(vendor_private)

    license := "customer=Pars Co;seats=25;until=2027-12-31"
    mut ok := false
    signature := tls.P256Sign(vendor_private, digest_of(license), ok)
    println "signed:", ok
    println "signature:", signature

    println "genuine license:", tls.P256Verify(vendor_public, digest_of(license), signature)
    edited := "customer=Pars Co;seats=250;until=2027-12-31"
    println "seats edited:", tls.P256Verify(vendor_public, digest_of(edited), signature)
    println "same signature again:",
        tls.P256Sign(vendor_private, digest_of(license), ok) == signature
end
Output
signed: true
signature: Z9NSfoPJN31QJ2ELmSVzzziGYOZrA/+elf2AUQXUjx4uBr0U+Pyx7HxCt/gsuGacDKrD0KcJ6g1KkSOOjI1Hlg==
genuine license: true
seats edited: false
same signature again: true

The private key in the program is there so that the output stays the same. Keep a real one out of the source code: read it from a file or the environment, and ship only the public point with the program that checks.

Which function for which job

JobUse
An HTTPS or other TLS clientNewConfig, Dial, Write, Read, Close; for plain web requests, net.http does this for you
A TLS serverNewServerConfig, then WrapServer on each accepted socket
Upgrade a socket that is already open (STARTTLS)WrapClient
Encrypt data at restAesGcmSeal, AesGcmOpen, GcmNonce
Agree on a keyEcdhP256Generate, EcdhP256Shared, HkdfSha256
Sign and verifyP256Sign, P256Verify
Check a certificate yourselfLoadRoots, VerifyCert, VerifyError

Types

Config

#
struct Config

The client configuration.

NameTypeDescription
server_namestr = ""The hostname for SNI and for certificate verification.
ca_filestr = ""The file of root certificates; empty means the system roots.
insecure_skip_verifybool = falseDo not verify the certificate; for testing only, since it leaves the connection open to eavesdropping.
skip_hostname_checkbool = falseDo not match the certificate against the server name. The chain is still verified against the CA; use it for a mode that checks the CA only.
alpnstr = ""The protocol for ALPN, such as h2.
aes_onlybool = falseOffer AES ciphers only.
frag_tlsbool = falseSplit the first handshake message (the ClientHello) into several TLS records, so that a middlebox that reads only the first record never sees the whole hello. Off by default.
frag_tcpbool = falseSend the first flight as several small TCP writes, with frag_delay_ms between them, so that it does not travel in one packet. Off by default.
frag_snibool = falseMake one cut in the middle of the server name, so no single record or packet holds the whole name. Used with frag_tls or frag_tcp.
frag_minint = 5The smallest piece in bytes when the hello is cut up. The default is 5.
frag_maxint = 20The largest piece in bytes when the hello is cut up. The default is 20; a random size between frag_min and this is taken for each piece.
frag_delay_msint = 0The pause in milliseconds between TCP pieces. The default is 0.
frag_writesint = 1How many of the first handshake writes are cut up. The default is 1, which is the ClientHello.
tls-Client.salam
import tls

func main:
    mut cfg := tls.NewConfig("example.com")
    cfg.alpn = "http/1.1"
    mut conn := tls.Dial("example.com", 443, cfg)
    if not tls.ConnOk(conn):
        println "error:", tls.ConnError(conn)
        ret
    end
    println tls.Version(conn), tls.CipherName(conn), tls.PeerCertCount(conn)
    _ := tls.Write(conn, "GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n")
    mut body := ""
    until tls.ConnOk(conn):
        chunk := tls.Read(conn, 4096)
        if chunk.Len() == 0:
            break
        end
        body += chunk
    end
    println body.Len() > 0
    tls.Close(conn)
end

Conn

#
struct Conn

One TLS connection.

NameTypeDescription
hHandshakeThe handshake state.
hoststr = ""The host.
openbool = falseThe connection is open.
insecurebool = falseWithout certificate verification.
pendingBufData that has been read but not taken yet.
errstr = ""The error message.
rdonebool = falseTrue once the other side sent its close alert, so no more data will arrive.
wdonebool = falseTrue once CloseWrite has sent our close alert, so nothing more may be written.
directbool = falseTrue after SwitchDirect: reads skip the record layer.

The example for this item is shown with the ones above: tls-Client.salam

ServerConfig

#
struct ServerConfig

The server configuration: the certificate chain and the private key.

NameTypeDescription
chainRootsThe certificate chain.
keyPrivateKeyThe private key.
okbool = falseBoth were read.
tls-Server.salam
import tls
import net.tcp
import mem

func main:
    cfg := tls.NewServerConfig("cert.pem", "key.pem")
    if not cfg.ok:
        println "the certificate or key could not be read"
        ret
    end
    server := tcp.Bind(8443)
    until true:
        sock := tcp.Accept(server)
        mut conn := tls.WrapServer(sock.fd, cfg)
        if tls.ConnOk(conn):
            if tls.Readable(conn) or tls.Pending(conn) > 0:
                println tls.Read(conn, 1024)
            end
            buffer := mem.Allocate(256 as u64)
            n := tls.ReadBytes(conn, buffer, 256)
            _ := tls.WriteBytes(conn, buffer, n)
            tls.Cork(conn)
            _ := tls.Write(conn, "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello")
            _ := tls.Flush(conn)
            mem.Free(buffer)
            println tls.Fd(conn) >= 0
        end
        tls.Close(conn)
    end
end

Constants and variables

TLS10

#
const TLS10: i32 = 769

The version number of TLS 1.0; not supported.

tls-Certs.salam
import tls
import net.tcp
import encoding
import io

func main:
    mut roots := tls.LoadRoots("/etc/ssl/cert.pem")
    println tls.RootCount(roots)

    chain := tls.LoadCertChainFile("cert.pem")
    println tls.RootCount(chain)
    mut key := tls.LoadPrivateKeyFile("key.pem")
    mut key2 := tls.ParsePrivateKeyPEM("-----BEGIN ...")
    tls.FreePrivateKey(key2)

    cert := tls.HexDecodeBuf("3082...")
    println tls.CertIsValid(cert), tls.CertSubjectCN(cert)
    code := tls.VerifyCert(cert, roots, "example.com")
    println code, tls.VerifyError(code)

    digest := tls.HashDigest(false, "message")
    mut sig := tls.NewBuf(512)
    println tls.SignRSAPKCS1(key, false, digest, sig)
    println tls.SignRSAPSS(key, false, digest, sig)
    println tls.VerifyRSAPSSWithKey(key, false, digest, sig)
    r := tls.NewBuf(32)
    s := tls.NewBuf(32)
    if tls.SignECDSA(key, digest, r, s):
        der := tls.ECDSADerEncode(r, s, 32)
        println tls.VerifyECDSADERWithKey(key, digest, der)
    end

    pem := io.ReadFile("rsa-key.pem")
    mut good := false
    println tls.RsaKeyBits(pem)
    println tls.RsaSignPkcs1Sha256(pem, encoding.Base64Encode("..."), good)

    mut cfg := tls.NewConfig("internal.example")
    cfg.ca_file = "company-ca.pem"
    cfg.aes_only = true
    mut conn := tls.Dial("internal.example", 443, cfg)
    println tls.ConnOk(conn)
    tls.Close(conn)
    sock := tcp.Dial("example.com", 443)
    mut conn2 := tls.WrapClient(sock.fd, tls.NewConfig("example.com"))
    println tls.Version(conn2) == "TLS1.3"
    tls.Close(conn2)
    println tls.TLS10, tls.TLS11, tls.TLS12, tls.TLS13
    println tls.SelfTest()
    tls.FreeRoots(roots)
    tls.FreePrivateKey(key)
end

TLS11

#
const TLS11: i32 = 770

TLS 1.1; not supported.

The example for this item is shown with the ones above: tls-Certs.salam

TLS12

#
const TLS12: i32 = 771

TLS 1.2.

The example for this item is shown with the ones above: tls-Certs.salam

TLS13

#
const TLS13: i32 = 772

TLS 1.3.

The example for this item is shown with the ones above: tls-Certs.salam

AEAD_AES_128_GCM

#
const AEAD_AES_128_GCM: i32 = 0

The cipher number of AES-128-GCM for AeadNew; its key is 16 bytes.

tls-Aead.salam
import tls
import mem

const DIGITS := "0123456789abcdef"

func hex_of(p: void*, n: int): str:
    mut out := ""
    repeat n in i:
        b := (p as u8*)[i] as int
        out += DIGITS.Substr(b / 16, 1) + DIGITS.Substr(b % 16, 1)
    end
    ret out
end

func filled(n: int, start: int): void*:
    p := mem.AllocateZeroed(n as u64)
    repeat n in i:
        (p as u8*)[i] = ((start + i) % 256) as u8
    end
    ret p
end

func main:
    println tls.AEAD_AES_128_GCM, tls.AEAD_AES_256_GCM, tls.AEAD_CHACHA20_POLY1305
    println tls.AEAD_TAG_LEN, tls.AEAD_NONCE_LEN
    println tls.AeadKeyLen(tls.AEAD_AES_128_GCM),
        tls.AeadKeyLen(tls.AEAD_AES_256_GCM),
        tls.AeadKeyLen(tls.AEAD_CHACHA20_POLY1305)

    key := filled(32, 0)
    nonce := filled(12, 100)
    message := "attack at dawn"
    n := message.Len()
    out := mem.AllocateZeroed((n + tls.AEAD_TAG_LEN) as u64)
    back := mem.AllocateZeroed((n + 1) as u64)

    each kind in [tls.AEAD_AES_128_GCM, tls.AEAD_AES_256_GCM, tls.AEAD_CHACHA20_POLY1305]:
        ctx := tls.AeadNew(kind, key)
        tls.AeadSeal(ctx, nonce, null, 0, message as void*, n, out)
        println kind, hex_of(out, n + tls.AEAD_TAG_LEN)
        println tls.AeadOpen(ctx, nonce, null, 0, out, n, back), (back as str).Substr(0, n)
        (out as u8*)[0] = ((out as u8*)[0] as int ^ 1) as u8
        println tls.AeadOpen(ctx, nonce, null, 0, out, n, back)
        tls.AeadFree(ctx)
    end

    println tls.AesGcmSealRaw(key, 16, nonce, null, 0, message as void*, n, out)
    println hex_of(out, n + tls.AEAD_TAG_LEN)
    println tls.AesGcmOpenRaw(key, 16, nonce, null, 0, out, n + tls.AEAD_TAG_LEN, back),
        (back as str).Substr(0, n)

    println tls.ChaCha20Poly1305SealRaw(key, nonce, null, 0, message as void*, n, out)
    println hex_of(out, n + tls.AEAD_TAG_LEN)
    println tls.ChaCha20Poly1305OpenRaw(key, nonce, null, 0, out, n + tls.AEAD_TAG_LEN, back),
        (back as str).Substr(0, n)

    nonce24 := filled(24, 100)
    println tls.XChaCha20Poly1305SealRaw(key, nonce24, null, 0, message as void*, n, out)
    println hex_of(out, n + tls.AEAD_TAG_LEN)
    println tls.XChaCha20Poly1305OpenRaw(key, nonce24, null, 0, out, n + tls.AEAD_TAG_LEN, back),
        (back as str).Substr(0, n)

    plain := mem.AllocateZeroed(16 as u64)
    repeat 16 in i:
        (plain as u8*)[i] = (i * 17) as u8
    end
    cipher := mem.AllocateZeroed(16 as u64)
    key16 := filled(16, 0)
    println tls.AesEcbBlock(key16, 16, plain, cipher, false), hex_of(cipher, 16)
    println tls.AesEcbBlock(key16, 16, cipher, back, true), hex_of(back, 16) == hex_of(plain, 16)

    mem.Free(key)
    mem.Free(nonce)
    mem.Free(nonce24)
    mem.Free(out)
    mem.Free(back)
    mem.Free(plain)
    mem.Free(cipher)
    mem.Free(key16)
end
Output
0 1 2
16 12
16 32 32
0 7b163ac4b869989bef1e3371f1a41dc78d25d87c287515a3bf23f863acc9
true attack at dawn
false
1 296faa071a8276ff4a423b89ad0b5537a90cc7db07314a46d350158ee5c0
true attack at dawn
false
2 5565cfabfbce56338ffe711e85e78bbd1978d881377eec1a128409ee14bd
true attack at dawn
false
true
7b163ac4b869989bef1e3371f1a41dc78d25d87c287515a3bf23f863acc9
true attack at dawn
true
5565cfabfbce56338ffe711e85e78bbd1978d881377eec1a128409ee14bd
true attack at dawn
true
1d078dd19c45a9e3f310f95ed1019b35c7694970811df3af39456b18b9ba
true attack at dawn
true 69c4e0d86a7b0430d8cdb78070b4c55a
true true

AEAD_AES_256_GCM

#
const AEAD_AES_256_GCM: i32 = 1

The cipher number of AES-256-GCM for AeadNew; its key is 32 bytes.

The example for this item is shown with the ones above: tls-Aead.salam

AEAD_CHACHA20_POLY1305

#
const AEAD_CHACHA20_POLY1305: i32 = 2

The cipher number of ChaCha20-Poly1305 for AeadNew; its key is 32 bytes.

The example for this item is shown with the ones above: tls-Aead.salam

AEAD_TAG_LEN

#
const AEAD_TAG_LEN: i32 = 16

The length of the authentication tag that sealing adds after the encrypted bytes: 16.

The example for this item is shown with the ones above: tls-Aead.salam

AEAD_NONCE_LEN

#
const AEAD_NONCE_LEN: i32 = 12

The length of the nonce of these ciphers in bytes: 12.

The example for this item is shown with the ones above: tls-Aead.salam

Functions

XChaCha20Poly1305SealRaw

#
func XChaCha20Poly1305SealRaw(key: void*, nonce24: void*, aad: void*, aadlen: int, pt: void*, n: int, out: void*): bool

One shot ChaCha20-Poly1305 with a 24 byte nonce: a one time key is derived from the key and the first 16 bytes of the nonce, which makes random nonces safe. Writes n encrypted bytes and the 16 byte tag to out.

The example for this item is shown with the ones above: tls-Aead.salam

XChaCha20Poly1305OpenRaw

#
func XChaCha20Poly1305OpenRaw(key: void*, nonce24: void*, aad: void*, aadlen: int, sealed: void*, sealed_len: int, out: void*): bool

The reverse of XChaCha20Poly1305SealRaw: sealed_len counts the tag too. Returns false when the data is too short or was changed.

The example for this item is shown with the ones above: tls-Aead.salam

AesEcbBlock

#
func AesEcbBlock(key: void*, keylen: int, inp: void*, out: void*, decrypt: bool): bool

Encrypts or decrypts one 16 byte block with AES, for a key of 16 or 32 bytes, without chaining. It is a building block for protocol headers, not a way to encrypt messages. Returns false for a bad key length.

The example for this item is shown with the ones above: tls-Aead.salam

NewConfig

#
func NewConfig(server_name: str): Config

A client configuration for one host.

The example for this item is shown with the ones above: tls-Client.salam

Dial

#
func Dial(host: str, port: int, cfg: Config): Conn

Connects to the host and does the TLS 1.3 or 1.2 handshake.

The example for this item is shown with the ones above: tls-Client.salam

WrapClient

#
func WrapClient(fd: i64, cfg: Config): Conn

Does the client handshake over an open TCP socket.

The example for this item is shown with the ones above: tls-Certs.salam

NewServerConfig

#
func NewServerConfig(cert_file: str, key_file: str): ServerConfig

Reads the server certificate and key from PEM files.

The example for this item is shown with the ones above: tls-Server.salam

WrapServer

#
func WrapServer(fd: i64, cfg: ServerConfig): Conn

Does the server handshake over a socket you accepted.

The example for this item is shown with the ones above: tls-Server.salam

ConnOk

#
func ConnOk(c: Conn): bool

The connection is healthy.

The example for this item is shown with the ones above: tls-Client.salam

ConnError

#
func ConnError(c: Conn): str

The error message of the connection.

The example for this item is shown with the ones above: tls-Client.salam

Write

#
func Write(c &: Conn, data: str): int

Sends data and returns the number of bytes.

The example for this item is shown with the ones above: tls-Client.salam

WriteBytes

#
func WriteBytes(c &: Conn, ptr: void*, n: int): int

Sends bytes from memory.

The example for this item is shown with the ones above: tls-Server.salam

Cork

#
func Cork(c &: Conn)

Hold written records back until Flush, so a response that takes several writes goes out in one send.

The example for this item is shown with the ones above: tls-Server.salam

Flush

#
func Flush(c &: Conn): bool

Send the records held back by Cork.

The example for this item is shown with the ones above: tls-Server.salam

Read

#
func Read(c &: Conn, max: int): str

Reads up to this many bytes as a string; an empty string means the connection closed or a time limit ran out. The text stops at a zero byte, so use ReadBytes for binary data.

The example for this item is shown with the ones above: tls-Client.salam

ReadBytes

#
func ReadBytes(c &: Conn, buf: void*, max: int): int

Reads up to max bytes into the given memory and returns how many; 0 when the connection closed.

The example for this item is shown with the ones above: tls-Server.salam

SwitchDirect

#
func SwitchDirect(c &: Conn)

Makes later reads come straight from the socket, for the moment a peer using XTLS Vision sends its direct command. Bytes that were already read ahead are handed out first.

Pending

#
func Pending(c: Conn): int

The bytes that are decrypted and ready to read.

The example for this item is shown with the ones above: tls-Server.salam

Readable

#
func Readable(c: Conn): bool

There is something to read without waiting.

The example for this item is shown with the ones above: tls-Server.salam

Fd

#
func Fd(c: Conn): i64

The descriptor of the socket underneath.

The example for this item is shown with the ones above: tls-Server.salam

CloseWrite

#
func CloseWrite(c &: Conn)

Half-close: sends the close alert and shuts down the sending side of the socket but keeps the receiving side open, so the other side sees the end of your data and can still answer. Call Close afterwards. It does nothing when the write side is already finished.

tls-CloseWrite.salam
import tls
import net.tcp

func main:
    cfg := tls.NewServerConfig("cert.pem", "key.pem")
    if not cfg.ok:
        println "the certificate or key could not be read"
        ret
    end
    server := tcp.Bind(8443)
    sock := tcp.Accept(server)
    mut conn := tls.WrapServer(sock.fd, cfg)
    if tls.ConnOk(conn):
        mut request := ""
        until true:
            part := tls.Read(conn, 1024)
            if part.Len() == 0:
                break
            end
            request += part
        end
        println request.Len(), conn.rdone
        _ := tls.Write(conn, "received " + request.Len() + " bytes")
        tls.CloseWrite(conn)
    end
    tls.Close(conn)
    tcp.CloseServer(server)
end

Detach

#
func Detach(c &: Conn)

Sends the close alert and frees the TLS state, but leaves the socket open.

tls-Detach.salam
import tls
import net.tcp

func main:
    sock := tcp.Dial("example.com", 443)
    if not tcp.ConnOk(sock):
        println "the connection was not made"
        ret
    end
    mut conn := tls.WrapClient(sock.fd, tls.NewConfig("example.com"))
    println tls.ConnOk(conn)
    tls.Detach(conn)
    tcp.Close(sock)
end

Close

#
func Close(c &: Conn)

Sends the close alert and closes the socket.

The example for this item is shown with the ones above: tls-Client.salam

Version

#
func Version(c: Conn): str

The agreed version, such as TLS1.3.

The example for this item is shown with the ones above: tls-Client.salam

CipherName

#
func CipherName(c: Conn): str

The name of the agreed cipher.

The example for this item is shown with the ones above: tls-Client.salam

PeerCertCount

#
func PeerCertCount(c: Conn): int

The number of certificates the other side sent.

The example for this item is shown with the ones above: tls-Client.salam

EcdhP256Generate

#
func EcdhP256Generate(priv &: str, pub_spki &: str): bool

An ECDH key pair on the P-256 curve: the private key as base64 and the SPKI public key as base64.

tls-Crypto.salam
import tls
import encoding

func main throw:
    mut priv1 := ""
    mut pub1 := ""
    mut priv2 := ""
    mut pub2 := ""
    println tls.EcdhP256Generate(priv1, pub1), tls.EcdhP256Generate(priv2, pub2)
    mut good := false
    secret1 := tls.EcdhP256Shared(priv1, pub2, good)
    secret2 := tls.EcdhP256Shared(priv2, pub1, good)
    println good, secret1 == secret2

    point1 := tls.EcdhP256PublicPoint(priv1)
    point2 := tls.EcdhP256PublicPoint(priv2)
    println tls.EcdhP256SharedPoint(
        priv1, point2, good
    ) == tls.EcdhP256SharedPoint(priv2, point1, good)

    salt := tls.RandomSalt(16)
    key := tls.HkdfSha256(secret1, salt, "chat v1", 32, good)
    println good, key == tls.HkdfSha256(secret2, salt, "chat v1", 32, good)
    println tls.HkdfSha256Raw(secret1, salt, encoding.Base64Encode("chat v1"), 32, good) == key

    nonce := tls.GcmNonce(0)
    sealed := tls.AesGcmSeal(key, nonce, "hello, this message is encrypted", good)
    println good
    println tls.AesGcmOpen(key, nonce, sealed, good), good
    _ := tls.AesGcmOpen(key, tls.GcmNonce(1), sealed, good)
    println good
    binary := tls.AesGcmSealBytes(key, nonce, encoding.Base64Encode("abc"), good)
    println try encoding.Base64Decode(tls.AesGcmOpenBytes(key, nonce, binary, good))

    digest := encoding.Base64Encode("0123456789abcdef0123456789abcdef")
    sig := tls.P256Sign(priv1, digest, good)
    println good, tls.P256Verify(point1, digest, sig), tls.P256Verify(point2, digest, sig)

    b := tls.HashDigest(false, "abc")
    println tls.BufLen(b), tls.HexEncodeBuf(b)
    mut hex := tls.HexDecodeBuf("cafe")
    tls.BufAppendStr(hex, "!")
    println tls.BufLen(hex), tls.HexEncodeBuf(hex)
    mut zeros := tls.NewZeroBuf(4)
    println tls.HexEncodeBuf(zeros)
    mut empty := tls.NewBuf(64)
    println tls.BufLen(empty)
    tls.WipeBuf(hex)
    tls.FreeBuf(hex)
    tls.FreeBuf(zeros)
    tls.FreeBuf(empty)
end
Output
true true
true true
true
true true
true
true
hello, this message is encrypted true
false
abc
true true false
32 ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
3 cafe21
00000000
0

EcdhP256Shared

#
func EcdhP256Shared(priv_b64: str, peer_spki_b64: str, ok &: bool): str

The shared secret from your own private key and the public key of the other side.

The example for this item is shown with the ones above: tls-Crypto.salam

HkdfSha256

#
func HkdfSha256(ikm_b64: str, salt_b64: str, info: str, out_len: int, ok &: bool): str

Derives a key of any length from a secret with a salt and an info string; give every use its own info string.

The example for this item is shown with the ones above: tls-Crypto.salam

AesGcmSeal

#
func AesGcmSeal(key_b64: str, nonce_b64: str, plaintext: str, ok &: bool): str

Encrypts and seals the text with AES-GCM; the output is base64. Never use one nonce twice with the same key.

The example for this item is shown with the ones above: tls-Crypto.salam

AesGcmOpen

#
func AesGcmOpen(key_b64: str, nonce_b64: str, sealed_b64: str, ok &: bool): str

Opens sealed text; when it was tampered with, or the key or nonce is wrong, ok becomes false.

The example for this item is shown with the ones above: tls-Crypto.salam

GcmNonce

#
func GcmNonce(counter: i64): str

A 12 byte nonce from a counter; raise the counter by one for every message.

The example for this item is shown with the ones above: tls-Crypto.salam

RandomSalt

#
func RandomSalt(n: int): str

n random bytes as base64.

The example for this item is shown with the ones above: tls-Crypto.salam

EcdhP256PublicPoint

#
func EcdhP256PublicPoint(priv_b64: str): str

The raw public point of a private key, 65 bytes as base64.

The example for this item is shown with the ones above: tls-Crypto.salam

EcdhP256SharedPoint

#
func EcdhP256SharedPoint(priv_b64: str, peer_point_b64: str, ok &: bool): str

The shared secret from the raw public point of the other side.

The example for this item is shown with the ones above: tls-Crypto.salam

HkdfSha256Raw

#
func HkdfSha256Raw(ikm_b64: str, salt_b64: str, info_b64: str, out_len: int, ok &: bool): str

The same, with the info string as base64.

The example for this item is shown with the ones above: tls-Crypto.salam

AesGcmSealBytes

#
func AesGcmSealBytes(key_b64: str, nonce_b64: str, plaintext_b64: str, ok &: bool): str

Like seal, with base64 input for binary data.

The example for this item is shown with the ones above: tls-Crypto.salam

AesGcmOpenBytes

#
func AesGcmOpenBytes(key_b64: str, nonce_b64: str, sealed_b64: str, ok &: bool): str

Like open, with base64 output.

The example for this item is shown with the ones above: tls-Crypto.salam

P256Sign

#
func P256Sign(priv_b64: str, digest_b64: str, ok &: bool): str

A deterministic ECDSA signature under RFC 6979 over a digest; 64 bytes of r and s as base64.

The example for this item is shown with the ones above: tls-Crypto.salam

P256Verify

#
func P256Verify(pub_point_b64: str, digest_b64: str, sig_b64: str): bool

Verifies the signature against a public point.

The example for this item is shown with the ones above: tls-Crypto.salam

RsaSignPkcs1Sha256

#
func RsaSignPkcs1Sha256(pem: str, digest_b64: str, ok &: bool): str

Signs a digest with an RSA key given as PEM text.

The example for this item is shown with the ones above: tls-Certs.salam

RsaKeyBits

#
func RsaKeyBits(pem: str): int

The length of the RSA key in bits.

The example for this item is shown with the ones above: tls-Certs.salam

RsaEncryptOaepSha1

#
func RsaEncryptOaepSha1(pem: str, plain_b64: str, ok &: bool): str

Encrypts a small piece of data with an RSA public key, given as PEM, and OAEP padding with SHA-1; input and output are base64.

tls-RsaEncryptOaepSha1.salam
import tls
import encoding
import io

func main:
    key := io.ReadFile("public.pem")
    mut ok := false
    cipher := tls.RsaEncryptOaepSha1(key, encoding.Base64Encode("hello"), ok)
    if not ok:
        println "the RSA public key could not be read"
        ret
    end
    println cipher.Len() > 0
end

LoadCertChainFile

#
func LoadCertChainFile(path: str): Roots

Reads the certificate chain from a PEM file.

The example for this item is shown with the ones above: tls-Certs.salam

FreePrivateKey

#
func FreePrivateKey(k &: PrivateKey)

Wipes the private key from memory and frees it.

The example for this item is shown with the ones above: tls-Certs.salam

ParsePrivateKeyPEM

#
func ParsePrivateKeyPEM(pem: str): PrivateKey

Reads an RSA or EC key from PEM text.

The example for this item is shown with the ones above: tls-Certs.salam

LoadPrivateKeyFile

#
func LoadPrivateKeyFile(path: str): PrivateKey

Reads the key from a PEM file.

The example for this item is shown with the ones above: tls-Certs.salam

WrapClientRaw

#
func WrapClientRaw(fd: i64, hello: void*, hlen: int, xpriv: void*, auth: void*, authlen: int, cfg: Config): Conn

Runs a TLS 1.3 client handshake on a socket with a ClientHello that you built yourself, as net.utls does. It needs the x25519 private key of the hello's key share. A non empty authentication key switches certificate checking to the REALITY rule used by net.reality. It fails on a HelloRetryRequest.

WrapClientRawPq

#
func WrapClientRawPq(fd: i64, hello: void*, hlen: int, xpriv: void*, pq_seed: void*, auth: void*, authlen: int, cfg: Config): Conn

Like WrapClientRaw, and it also takes the 64 byte ML-KEM seed behind an X25519MLKEM768 key share, so the handshake still finishes when the server picks that group.

X25519Public

#
func X25519Public(priv: void*, out: void*)

Computes the x25519 public key of a 32 byte private key.

X25519Shared

#
func X25519Shared(priv: void*, peer: void*, out: void*): bool

Computes the x25519 shared secret. False when the result is all zeros.

HkdfSha256Derive

#
func HkdfSha256Derive(ikm: void*, ikmlen: int, salt: void*, saltlen: int, info: str, out: void*, outlen: int): bool

HKDF-SHA256 extract and expand of key material with a salt and an info text.

HmacSha512Raw

#
func HmacSha512Raw(key: void*, klen: int, msg: void*, mlen: int, out: void*)

HMAC-SHA512 of a message under a key, written to a 64 byte output pointer.

WrapServerRaw

#
func WrapServerRaw(fd: i64, ch: void*, chlen: int, cert: void*, certlen: int, seed: void*): Conn

Runs the TLS 1.3 server side with a ClientHello that was already read, a DER certificate and the ed25519 seed that signs the handshake, as net.reality does.

HexEncodeBuf

#
func HexEncodeBuf(b: Buf): str

Turns a buffer into hex.

The example for this item is shown with the ones above: tls-Crypto.salam

HexDecodeBuf

#
func HexDecodeBuf(s: str): Buf

Turns hex back into a buffer.

The example for this item is shown with the ones above: tls-Crypto.salam

NewBuf

#
func NewBuf(cap: int): Buf

An empty buffer with this capacity.

The example for this item is shown with the ones above: tls-Crypto.salam

NewZeroBuf

#
func NewZeroBuf(n: int): Buf

A buffer of n zero bytes.

The example for this item is shown with the ones above: tls-Crypto.salam

FreeBuf

#
func FreeBuf(b &: Buf)

Frees the buffer.

The example for this item is shown with the ones above: tls-Crypto.salam

WipeBuf

#
func WipeBuf(b &: Buf)

Zeroes the contents of the buffer; for secrets, before freeing.

The example for this item is shown with the ones above: tls-Crypto.salam

BufLen

#
func BufLen(b: Buf): int

The length of the buffer.

The example for this item is shown with the ones above: tls-Crypto.salam

BufAppendStr

#
func BufAppendStr(b &: Buf, s: str)

Adds a string to the buffer.

The example for this item is shown with the ones above: tls-Crypto.salam

LoadRoots

#
func LoadRoots(ca_file: str): Roots

Reads the root certificates from a PEM file.

The example for this item is shown with the ones above: tls-Certs.salam

RootCount

#
func RootCount(r: Roots): int

The number of certificates.

The example for this item is shown with the ones above: tls-Certs.salam

FreeRoots

#
func FreeRoots(r &: Roots)

Frees the certificates.

The example for this item is shown with the ones above: tls-Certs.salam

VerifyError

#
func VerifyError(code: int): str

The explanation of a certificate verification error code.

The example for this item is shown with the ones above: tls-Certs.salam

VerifyCert

#
func VerifyCert(der: Buf, roots: Roots, host: str): int

Verifies a DER certificate against the roots and the hostname; zero means valid.

The example for this item is shown with the ones above: tls-Certs.salam

CertIsValid

#
func CertIsValid(der: Buf): bool

The DER certificate parses correctly.

The example for this item is shown with the ones above: tls-Certs.salam

CertSubjectCN

#
func CertSubjectCN(der: Buf): str

The common name (CN) of the certificate.

The example for this item is shown with the ones above: tls-Certs.salam

HashDigest

#
func HashDigest(sha384: bool, msg: str): Buf

The SHA-256 digest, or SHA-384 when the first parameter is true, into a buffer.

The example for this item is shown with the ones above: tls-Crypto.salam

SignRSAPKCS1

#
func SignRSAPKCS1(k: PrivateKey, sha384: bool, digest: Buf, sigout &: Buf): bool

An RSA signature with PKCS#1 v1.5.

The example for this item is shown with the ones above: tls-Certs.salam

SignRSAPSS

#
func SignRSAPSS(k: PrivateKey, sha384: bool, digest: Buf, sigout &: Buf): bool

An RSA-PSS signature.

The example for this item is shown with the ones above: tls-Certs.salam

SignECDSA

#
func SignECDSA(k: PrivateKey, digest: Buf, rout: Buf, sout: Buf): bool

An ECDSA signature with r and s apart.

The example for this item is shown with the ones above: tls-Certs.salam

ECDSADerEncode

#
func ECDSADerEncode(rbytes: Buf, sbytes: Buf, width: int): Buf

Turns r and s into the DER signature format.

The example for this item is shown with the ones above: tls-Certs.salam

VerifyRSAPSSWithKey

#
func VerifyRSAPSSWithKey(k: PrivateKey, sha384: bool, digest: Buf, sig: Buf): bool

Verifies an RSA-PSS signature against a key.

The example for this item is shown with the ones above: tls-Certs.salam

VerifyECDSADERWithKey

#
func VerifyECDSADERWithKey(k: PrivateKey, digest: Buf, dersig: Buf): bool

Verifies an ECDSA signature in DER format.

The example for this item is shown with the ones above: tls-Certs.salam

AesGcmSealRaw

#
func AesGcmSealRaw(key: void*, keylen: int, nonce: void*, aad: void*, aadlen: int, pt: void*, n: int, out: void*): bool

One shot AES-GCM on memory: key of 16 or 32 bytes, 12 byte nonce. Writes n encrypted bytes and the 16 byte tag to out. Returns false for a bad key length.

The example for this item is shown with the ones above: tls-Aead.salam

AesGcmOpenRaw

#
func AesGcmOpenRaw(key: void*, keylen: int, nonce: void*, aad: void*, aadlen: int, sealed: void*, sealed_len: int, out: void*): bool

The reverse of AesGcmSealRaw: sealed_len counts the tag too. Returns false for a bad key length, data that is too short or data that was changed.

The example for this item is shown with the ones above: tls-Aead.salam

ChaCha20Poly1305SealRaw

#
func ChaCha20Poly1305SealRaw(key: void*, nonce: void*, aad: void*, aadlen: int, pt: void*, n: int, out: void*): bool

One shot ChaCha20-Poly1305 on memory: key of 32 bytes, 12 byte nonce. Writes n encrypted bytes and the 16 byte tag to out.

The example for this item is shown with the ones above: tls-Aead.salam

ChaCha20Poly1305OpenRaw

#
func ChaCha20Poly1305OpenRaw(key: void*, nonce: void*, aad: void*, aadlen: int, sealed: void*, sealed_len: int, out: void*): bool

The reverse of ChaCha20Poly1305SealRaw: sealed_len counts the tag too. Returns false when the data is too short or was changed.

The example for this item is shown with the ones above: tls-Aead.salam

SelfTest

#
func SelfTest(): int

Runs the internal tests of the package and reports them; returns the number of failures.

The example for this item is shown with the ones above: tls-Certs.salam

AeadKeyLen

#
func AeadKeyLen(kind: int): int

The key length in bytes of a cipher number: 16 for AES-128-GCM and 32 for the others.

The example for this item is shown with the ones above: tls-Aead.salam

AeadNew

#
func AeadNew(kind: int, key: void*): void*

Makes a cipher context from a cipher number and a key of AeadKeyLen bytes, preparing the AES key schedule once so that many records can be sealed quickly. AES ciphers use the processor's AES instructions when cpu says they are there, and the choice is made here, at this call. Returns null for an unknown cipher number. Release it with AeadFree.

The example for this item is shown with the ones above: tls-Aead.salam

AeadFree

#
func AeadFree(ctx: void*)

Wipes the key and frees a context made by AeadNew; null is allowed.

The example for this item is shown with the ones above: tls-Aead.salam

AeadSeal

#
func AeadSeal(ctx: void*, nonce: void*, aad: void*, aadlen: int, pt: void*, n: int, out: void*)

Encrypts n bytes of pt into out and writes the 16 byte tag right after them, so out needs n plus AEAD_TAG_LEN bytes. The nonce is 12 bytes and the extra authenticated data may be null with length 0. Never use one nonce twice under one key.

The example for this item is shown with the ones above: tls-Aead.salam

AeadOpen

#
func AeadOpen(ctx: void*, nonce: void*, aad: void*, aadlen: int, ct: void*, n: int, out: void*): bool

Checks the tag that follows the n bytes of ct and decrypts them into out. Returns false when anything was changed, and then out must not be used.

The example for this item is shown with the ones above: tls-Aead.salam

Ed25519PublicKey

#
func Ed25519PublicKey(seed: void*, out: void*)

Computes the 32 byte ed25519 public key (RFC 8032) of a 32 byte seed into the output pointer.

Ed25519Sign

#
func Ed25519Sign(seed: void*, msg: void*, n: int, out: void*)

Signs a message with an ed25519 seed and writes the 64 byte signature. The code is checked against the RFC 8032 vectors and is not constant time.

Ed25519Verify

#
func Ed25519Verify(pubk: void*, msg: void*, n: int, sig: void*): bool

Checks a 64 byte ed25519 signature against a public key and a message. Rejects a non canonical S value.

Mlkem768PublicKey

#
func Mlkem768PublicKey(seed: void*, ek_out: void*)

Derives the 1184 byte ML-KEM-768 encapsulation key from a 64 byte seed (the d and z of FIPS 203).

Mlkem768Encapsulate

#
func Mlkem768Encapsulate(ek: void*, m: void*, ct_out: void*, ss_out: void*): bool

Encapsulates to an ML-KEM-768 key with a 32 byte message and writes the 1088 byte ciphertext and the 32 byte shared key. False when the key is malformed. Pass random bytes as the message for real use.

Mlkem768Decapsulate

#
func Mlkem768Decapsulate(seed: void*, ct: void*, ss_out: void*)

Decapsulates a 1088 byte ciphertext with the key derived from a 64 byte seed and writes the 32 byte shared key. A damaged ciphertext gives the implicit rejection key that FIPS 203 asks for.