openssl clib Security / Cryptography

Full TLS/SSL library for PascalAI. TLS client/server, X.509 certificates, EVP crypto, RSA/EC/Ed25519 keys, HMAC, PBKDF2, HKDF, and a CSPRNG — all through a single uses openssl;.

ppm install openssl

Overview

openssl wraps libssl — the most widely deployed TLS/SSL library in the world. It provides a full-stack implementation of TLS 1.2 and TLS 1.3, X.509 certificate management, and a comprehensive cryptography toolkit built on the EVP unified API.

The library handles every layer: TLS handshakes and session resumption, certificate chain verification, AEAD symmetric encryption, digital signatures, key derivation, and a hardware-backed CSPRNG. One package covers everything from a simple HTTPS connection to a full mutual-TLS service mesh.

CLib package

Requires libssl-dev. Ubuntu/Debian: sudo apt install libssl-dev

Key Capabilities

AreaWhat you get
TLS/SSLClient and server, TLS 1.0–1.3, SNI, mutual auth, session resumption
X.509Load/save/verify certificates, create self-signed certs, inspect SAN/issuer/fingerprint
EVPUnified crypto API covering all algorithms below through a single consistent interface
Symmetric ciphersAES-128/256-GCM (AEAD), AES-128/256-CBC, ChaCha20-Poly1305
AsymmetricRSA (2048/3072/4096), ECDSA (P-256/P-384/P-521), Ed25519, DH/ECDH key exchange
Hash / DigestSHA-1, SHA-256, SHA-384, SHA-512, MD5, BLAKE2b; file hashing
MACHMAC (any digest), CMAC, GMAC
KDFPBKDF2, HKDF (RFC 5869), scrypt, Argon2 via EVP
PRNGCSPRNG seeded from OS entropy + RDRAND hardware instruction

vs Other Libraries

LibraryBest forCompared to openssl
libsodiumOpinionated, hard-to-misuse modern cryptoSimpler API with safe defaults; openssl exposes the full spec and more algorithms
mbedTLSEmbedded / IoT devicesSmaller footprint; openssl is more featureful and has a wider ecosystem
GnuTLSLGPL-licensed projectsSimilar scope; openssl has broader language bindings and deployment base

Quick Start

TLS client connection

uses openssl;

SSLInit();  { call once at startup }

var ctx := NewClientCtx(smTLS);
UseSystemCA(ctx);          { trust OS certificate store }
SetVerify(ctx, True);      { enforce peer verification }

{ open a TCP socket to port 443 first, then wrap it }
var fd  := TCPConnect('api.example.com', 443);
var ssl := NewSSL(ctx, fd);
Connect(ssl, 'api.example.com');  { TLS handshake + SNI }

Write(ssl, 'GET / HTTP/1.1' + #13#10 + 'Host: api.example.com' + #13#10#13#10);
var resp := Read(ssl, 4096);
WriteLn(resp);

Shutdown(ssl);
FreeSSL(ssl);
FreeCtx(ctx);

SHA-256 hash

uses openssl;

SSLInit();

{ convenience shortcut }
var hex := SHA256('Hello, world!');
WriteLn(hex);

{ generic API — any digest algorithm }
var raw := Hash(daSHA512, 'Hello, world!');
WriteLn(HashHex(daBLAKE2b, 'Hello, world!'));

{ hash a file on disk }
var fileDigest := HashFile(daSHA256, '/etc/os-release');
WriteLn('File SHA-256: ' + fileDigest);

AES-256-GCM encrypt / decrypt

uses openssl;

SSLInit();

var key := RandomBytes(32);   { 256-bit key }
var iv  := GenIV(caAES256GCM);  { 12-byte nonce }
var aad := 'request-id:abc123'; { additional authenticated data }

var plain  := 'secret payload';
var cipher := Encrypt(caAES256GCM, key, iv, plain, aad);
WriteLn('Ciphertext len: ' + IntToStr(Length(cipher)));

var plain2 := Decrypt(caAES256GCM, key, iv, cipher, aad);
WriteLn(plain2);  { 'secret payload' }

RSA key generation + sign / verify

uses openssl;

SSLInit();

{ generate a 2048-bit RSA key pair }
var key := GenRSAKey(2048);

{ export to PEM (private key) }
var privPEM := SaveKeyPEM(key, True);
var pubPEM  := SaveKeyPEM(key, False);
WriteLn(pubPEM);

{ sign a message with the private key }
var msg := 'important document';
var sig := Sign(key, daSHA256, msg);

{ verify using the same key (public part) }
var ok := Verify(key, daSHA256, msg, sig);
WriteLn('Valid: ' + BoolToStr(ok));

FreeKey(key);

Types

TypeDescription
TSSLCtxSSL context handle — holds certificates, keys, cipher settings, and verification options. Created once; reused for many connections.
TSSLSSL connection handle wrapping a TCP file descriptor. One per active TLS session.
TX509X.509 certificate object. Load from PEM, inspect fields, verify against a store.
TX509StoreCertificate store / trust anchors. Used to verify certificate chains.
TEVP_KeyAsymmetric key (RSA, EC, Ed25519, etc.). Holds both public and private components until exported.
TBIOOpenSSL I/O abstraction over memory buffers, files, or sockets.
TSSLMethodEnum: smTLS (auto-negotiate best), smTLS12 (force TLS 1.2+), smTLS13 (TLS 1.3 only).
TX509InfoRecord with certificate metadata: Subject, Issuer, SerialNumber, NotBefore/After (Unix timestamps), Fingerprint (SHA-256 hex), IsCA, DNSNames, IPAddresses.
TDigestAlgoEnum: daSHA1, daSHA256, daSHA384, daSHA512, daMD5, daBLAKE2b.
TCipherAlgoEnum: caAES128GCM, caAES256GCM, caAES128CBC, caAES256CBC, caChaCha20Poly.

SSL Context API

A context (TSSLCtx) carries all configuration for a set of connections — certificates, CA trust, cipher list, and verification mode. Create one context per role (client or server) and reuse it.

FunctionDescription
SSLInit()Initialize OpenSSL global state. Call exactly once before any other function.
NewClientCtx(Method)Create a client SSL context with the given TSSLMethod
NewServerCtx(Method)Create a server SSL context
LoadCertKey(Ctx, CertPEM, KeyPEM)Load certificate and private key from PEM file paths
LoadCA(Ctx, CAPemPath)Load CA certificate(s) for peer verification from a PEM file
UseSystemCA(Ctx)Trust the OS certificate store (e.g. /etc/ssl/certs)
SetVerify(Ctx, Verify)Enable or disable peer certificate verification
SetCiphers(Ctx, Ciphers)Restrict allowed cipher suites using an OpenSSL cipher string
FreeCtx(Ctx)Release the context and all associated memory

SSL Connection API

A connection (TSSL) wraps an already-connected TCP file descriptor. Open the TCP socket yourself (e.g. via the curl or socket APIs), then hand the file descriptor to NewSSL.

FunctionDescription
NewSSL(Ctx, FD)Wrap a TCP file descriptor with the given context. Returns an SSL handle.
Connect(S, Hostname)Perform the client-side TLS handshake. Hostname is used for SNI and certificate CN/SAN verification.
Accept(S)Perform the server-side TLS handshake
Write(S, Data)Send encrypted data. Returns number of bytes written.
Read(S, MaxBytes)Receive decrypted data up to MaxBytes. Returns the received string.
Shutdown(S)Send a TLS close_notify alert for a graceful shutdown
FreeSSL(S)Release the SSL connection handle
GetPeerCert(S)Return the peer's TX509 certificate after a successful handshake

Hash / Digest API

All hash functions return raw bytes by default. Append Hex for a lowercase hex string. Use HashFile to hash large files without reading them into memory.

FunctionDescription
Hash(Algo, Data)Compute a digest of Data. Returns raw bytes.
HashHex(Algo, Data)Compute a digest and return as a lowercase hex string
SHA256(Data)Convenience: SHA-256 hex digest
SHA512(Data)Convenience: SHA-512 hex digest
HashFile(Algo, Path)Hash a file at Path and return hex digest. Streams the file; safe for large files.

HMAC API

HMAC provides message authentication — it proves both data integrity and that the sender holds the secret key. Use daSHA256 or daSHA512 for new designs.

FunctionDescription
HMAC(Algo, Key, Data)Compute HMAC. Returns raw bytes.
HMACHex(Algo, Key, Data)Compute HMAC and return as hex string
uses openssl;

SSLInit();
var mac := HMACHex(daSHA256, 'secret-key', 'message body');
WriteLn('HMAC-SHA256: ' + mac);

Symmetric Encryption API

AES-GCM and ChaCha20-Poly1305 are AEAD ciphers — they encrypt and authenticate simultaneously. The AAD parameter adds additional authenticated data (e.g. headers) that is verified but not encrypted. The GCM authentication tag is appended to the ciphertext returned by Encrypt and must be passed back to Decrypt.

FunctionDescription
Encrypt(Algo, Key, IV, PlainText, AAD)Encrypt PlainText. Returns ciphertext with authentication tag appended. AAD may be empty for non-AEAD modes.
Decrypt(Algo, Key, IV, CipherText, AAD)Decrypt and verify. Raises an exception if the tag is invalid. Returns plaintext.
GenIV(Algo)Generate a random IV of the correct size for the given cipher (12 bytes for GCM, 16 for CBC)
Tip — never reuse IV+Key pairs

Call GenIV for every message. Reusing an IV with the same key in GCM mode completely breaks confidentiality and authentication.

Asymmetric Keys API

Generate, load, save, sign, verify, and perform RSA encryption/decryption. For new designs prefer Ed25519 (fastest, smallest signatures) or ECDSA P-256 (wide interoperability).

FunctionDescription
GenRSAKey(Bits)Generate an RSA key pair. Bits: 2048, 3072, or 4096.
GenECKey(Curve)Generate an EC key pair. Curve: 'P-256', 'P-384', or 'P-521'.
GenEd25519Key()Generate an Ed25519 key pair (fast, modern, 64-byte signatures)
LoadKeyPEM(PEM)Parse a PEM string (private or public) into a TEVP_Key
SaveKeyPEM(Key, IncludePrivate)Export key to PEM. Pass False to export public key only.
FreeKey(Key)Securely release the key and zero its memory
Sign(Key, Algo, Data)Sign Data with the private key using Algo as digest. Returns DER-encoded signature.
Verify(Key, Algo, Data, Sig)Verify a DER signature against the public key. Returns Boolean.
RSAEncrypt(Key, Data)RSA-OAEP encrypt with public key (for small payloads; use AES for bulk data)
RSADecrypt(Key, Data)RSA-OAEP decrypt with private key

X.509 Certificates API

Load, inspect, create, and verify X.509 certificates. Use GetPeerCert on an established TLS connection to inspect the remote certificate at runtime.

FunctionDescription
LoadCertPEM(PEM)Parse a PEM certificate string into a TX509 handle
LoadCertFile(Path)Load a certificate from a PEM file on disk
GetCertInfo(Cert)Return a TX509Info record with all certificate fields
FreeCert(Cert)Release the certificate handle
CreateSelfSigned(Key, CN, O, C, Days)Create a self-signed certificate. CN=common name, O=organization, C=country code, Days=validity period.
SaveCertPEM(Cert)Export certificate to PEM string
VerifyCert(Cert, Store)Verify a certificate chain against a TX509Store. Returns Boolean.
uses openssl;

SSLInit();

{ create a self-signed TLS certificate }
var key  := GenECKey('P-256');
var cert := CreateSelfSigned(key, 'localhost', 'Acme Inc', 'US', 365);

var info := GetCertInfo(cert);
WriteLn('Subject:     ' + info.Subject);
WriteLn('Fingerprint: ' + info.Fingerprint);
WriteLn('Is CA:       ' + BoolToStr(info.IsCA));

WriteLn(SaveCertPEM(cert));
FreeCert(cert);
FreeKey(key);

KDF API

Key derivation functions turn low-entropy secrets (passwords) or high-entropy input keying material into fixed-length keys suitable for symmetric encryption.

FunctionDescription
PBKDF2(Algo, Password, Salt, Iterations, KeyLen)Password-based KDF. Use ≥100 000 iterations and a random 16-byte salt. Returns KeyLen bytes.
HKDF(Algo, IKM, Salt, Info, KeyLen)HMAC-based Extract-and-Expand (RFC 5869). Suitable for deriving multiple keys from a shared secret.
uses openssl;

SSLInit();

{ derive an AES-256 key from a password }
var salt := RandomBytes(16);
var key  := PBKDF2(daSHA256, 'my passphrase', salt, 100000, 32);

{ expand a shared secret into two subkeys via HKDF }
var encKey := HKDF(daSHA256, sharedSecret, salt, 'encryption', 32);
var macKey := HKDF(daSHA256, sharedSecret, salt, 'authentication', 32);

Random API

The CSPRNG is automatically seeded from OS entropy (/dev/urandom) and RDRAND on x86. Always use these functions instead of Random() for any security-sensitive purpose.

FunctionDescription
RandomBytes(N)Generate N cryptographically secure random bytes. Returns as a string (binary).
RandomHex(N)Generate N random bytes and return as a lowercase hex string (length 2N)

Info

FunctionDescription
OpenSSLVersion()Return the linked OpenSSL library version string, e.g. 'OpenSSL 3.2.1 30 Jan 2024'

Package Info

Version1.0.0
Typeclib
C Librarylibssl-dev
Authorgustavo

System Requirements

libssl-dev

Ubuntu/Debian:
sudo apt install libssl-dev

TDigestAlgo

daSHA1 — SHA-1 (legacy)
daSHA256 — SHA-256 (recommended)
daSHA384 — SHA-384
daSHA512 — SHA-512
daMD5 — MD5 (legacy)
daBLAKE2b — BLAKE2b (fast)

TCipherAlgo

caAES128GCM — AES-128-GCM
caAES256GCM — AES-256-GCM ★
caAES128CBC — AES-128-CBC
caAES256CBC — AES-256-CBC
caChaCha20Poly — ChaCha20-Poly1305

Functions

  • SSLInit
  • NewClientCtx / NewServerCtx
  • LoadCertKey / LoadCA
  • UseSystemCA / SetVerify
  • SetCiphers / FreeCtx
  • NewSSL / Connect / Accept
  • Write / Read
  • Shutdown / FreeSSL
  • GetPeerCert
  • Hash / HashHex
  • SHA256 / SHA512
  • HashFile
  • HMAC / HMACHex
  • Encrypt / Decrypt / GenIV
  • GenRSAKey / GenECKey
  • GenEd25519Key
  • LoadKeyPEM / SaveKeyPEM
  • FreeKey
  • Sign / Verify
  • RSAEncrypt / RSADecrypt
  • LoadCertPEM / LoadCertFile
  • GetCertInfo / FreeCert
  • CreateSelfSigned
  • SaveCertPEM / VerifyCert
  • PBKDF2 / HKDF
  • RandomBytes / RandomHex
  • OpenSSLVersion

See Also