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
ConnOkafterDial. A failed handshake or a bad certificate gives a closed connection, andConnErrorsays why. Readreturns astr, which stops at a zero byte. For binary data useReadBytesandWriteByteswith your own buffer.- Clients cannot present a certificate (no mutual TLS), and a
Connis 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 shotAesGcmSealRawandAesGcmOpenRawand 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.
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")
endIt 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.
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
endWith 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.
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
endECDH 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.
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
endThe 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
| Job | Use |
|---|---|
| An HTTPS or other TLS client | NewConfig, Dial, Write, Read, Close; for plain web requests, net.http does this for you |
| A TLS server | NewServerConfig, then WrapServer on each accepted socket |
| Upgrade a socket that is already open (STARTTLS) | WrapClient |
| Encrypt data at rest | AesGcmSeal, AesGcmOpen, GcmNonce |
| Agree on a key | EcdhP256Generate, EcdhP256Shared, HkdfSha256 |
| Sign and verify | P256Sign, P256Verify |
| Check a certificate yourself | LoadRoots, VerifyCert, VerifyError |
Types
ServerConfig
struct ServerConfig| Name | Type | Description |
|---|---|---|
chain | Roots | The certificate chain. |
key | PrivateKey | The private key. |
ok | bool = false | Both were read. |
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
endConfig
struct Config| Name | Type | Description |
|---|---|---|
server_name | str = "" | The hostname for SNI and for certificate verification. |
ca_file | str = "" | The file of root certificates; empty means the system roots. |
insecure_skip_verify | bool = false | Do not verify the certificate; for testing only, since it leaves the connection open to eavesdropping. |
alpn | str = "" | The protocol for ALPN, such as h2. |
aes_only | bool = false | Offer AES ciphers only. |
frag_tls | bool = false | Split 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_tcp | bool = false | Send 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_sni | bool = false | Make 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_min | int = 5 | The smallest piece in bytes when the hello is cut up. The default is 5. |
frag_max | int = 20 | The 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_ms | int = 0 | The pause in milliseconds between TCP pieces. The default is 0. |
frag_writes | int = 1 | How many of the first handshake writes are cut up. The default is 1, which is the ClientHello. |
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)
endConn
struct Conn| Name | Type | Description |
|---|---|---|
h | Handshake | The handshake state. |
host | str = "" | The host. |
open | bool = false | The connection is open. |
insecure | bool = false | Without certificate verification. |
pending | Buf | Data that has been read but not taken yet. |
err | str = "" | The error message. |
rdone | bool = false | True once the other side sent its close alert, so no more data will arrive. |
wdone | bool = false | True once CloseWrite has sent our close alert, so nothing more may be written. |
direct | bool = false | True after SwitchDirect: reads skip the record layer. |
The example for this item is shown with the ones above: tls-Client.salam
Constants and variables
AEAD_AES_128_GCM
const AEAD_AES_128_GCM: i32 = 0AeadNew; its key is 16 bytes.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)
endAEAD_AES_256_GCM
const AEAD_AES_256_GCM: i32 = 1AeadNew; 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 = 2AeadNew; 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 = 16The example for this item is shown with the ones above: tls-Aead.salam
AEAD_NONCE_LEN
const AEAD_NONCE_LEN: i32 = 12The example for this item is shown with the ones above: tls-Aead.salam
TLS10
const TLS10: i32 = 769import 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)
endTLS11
const TLS11: i32 = 770The example for this item is shown with the ones above: tls-Certs.salam
TLS12
const TLS12: i32 = 771The example for this item is shown with the ones above: tls-Certs.salam
TLS13
const TLS13: i32 = 772The example for this item is shown with the ones above: tls-Certs.salam
Functions
Mlkem768PublicKey
func Mlkem768PublicKey(seed: void*, ek_out: void*)Mlkem768Encapsulate
func Mlkem768Encapsulate(ek: void*, m: void*, ct_out: void*, ss_out: void*): boolMlkem768Decapsulate
func Mlkem768Decapsulate(seed: void*, ct: void*, ss_out: void*)AeadKeyLen
func AeadKeyLen(kind: int): intThe example for this item is shown with the ones above: tls-Aead.salam
AeadNew
func AeadNew(kind: int, key: void*): void*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*)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*)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*): booln 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
NewConfig
func NewConfig(server_name: str): ConfigThe example for this item is shown with the ones above: tls-Client.salam
Dial
func Dial(host: str, port: int, cfg: Config): ConnThe example for this item is shown with the ones above: tls-Client.salam
WrapClient
func WrapClient(fd: i64, cfg: Config): ConnThe example for this item is shown with the ones above: tls-Certs.salam
NewServerConfig
func NewServerConfig(cert_file: str, key_file: str): ServerConfigThe example for this item is shown with the ones above: tls-Server.salam
WrapServer
func WrapServer(fd: i64, cfg: ServerConfig): ConnThe example for this item is shown with the ones above: tls-Server.salam
ConnOk
func ConnOk(c: Conn): boolThe example for this item is shown with the ones above: tls-Client.salam
ConnError
func ConnError(c: Conn): strThe example for this item is shown with the ones above: tls-Client.salam
Write
func Write(c &: Conn, data: str): intThe example for this item is shown with the ones above: tls-Client.salam
WriteBytes
func WriteBytes(c &: Conn, ptr: void*, n: int): intThe example for this item is shown with the ones above: tls-Server.salam
Cork
func Cork(c &: Conn)The example for this item is shown with the ones above: tls-Server.salam
Flush
func Flush(c &: Conn): boolThe example for this item is shown with the ones above: tls-Server.salam
Read
func Read(c &: Conn, max: int): strReadBytes 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): intmax 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)Pending
func Pending(c: Conn): intThe example for this item is shown with the ones above: tls-Server.salam
Readable
func Readable(c: Conn): boolThe example for this item is shown with the ones above: tls-Server.salam
Fd
func Fd(c: Conn): i64The example for this item is shown with the ones above: tls-Server.salam
CloseWrite
func CloseWrite(c &: Conn)Close afterwards. It does nothing when the write side is already finished.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)
endDetach
func Detach(c &: Conn)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)
endClose
func Close(c &: Conn)The example for this item is shown with the ones above: tls-Client.salam
Version
func Version(c: Conn): strTLS1.3.The example for this item is shown with the ones above: tls-Client.salam
CipherName
func CipherName(c: Conn): strThe example for this item is shown with the ones above: tls-Client.salam
PeerCertCount
func PeerCertCount(c: Conn): intThe example for this item is shown with the ones above: tls-Client.salam
FreePrivateKey
func FreePrivateKey(k &: PrivateKey)The example for this item is shown with the ones above: tls-Certs.salam
ParsePrivateKeyPEM
func ParsePrivateKeyPEM(pem: str): PrivateKeyThe example for this item is shown with the ones above: tls-Certs.salam
LoadPrivateKeyFile
func LoadPrivateKeyFile(path: str): PrivateKeyThe example for this item is shown with the ones above: tls-Certs.salam
LoadCertChainFile
func LoadCertChainFile(path: str): RootsThe example for this item is shown with the ones above: tls-Certs.salam
Ed25519PublicKey
func Ed25519PublicKey(seed: void*, out: void*)Ed25519Sign
func Ed25519Sign(seed: void*, msg: void*, n: int, out: void*)Ed25519Verify
func Ed25519Verify(pubk: void*, msg: void*, n: int, sig: void*): boolHexEncodeBuf
func HexEncodeBuf(b: Buf): strimport tls
import encoding
func main throws:
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)
endHexDecodeBuf
func HexDecodeBuf(s: str): BufThe example for this item is shown with the ones above: tls-Crypto.salam
NewBuf
func NewBuf(cap: int): BufThe example for this item is shown with the ones above: tls-Crypto.salam
NewZeroBuf
func NewZeroBuf(n: int): BufThe example for this item is shown with the ones above: tls-Crypto.salam
FreeBuf
func FreeBuf(b &: Buf)The example for this item is shown with the ones above: tls-Crypto.salam
WipeBuf
func WipeBuf(b &: Buf)The example for this item is shown with the ones above: tls-Crypto.salam
BufLen
func BufLen(b: Buf): intThe example for this item is shown with the ones above: tls-Crypto.salam
BufAppendStr
func BufAppendStr(b &: Buf, s: str)The example for this item is shown with the ones above: tls-Crypto.salam
LoadRoots
func LoadRoots(ca_file: str): RootsThe example for this item is shown with the ones above: tls-Certs.salam
RootCount
func RootCount(r: Roots): intThe example for this item is shown with the ones above: tls-Certs.salam
FreeRoots
func FreeRoots(r &: Roots)The example for this item is shown with the ones above: tls-Certs.salam
VerifyError
func VerifyError(code: int): strThe example for this item is shown with the ones above: tls-Certs.salam
VerifyCert
func VerifyCert(der: Buf, roots: Roots, host: str): intThe example for this item is shown with the ones above: tls-Certs.salam
CertIsValid
func CertIsValid(der: Buf): boolThe example for this item is shown with the ones above: tls-Certs.salam
CertSubjectCN
func CertSubjectCN(der: Buf): strThe example for this item is shown with the ones above: tls-Certs.salam
HashDigest
func HashDigest(sha384: bool, msg: str): BufThe example for this item is shown with the ones above: tls-Crypto.salam
SignRSAPKCS1
func SignRSAPKCS1(k: PrivateKey, sha384: bool, digest: Buf, sigout &: Buf): boolThe example for this item is shown with the ones above: tls-Certs.salam
SignRSAPSS
func SignRSAPSS(k: PrivateKey, sha384: bool, digest: Buf, sigout &: Buf): boolThe example for this item is shown with the ones above: tls-Certs.salam
SignECDSA
func SignECDSA(k: PrivateKey, digest: Buf, rout: Buf, sout: Buf): boolThe example for this item is shown with the ones above: tls-Certs.salam
ECDSADerEncode
func ECDSADerEncode(rbytes: Buf, sbytes: Buf, width: int): BufThe example for this item is shown with the ones above: tls-Certs.salam
VerifyRSAPSSWithKey
func VerifyRSAPSSWithKey(k: PrivateKey, sha384: bool, digest: Buf, sig: Buf): boolThe example for this item is shown with the ones above: tls-Certs.salam
VerifyECDSADERWithKey
func VerifyECDSADERWithKey(k: PrivateKey, digest: Buf, dersig: Buf): boolThe 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*): booln 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*): boolAesGcmSealRaw: 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*): booln 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*): boolChaCha20Poly1305SealRaw: 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
EcdhP256Generate
func EcdhP256Generate(priv &: str, pub_spki &: str): boolThe example for this item is shown with the ones above: tls-Crypto.salam
EcdhP256Shared
func EcdhP256Shared(priv_b64: str, peer_spki_b64: str, ok &: bool): strThe 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): strThe 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): strThe 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): strThe example for this item is shown with the ones above: tls-Crypto.salam
GcmNonce
func GcmNonce(counter: i64): strThe example for this item is shown with the ones above: tls-Crypto.salam
RandomSalt
func RandomSalt(n: int): strThe example for this item is shown with the ones above: tls-Crypto.salam
EcdhP256PublicPoint
func EcdhP256PublicPoint(priv_b64: str): strThe 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): strThe 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): strThe 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): strThe 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): strThe example for this item is shown with the ones above: tls-Crypto.salam
P256Sign
func P256Sign(priv_b64: str, digest_b64: str, ok &: bool): strThe 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): boolThe example for this item is shown with the ones above: tls-Crypto.salam
RsaSignPkcs1Sha256
func RsaSignPkcs1Sha256(pem: str, digest_b64: str, ok &: bool): strThe example for this item is shown with the ones above: tls-Certs.salam
RsaKeyBits
func RsaKeyBits(pem: str): intThe example for this item is shown with the ones above: tls-Certs.salam
RsaEncryptOaepSha1
func RsaEncryptOaepSha1(pem: str, plain_b64: str, ok &: bool): strimport 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
endXChaCha20Poly1305SealRaw
func XChaCha20Poly1305SealRaw(key: void*, nonce24: void*, aad: void*, aadlen: int, pt: void*, n: int, out: void*): booln 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*): boolXChaCha20Poly1305SealRaw: 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): boolThe example for this item is shown with the ones above: tls-Aead.salam
SelfTest
func SelfTest(): intThe 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): Connnet.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): ConnWrapClientRaw, 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*)X25519Shared
func X25519Shared(priv: void*, peer: void*, out: void*): boolHkdfSha256Derive
func HkdfSha256Derive(ikm: void*, ikmlen: int, salt: void*, saltlen: int, info: str, out: void*, outlen: int): boolHmacSha512Raw
func HmacSha512Raw(key: void*, klen: int, msg: void*, mlen: int, out: void*)WrapServerRaw
func WrapServerRaw(fd: i64, ch: void*, chlen: int, cert: void*, certlen: int, seed: void*): Connnet.reality does.