feat: crypto library, Nexus HTTP server, JWT CLI, Boko web framework

- lib/crypto/: 9-module crypto library (Hash, HMAC, Base64/URL, Random, AES, RSA, ECDSA, Ed25519, JWT)
- rt/runtime.c: +346 lines OpenSSL crypto primitives (SHA-1/384/512, HMAC, Base64URL, AES-CBC/GCM, RSA, ECDSA, Ed25519)
- apps/nexus/: multi-threaded HTTP/1.1 + HTTP/2 detect + WebSocket server
- apps/jwt-pitbul/: JWT CLI tool (sign, verify, decode, keygen)
- apps/boko-framework/: FastAPI-inspired async web framework
- test_crypto/: crypto library test suite (23 tests)
This commit is contained in:
2026-06-07 22:15:00 +03:00
parent a2617e9954
commit e7e900973f
47 changed files with 3983 additions and 6 deletions
+265
View File
@@ -0,0 +1,265 @@
# Bux Crypto Library (`Std::Crypto`)
Cryptographic primitives for the Bux programming language. Backed by OpenSSL via the C runtime (`rt/runtime.c`).
## Modules
| Module | Import Path | Provides |
|--------|------------|----------|
| **Base64** | `Std::Crypto::Base64` | Base64 and Base64URL (RFC 4648 §5) encode/decode |
| **Hash** | `Std::Crypto::Hash` | SHA-1, SHA-256, SHA-384, SHA-512 (hex + raw) |
| **HMAC** | `Std::Crypto::Hmac` | HMAC-SHA256, HMAC-SHA384, HMAC-SHA512 (hex + raw + base64) |
| **Random** | `Std::Crypto::Random` | Cryptographically secure random bytes, hex, base64, uint32 |
| **AES** | `Std::Crypto::Aes` | AES-256-CBC and AES-256-GCM encrypt/decrypt |
| **RSA** | `Std::Crypto::Rsa` | RSA PKCS#1 v1.5 sign/verify (SHA-256/384/512) |
| **ECDSA** | `Std::Crypto::Ecdsa` | ECDSA P-256 and P-384 sign/verify |
| **Ed25519** | `Std::Crypto::Ed25519` | Ed25519 key generation, signing, verification |
| **JWT** | `Std::Crypto::Jwt` | JSON Web Tokens (HS256/384/512, RS256/384/512, ES256/384, EdDSA) |
The legacy `Std::Crypto` module (the old single-file API) is preserved as a backward-compatible wrapper — existing code continues to work.
## Quick Start
### Hash
```bux
import Std::Crypto::Hash::{Hash_Sha256, Hash_Sha384, Hash_Sha512};
let hex: String = Hash_Sha256("hello");
// → "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
let size: int = Hash_Sha256Size(); // → 32 (bytes)
```
### HMAC
```bux
import Std::Crypto::Hmac::{Hmac_Sha256, Hmac_Sha256Raw, Hmac_Sha256Base64};
let hex: String = Hmac_Sha256("secret-key", "message");
// → hex string
// Raw binary output (caller allocates 32-byte buffer)
let buf: *void = Alloc(32);
Hmac_Sha256Raw("secret-key", "message", buf);
// buf now contains 32 bytes of raw HMAC
let b64: String = Hmac_Sha256Base64("secret-key", "message");
// → base64-encoded HMAC
```
### Base64 & Base64URL
```bux
import Std::Crypto::Base64::{Base64_Encode, Base64_Decode,
Base64URL_Encode, Base64URL_Decode};
let std: String = Base64_Encode("hello"); // → "aGVsbG8="
let orig: String = Base64_Decode(std); // → "hello"
let url: String = Base64URL_Encode("hello"); // → "aGVsbG8" (no padding)
let orig2: String = Base64URL_Decode(url); // → "hello"
```
### Random
```bux
import Std::Crypto::Random::{Random_Bytes, Random_Hex, Random_Base64, Random_Uint32};
let raw: String = Random_Bytes(32); // 32 random bytes (binary-safe string)
let hex: String = Random_Hex(16); // 16 random bytes as hex (32 chars)
let b64: String = Random_Base64(16); // 16 random bytes as base64
let u32: uint = Random_Uint32(); // random 32-bit unsigned integer
```
### AES-256
```bux
import Std::Crypto::Aes::{Aes_GenerateKey, Aes_GenerateIV,
Aes_CbcEncrypt, Aes_CbcDecrypt,
Aes_GcmEncrypt, Aes_GcmDecrypt};
// Generate random key and IV
let key: String = Aes_GenerateKey(); // 32 raw bytes
let iv: String = Aes_GenerateIV(); // 16 raw bytes
// CBC mode
let cipher: String = Aes_CbcEncrypt("secret message", key, iv);
let plain: String = Aes_CbcDecrypt(cipher, key, iv);
// GCM mode (authenticated encryption)
let tag: *void = Alloc(16);
let gcmCipher: String = Aes_GcmEncrypt("secret", key, iv, tag);
let gcmPlain: String = Aes_GcmDecrypt(gcmCipher, key, iv, tag as String);
```
### RSA
```bux
import Std::Crypto::Rsa::{Rsa_SignSha256, Rsa_VerifySha256,
Rsa_SignSha256Base64, Rsa_VerifySha256Base64};
// Keys are PEM-encoded strings
let pemPriv: String = ReadFile("private.pem");
let pemPub: String = ReadFile("public.pem");
// Sign — returns raw signature
let sig: String = Rsa_SignSha256(pemPriv, "data to sign");
// Or sign and get base64
let sigB64: String = Rsa_SignSha256Base64(pemPriv, "data to sign");
// Verify raw signature
let valid: bool = Rsa_VerifySha256(pemPub, "data to sign", sig);
// Verify base64 signature
let validB64: bool = Rsa_VerifySha256Base64(pemPub, "data to sign", sigB64);
```
### ECDSA
```bux
import Std::Crypto::Ecdsa::{Ecdsa_SignP256, Ecdsa_VerifyP256,
Ecdsa_SignP384, Ecdsa_VerifyP384};
// P-256 (ES256)
let sig: String = Ecdsa_SignP256(pemPriv, "data");
let ok: bool = Ecdsa_VerifyP256(pemPub, "data", sig);
// P-384 (ES384)
let sig384: String = Ecdsa_SignP384(pemPriv, "data");
let ok384: bool = Ecdsa_VerifyP384(pemPub, "data", sig384);
```
### Ed25519
```bux
import Std::Crypto::Ed25519::{Ed25519_Keypair, Ed25519_Sign, Ed25519_Verify};
// Generate keypair — keys are 32 raw bytes each
let pub: *void = Alloc(32);
let priv: *void = Alloc(32);
Ed25519_Keypair(pub, priv);
// Sign
let sig: String = Ed25519_Sign(priv as String, "message");
// sig is 64 raw bytes
// Verify
let valid: bool = Ed25519_Verify(pub as String, sig, "message");
```
### JWT
```bux
import Std::Crypto::Jwt::{JwtAlg, Jwt_MakeHeader, Jwt_Encode,
Jwt_Decode, Jwt_EncodeHS256};
// --- Symmetric (HS256) ---
let token: String = Jwt_EncodeHS256("{\"sub\":\"123\",\"role\":\"admin\"}", "my-secret");
var header: String;
var payload: String;
let alg: JwtAlg = JwtAlg { tag: JwtAlg_HS256 };
if Jwt_Decode(token, alg, "my-secret", &header, &payload) {
PrintLine(payload); // {"sub":"123","role":"admin"}
}
// --- Asymmetric (RS256) ---
let rsToken: String = Jwt_Encode(
"{\"alg\":\"RS256\",\"typ\":\"JWT\"}",
"{\"sub\":\"456\"}",
JwtAlg { tag: JwtAlg_RS256 },
pemPrivateKey
);
// --- Convenience helpers ---
Jwt_EncodeHS256(payload, secret);
Jwt_EncodeHS384(payload, secret);
Jwt_EncodeHS512(payload, secret);
Jwt_EncodeRS256(payload, pemPrivKey);
Jwt_EncodeES256(payload, pemPrivKey);
Jwt_EncodeEdDSA(payload, rawPrivKey32);
```
## Supported JWT Algorithms
| Algorithm | JWT `alg` | Key Type | Key Format |
|-----------|-----------|----------|------------|
| HS256 | `HS256` | HMAC secret | Raw string |
| HS384 | `HS384` | HMAC secret | Raw string |
| HS512 | `HS512` | HMAC secret | Raw string |
| RS256 | `RS256` | RSA private/public key | PEM string |
| RS384 | `RS384` | RSA private/public key | PEM string |
| RS512 | `RS512` | RSA private/public key | PEM string |
| ES256 | `ES256` | ECDSA P-256 key | PEM string |
| ES384 | `ES384` | ECDSA P-384 key | PEM string |
| EdDSA | `EdDSA` | Ed25519 key | 32-byte raw |
## Backend
All primitives are implemented in C using OpenSSL and linked via the Bux runtime (`rt/runtime.c`). The C functions are declared as `extern func` in each Bux module.
Requires OpenSSL 1.1.1+ (for Ed25519 support). Link with `-lssl -lcrypto`.
## File Layout
```
lib/
├── Crypto.bux # Backward-compat wrapper (old API)
└── crypto/
├── base64.bux # Base64 + Base64URL
├── hash.bux # SHA-1/256/384/512
├── hmac.bux # HMAC-SHA256/384/512
├── random.bux # Secure random
├── aes.bux # AES-256-CBC/GCM
├── rsa.bux # RSA PKCS#1 v1.5
├── ecdsa.bux # ECDSA P-256/P-384
├── ed25519.bux # Ed25519
└── jwt.bux # JSON Web Tokens
lib/crypto_test/ # Test project (exercises all modules)
test_crypto/ # Standalone test project
```
## Migration from old `Std::Crypto`
The old single-file API is still available under `Std::Crypto`:
| Old Function | New Equivalent | Module |
|-------------|----------------|--------|
| `Crypto_Sha256(s)` | `Hash_Sha256(s)` | `Std::Crypto::Hash` |
| `Crypto_HmacSha256(k, m)` | `Hmac_Sha256(k, m)` | `Std::Crypto::Hmac` |
| `Crypto_RandomBytes(n)` | `Random_Base64(n)` | `Std::Crypto::Random` |
| `Crypto_Base64Encode(s)` | `Base64_Encode(s)` | `Std::Crypto::Base64` |
| `Crypto_Base64Decode(s)` | `Base64_Decode(s)` | `Std::Crypto::Base64` |
| `Crypto_HmacSha256Raw(k, m)` | `Hmac_Sha256Base64(k, m)` | `Std::Crypto::Hmac` |
New code should prefer the submodule imports for clarity and to avoid pulling in unused declarations.
## Running Tests
```bash
cd test_crypto
../buxc build
./test_crypto
```
Expected output:
```
================================================
Bux Crypto Library — Test Suite
================================================
--- Base64 ---
PASS Base64_Encode('hello')
PASS Base64_Decode('aGVsbG8=')
...
--- Hash ---
PASS Hash_Sha256('hello')
...
================================================
Passed: 23
Failed: 0
================================================
```
+67
View File
@@ -0,0 +1,67 @@
// =============================================================================
// Std::Crypto::Aes — AES-256-CBC and AES-256-GCM encryption/decryption
// =============================================================================
module Std::Crypto::Aes {
import Std::Mem::{Alloc, Free};
import Std::String::{String_Len};
extern func bux_random_bytes(buf: *void, len: int) -> int;
extern func bux_aes_256_cbc_encrypt(plain: String, plainlen: int, key: String, iv: String, outlen: *int) -> String;
extern func bux_aes_256_cbc_decrypt(cipher: String, cipherlen: int, key: String, iv: String, outlen: *int) -> String;
extern func bux_aes_256_gcm_encrypt(plain: String, plainlen: int, key: String, iv: String, tag: *void, outlen: *int) -> String;
extern func bux_aes_256_gcm_decrypt(cipher: String, cipherlen: int, key: String, iv: String, tag: String, outlen: *int) -> String;
// --- AES-256-CBC ---
const AES_KEY_SIZE: int = 32; // 256 bits
const AES_IV_SIZE: int = 16; // 128 bits
const AES_GCM_TAG_SIZE: int = 16;
// Generate a random 256-bit AES key (returns raw 32 bytes)
func Aes_GenerateKey() -> String {
let buf: *void = Alloc(AES_KEY_SIZE as uint);
if bux_random_bytes(buf, AES_KEY_SIZE) != 1 {
Free(buf);
return "";
}
return buf as String;
}
// Generate a random 128-bit IV (returns raw 16 bytes)
func Aes_GenerateIV() -> String {
let buf: *void = Alloc(AES_IV_SIZE as uint);
if bux_random_bytes(buf, AES_IV_SIZE) != 1 {
Free(buf);
return "";
}
return buf as String;
}
// AES-256-CBC encrypt. plain and key are binary strings, iv is 16 bytes.
// Returns ciphertext (may be longer than plain due to PKCS#7 padding).
func Aes_CbcEncrypt(plain: String, key: String, iv: String) -> String {
let outlen: int = 0;
return bux_aes_256_cbc_encrypt(plain, String_Len(plain) as int, key, iv, &outlen);
}
// AES-256-CBC decrypt. Returns plaintext.
func Aes_CbcDecrypt(cipher: String, key: String, iv: String) -> String {
let outlen: int = 0;
return bux_aes_256_cbc_decrypt(cipher, String_Len(cipher) as int, key, iv, &outlen);
}
// --- AES-256-GCM (Authenticated Encryption) ---
// AES-256-GCM encrypt. Returns ciphertext. tag receives 16-byte authentication tag.
func Aes_GcmEncrypt(plain: String, key: String, iv: String, tag: *void) -> String {
let outlen: int = 0;
return bux_aes_256_gcm_encrypt(plain, String_Len(plain) as int, key, iv, tag, &outlen);
}
// AES-256-GCM decrypt. Returns plaintext. tag must be the 16-byte auth tag from encryption.
func Aes_GcmDecrypt(cipher: String, key: String, iv: String, tag: String) -> String {
let outlen: int = 0;
return bux_aes_256_gcm_decrypt(cipher, String_Len(cipher) as int, key, iv, tag, &outlen);
}
}
+34
View File
@@ -0,0 +1,34 @@
// =============================================================================
// Std::Crypto::Base64 — Base64 and Base64URL encode/decode
// =============================================================================
module Std::Crypto::Base64 {
import Std::String::{String_Len};
extern func bux_base64_encode(data: String, len: int) -> String;
extern func bux_base64_decode(data: String, len: int, outlen: *int) -> String;
extern func bux_base64url_encode(data: String, len: int) -> String;
extern func bux_base64url_decode(data: String, len: int, outlen: *int) -> String;
// --- Standard Base64 ---
func Base64_Encode(s: String) -> String {
return bux_base64_encode(s, String_Len(s) as int);
}
func Base64_Decode(s: String) -> String {
let outlen: int = 0;
return bux_base64_decode(s, String_Len(s) as int, &outlen);
}
// --- Base64URL (RFC 4648 §5, uses - and _ instead of + and /, no padding) ---
func Base64URL_Encode(s: String) -> String {
return bux_base64url_encode(s, String_Len(s) as int);
}
func Base64URL_Decode(s: String) -> String {
let outlen: int = 0;
return bux_base64url_decode(s, String_Len(s) as int, &outlen);
}
}
+67
View File
@@ -0,0 +1,67 @@
// =============================================================================
// Std::Crypto::Ecdsa — ECDSA P-256 and P-384 sign/verify
// =============================================================================
module Std::Crypto::Ecdsa {
import Std::Mem::{Alloc, Free};
import Std::String::{String_Len};
extern func bux_ecdsa_sign_p256(pemKey: String, keylen: int, data: String, datalen: int, siglen: *int) -> String;
extern func bux_ecdsa_sign_p384(pemKey: String, keylen: int, data: String, datalen: int, siglen: *int) -> String;
extern func bux_ecdsa_verify_p256(pemKey: String, keylen: int, data: String, datalen: int, sig: String, siglen: int) -> int;
extern func bux_ecdsa_verify_p384(pemKey: String, keylen: int, data: String, datalen: int, sig: String, siglen: int) -> int;
extern func bux_base64_encode(data: String, len: int) -> String;
extern func bux_base64_decode(data: String, len: int, outlen: *int) -> String;
// --- ECDSA P-256 (ES256) ---
func Ecdsa_SignP256(pemPrivateKey: String, data: String) -> String {
let siglen: int = 0;
return bux_ecdsa_sign_p256(pemPrivateKey, String_Len(pemPrivateKey) as int,
data, String_Len(data) as int, &siglen);
}
func Ecdsa_SignP256Base64(pemPrivateKey: String, data: String) -> String {
let sig: String = Ecdsa_SignP256(pemPrivateKey, data);
return bux_base64_encode(sig, String_Len(sig) as int);
}
func Ecdsa_VerifyP256(pemPublicKey: String, data: String, signature: String) -> bool {
let r: int = bux_ecdsa_verify_p256(pemPublicKey, String_Len(pemPublicKey) as int,
data, String_Len(data) as int,
signature, String_Len(signature) as int);
return r == 1;
}
func Ecdsa_VerifyP256Base64(pemPublicKey: String, data: String, signatureB64: String) -> bool {
let outlen: int = 0;
let sig: String = bux_base64_decode(signatureB64, String_Len(signatureB64) as int, &outlen);
return Ecdsa_VerifyP256(pemPublicKey, data, sig);
}
// --- ECDSA P-384 (ES384) ---
func Ecdsa_SignP384(pemPrivateKey: String, data: String) -> String {
let siglen: int = 0;
return bux_ecdsa_sign_p384(pemPrivateKey, String_Len(pemPrivateKey) as int,
data, String_Len(data) as int, &siglen);
}
func Ecdsa_SignP384Base64(pemPrivateKey: String, data: String) -> String {
let sig: String = Ecdsa_SignP384(pemPrivateKey, data);
return bux_base64_encode(sig, String_Len(sig) as int);
}
func Ecdsa_VerifyP384(pemPublicKey: String, data: String, signature: String) -> bool {
let r: int = bux_ecdsa_verify_p384(pemPublicKey, String_Len(pemPublicKey) as int,
data, String_Len(data) as int,
signature, String_Len(signature) as int);
return r == 1;
}
func Ecdsa_VerifyP384Base64(pemPublicKey: String, data: String, signatureB64: String) -> bool {
let outlen: int = 0;
let sig: String = bux_base64_decode(signatureB64, String_Len(signatureB64) as int, &outlen);
return Ecdsa_VerifyP384(pemPublicKey, data, sig);
}
}
+80
View File
@@ -0,0 +1,80 @@
// =============================================================================
// Std::Crypto::Ed25519 — Ed25519 key generation, signing, and verification
// =============================================================================
module Std::Crypto::Ed25519 {
import Std::Mem::{Alloc, Free};
import Std::String::{String_Len, String_Concat};
extern func bux_ed25519_keypair(pubKey: *void, privKey: *void) -> int;
extern func bux_ed25519_sign(privKey: String, data: String, datalen: int, sig: *void) -> int;
extern func bux_ed25519_verify(pubKey: String, sig: String, data: String, datalen: int) -> int;
extern func bux_base64_encode(data: String, len: int) -> String;
extern func bux_base64_decode(data: String, len: int, outlen: *int) -> String;
const ED25519_PUBKEY_SIZE: int = 32;
const ED25519_PRIVKEY_SIZE: int = 32;
const ED25519_SIG_SIZE: int = 64;
// --- Key Generation ---
// Ed25519_Keypair: generates a new keypair.
// Returns true on success. pubKey and privKey receive 32-byte raw keys.
func Ed25519_Keypair(pubKey: *void, privKey: *void) -> bool {
let r: int = bux_ed25519_keypair(pubKey, privKey);
return r == 1;
}
// Convenience: generate and return base64-encoded keypair
func Ed25519_KeypairBase64() -> String {
let pub: *void = Alloc(ED25519_PUBKEY_SIZE as uint);
let priv: *void = Alloc(ED25519_PRIVKEY_SIZE as uint);
if bux_ed25519_keypair(pub, priv) != 1 {
Free(pub);
Free(priv);
return "";
}
// Return "pub_b64:priv_b64"
let pubB64: String = bux_base64_encode(pub as String, ED25519_PUBKEY_SIZE);
let privB64: String = bux_base64_encode(priv as String, ED25519_PRIVKEY_SIZE);
Free(pub);
Free(priv);
let pair: String = String_Concat(pubB64, ":");
return String_Concat(pair, privB64);
}
// --- Sign ---
// Ed25519_Sign: sign data with 32-byte raw private key. Returns 64-byte raw signature.
func Ed25519_Sign(privKey: String, data: String) -> String {
let sig: *void = Alloc(ED25519_SIG_SIZE as uint);
if bux_ed25519_sign(privKey, data, String_Len(data) as int, sig) != 1 {
Free(sig);
return "";
}
return sig as String;
}
// Convenience: sign and return base64-encoded signature
func Ed25519_SignBase64(privKey: String, data: String) -> String {
let sig: String = Ed25519_Sign(privKey, data);
if String_Len(sig) == 0 { return ""; }
return bux_base64_encode(sig, ED25519_SIG_SIZE);
}
// --- Verify ---
// Ed25519_Verify: verify a 64-byte raw signature against data with 32-byte public key.
func Ed25519_Verify(pubKey: String, signature: String, data: String) -> bool {
let r: int = bux_ed25519_verify(pubKey, signature, data, String_Len(data) as int);
return r == 1;
}
// Convenience: verify a base64-encoded signature
func Ed25519_VerifyBase64(pubKey: String, signatureB64: String, data: String) -> bool {
let outlen: int = 0;
let sig: String = bux_base64_decode(signatureB64, String_Len(signatureB64) as int, &outlen);
if outlen != ED25519_SIG_SIZE { return false; }
return Ed25519_Verify(pubKey, sig, data);
}
}
+73
View File
@@ -0,0 +1,73 @@
// =============================================================================
// Std::Crypto::Hash — SHA-1, SHA-256, SHA-384, SHA-512
// =============================================================================
module Std::Crypto::Hash {
import Std::Mem::{Alloc, Free};
import Std::String::{String_Len};
extern func bux_sha1(data: String, len: int, out: *void);
extern func bux_sha256(data: String, len: int, out: *void);
extern func bux_sha384(data: String, len: int, out: *void);
extern func bux_sha512(data: String, len: int, out: *void);
extern func bux_bytes_to_hex(data: *void, len: int) -> String;
// --- Convenience wrappers: hex output ---
func Hash_Sha1(data: String) -> String {
let len: int = String_Len(data) as int;
let buf: *void = Alloc(20);
bux_sha1(data, len, buf);
let result: String = bux_bytes_to_hex(buf, 20);
Free(buf);
return result;
}
func Hash_Sha256(data: String) -> String {
let len: int = String_Len(data) as int;
let buf: *void = Alloc(32);
bux_sha256(data, len, buf);
let result: String = bux_bytes_to_hex(buf, 32);
Free(buf);
return result;
}
func Hash_Sha384(data: String) -> String {
let len: int = String_Len(data) as int;
let buf: *void = Alloc(48);
bux_sha384(data, len, buf);
let result: String = bux_bytes_to_hex(buf, 48);
Free(buf);
return result;
}
func Hash_Sha512(data: String) -> String {
let len: int = String_Len(data) as int;
let buf: *void = Alloc(64);
bux_sha512(data, len, buf);
let result: String = bux_bytes_to_hex(buf, 64);
Free(buf);
return result;
}
// --- Raw binary output (caller must Alloc/Free) ---
func Hash_Sha256Raw(data: String, out: *void) {
bux_sha256(data, String_Len(data) as int, out);
}
func Hash_Sha384Raw(data: String, out: *void) {
bux_sha384(data, String_Len(data) as int, out);
}
func Hash_Sha512Raw(data: String, out: *void) {
bux_sha512(data, String_Len(data) as int, out);
}
// --- Digest sizes ---
func Hash_Sha1Size() -> int { return 20; }
func Hash_Sha256Size() -> int { return 32; }
func Hash_Sha384Size() -> int { return 48; }
func Hash_Sha512Size() -> int { return 64; }
}
+92
View File
@@ -0,0 +1,92 @@
// =============================================================================
// Std::Crypto::Hmac — HMAC-SHA256, HMAC-SHA384, HMAC-SHA512
// =============================================================================
module Std::Crypto::Hmac {
import Std::Mem::{Alloc, Free};
import Std::String::{String_Len};
extern func bux_hmac_sha256(key: String, keylen: int, msg: String, msglen: int, out: *void);
extern func bux_hmac_sha384(key: String, keylen: int, msg: String, msglen: int, out: *void);
extern func bux_hmac_sha512(key: String, keylen: int, msg: String, msglen: int, out: *void);
extern func bux_bytes_to_hex(data: *void, len: int) -> String;
extern func bux_base64_encode(data: String, len: int) -> String;
// --- HMAC-SHA256 ---
func Hmac_Sha256(key: String, message: String) -> String {
let kl: int = String_Len(key) as int;
let ml: int = String_Len(message) as int;
let buf: *void = Alloc(32);
bux_hmac_sha256(key, kl, message, ml, buf);
let result: String = bux_bytes_to_hex(buf, 32);
Free(buf);
return result;
}
func Hmac_Sha256Raw(key: String, message: String, out: *void) {
bux_hmac_sha256(key, String_Len(key) as int, message, String_Len(message) as int, out);
}
func Hmac_Sha256Base64(key: String, message: String) -> String {
let kl: int = String_Len(key) as int;
let ml: int = String_Len(message) as int;
let buf: *void = Alloc(32);
bux_hmac_sha256(key, kl, message, ml, buf);
let result: String = bux_base64_encode(buf as String, 32);
Free(buf);
return result;
}
// --- HMAC-SHA384 ---
func Hmac_Sha384(key: String, message: String) -> String {
let kl: int = String_Len(key) as int;
let ml: int = String_Len(message) as int;
let buf: *void = Alloc(48);
bux_hmac_sha384(key, kl, message, ml, buf);
let result: String = bux_bytes_to_hex(buf, 48);
Free(buf);
return result;
}
func Hmac_Sha384Raw(key: String, message: String, out: *void) {
bux_hmac_sha384(key, String_Len(key) as int, message, String_Len(message) as int, out);
}
func Hmac_Sha384Base64(key: String, message: String) -> String {
let kl: int = String_Len(key) as int;
let ml: int = String_Len(message) as int;
let buf: *void = Alloc(48);
bux_hmac_sha384(key, kl, message, ml, buf);
let result: String = bux_base64_encode(buf as String, 48);
Free(buf);
return result;
}
// --- HMAC-SHA512 ---
func Hmac_Sha512(key: String, message: String) -> String {
let kl: int = String_Len(key) as int;
let ml: int = String_Len(message) as int;
let buf: *void = Alloc(64);
bux_hmac_sha512(key, kl, message, ml, buf);
let result: String = bux_bytes_to_hex(buf, 64);
Free(buf);
return result;
}
func Hmac_Sha512Raw(key: String, message: String, out: *void) {
bux_hmac_sha512(key, String_Len(key) as int, message, String_Len(message) as int, out);
}
func Hmac_Sha512Base64(key: String, message: String) -> String {
let kl: int = String_Len(key) as int;
let ml: int = String_Len(message) as int;
let buf: *void = Alloc(64);
bux_hmac_sha512(key, kl, message, ml, buf);
let result: String = bux_base64_encode(buf as String, 64);
Free(buf);
return result;
}
}
+242
View File
@@ -0,0 +1,242 @@
// =============================================================================
// Std::Crypto::Jwt — JSON Web Token (RFC 7519) encode/decode
// Supports HS256, HS384, HS512, RS256, RS384, RS512, ES256, ES384, EdDSA
// =============================================================================
module Std::Crypto::Jwt {
import Std::Mem::{Alloc, Free};
import Std::String::{String_Len, String_Eq, String_StartsWith, String_Concat};
import Std::Crypto::Base64::{Base64URL_Encode, Base64URL_Decode};
import Std::Crypto::Hash::{Hash_Sha256Raw, Hash_Sha384Raw, Hash_Sha512Raw};
import Std::Crypto::Hmac::{Hmac_Sha256Raw, Hmac_Sha384Raw, Hmac_Sha512Raw};
import Std::Crypto::Rsa::{Rsa_SignSha256, Rsa_SignSha384, Rsa_SignSha512,
Rsa_VerifySha256, Rsa_VerifySha384, Rsa_VerifySha512};
import Std::Crypto::Ecdsa::{Ecdsa_SignP256, Ecdsa_SignP384, Ecdsa_VerifyP256, Ecdsa_VerifyP384};
import Std::Crypto::Ed25519::{Ed25519_Sign, Ed25519_Verify};
extern func bux_base64_encode(data: String, len: int) -> String;
extern func bux_str_split_count(s: String, delim: String) -> uint;
extern func bux_str_split_part(s: String, delim: String, index: uint) -> String;
// --- JWT Algorithm enum ---
enum JwtAlg {
HS256,
HS384,
HS512,
RS256,
RS384,
RS512,
ES256,
ES384,
EdDSA,
}
// --- Header ---
// Jwt_MakeHeader: build the JWT header JSON string for the given algorithm
func Jwt_MakeHeader(alg: JwtAlg) -> String {
if alg.tag == JwtAlg_HS256 { return "{\"alg\":\"HS256\",\"typ\":\"JWT\"}"; }
if alg.tag == JwtAlg_HS384 { return "{\"alg\":\"HS384\",\"typ\":\"JWT\"}"; }
if alg.tag == JwtAlg_HS512 { return "{\"alg\":\"HS512\",\"typ\":\"JWT\"}"; }
if alg.tag == JwtAlg_RS256 { return "{\"alg\":\"RS256\",\"typ\":\"JWT\"}"; }
if alg.tag == JwtAlg_RS384 { return "{\"alg\":\"RS384\",\"typ\":\"JWT\"}"; }
if alg.tag == JwtAlg_RS512 { return "{\"alg\":\"RS512\",\"typ\":\"JWT\"}"; }
if alg.tag == JwtAlg_ES256 { return "{\"alg\":\"ES256\",\"typ\":\"JWT\"}"; }
if alg.tag == JwtAlg_ES384 { return "{\"alg\":\"ES384\",\"typ\":\"JWT\"}"; }
if alg.tag == JwtAlg_EdDSA { return "{\"alg\":\"EdDSA\",\"typ\":\"JWT\"}"; }
return "{\"alg\":\"none\",\"typ\":\"JWT\"}";
}
// --- Signing ---
// Sign the JWT signing input with the given algorithm
func Jwt_Sign(alg: JwtAlg, signingInput: String, key: String) -> String {
let algTag: int = alg.tag;
let inputLen: int = String_Len(signingInput) as int;
// --- HMAC algorithms ---
if algTag == JwtAlg_HS256 {
let buf: *void = Alloc(32);
Hmac_Sha256Raw(key, signingInput, buf);
let result: String = bux_base64_encode(buf as String, 32);
Free(buf);
return result;
}
if algTag == JwtAlg_HS384 {
let buf: *void = Alloc(48);
Hmac_Sha384Raw(key, signingInput, buf);
let result: String = bux_base64_encode(buf as String, 48);
Free(buf);
return result;
}
if algTag == JwtAlg_HS512 {
let buf: *void = Alloc(64);
Hmac_Sha512Raw(key, signingInput, buf);
let result: String = bux_base64_encode(buf as String, 64);
Free(buf);
return result;
}
// --- RSA algorithms (key is PEM private key) ---
if algTag == JwtAlg_RS256 {
let raw: String = Rsa_SignSha256(key, signingInput);
return bux_base64_encode(raw, String_Len(raw) as int);
}
if algTag == JwtAlg_RS384 {
let raw: String = Rsa_SignSha384(key, signingInput);
return bux_base64_encode(raw, String_Len(raw) as int);
}
if algTag == JwtAlg_RS512 {
let raw: String = Rsa_SignSha512(key, signingInput);
return bux_base64_encode(raw, String_Len(raw) as int);
}
// --- ECDSA algorithms (key is PEM private key) ---
if algTag == JwtAlg_ES256 {
let raw: String = Ecdsa_SignP256(key, signingInput);
return bux_base64_encode(raw, String_Len(raw) as int);
}
if algTag == JwtAlg_ES384 {
let raw: String = Ecdsa_SignP384(key, signingInput);
return bux_base64_encode(raw, String_Len(raw) as int);
}
// --- EdDSA (key is 32-byte raw private key) ---
if algTag == JwtAlg_EdDSA {
return Ed25519_Sign(key, signingInput);
}
return "";
}
// --- Verify ---
// Verify a JWT signature
func Jwt_Verify(alg: JwtAlg, signingInput: String, signatureB64: String, key: String) -> bool {
let algTag: int = alg.tag;
let inputLen: int = String_Len(signingInput) as int;
// --- HMAC algorithms ---
if algTag == JwtAlg_HS256 {
let expectBuf: *void = Alloc(32);
Hmac_Sha256Raw(key, signingInput, expectBuf);
let expectB64: String = bux_base64_encode(expectBuf as String, 32);
Free(expectBuf);
return String_Eq(expectB64, signatureB64);
}
if algTag == JwtAlg_HS384 {
let expectBuf: *void = Alloc(48);
Hmac_Sha384Raw(key, signingInput, expectBuf);
let expectB64: String = bux_base64_encode(expectBuf as String, 48);
Free(expectBuf);
return String_Eq(expectB64, signatureB64);
}
if algTag == JwtAlg_HS512 {
let expectBuf: *void = Alloc(64);
Hmac_Sha512Raw(key, signingInput, expectBuf);
let expectB64: String = bux_base64_encode(expectBuf as String, 64);
Free(expectBuf);
return String_Eq(expectB64, signatureB64);
}
// --- RSA algorithms ---
if algTag == JwtAlg_RS256 { return Rsa_VerifySha256(key, signingInput, signatureB64); }
if algTag == JwtAlg_RS384 { return Rsa_VerifySha384(key, signingInput, signatureB64); }
if algTag == JwtAlg_RS512 { return Rsa_VerifySha512(key, signingInput, signatureB64); }
// --- ECDSA algorithms ---
if algTag == JwtAlg_ES256 { return Ecdsa_VerifyP256(key, signingInput, signatureB64); }
if algTag == JwtAlg_ES384 { return Ecdsa_VerifyP384(key, signingInput, signatureB64); }
// --- EdDSA ---
if algTag == JwtAlg_EdDSA { return Ed25519_Verify(key, signatureB64, signingInput); }
return false;
}
// --- Encode ---
// Jwt_Encode: create a signed JWT
// headerJson — JSON header string (use Jwt_MakeHeader or custom)
// payloadJson — JSON payload/claims string
// alg — signing algorithm
// key — signing key (HMAC secret, RSA PEM, ECDSA PEM, or Ed25519 raw privkey)
// Returns the complete "header.payload.signature" JWT string
func Jwt_Encode(headerJson: String, payloadJson: String, alg: JwtAlg, key: String) -> String {
let headerB64: String = Base64URL_Encode(headerJson);
let payloadB64: String = Base64URL_Encode(payloadJson);
let signingInput: String = String_Concat(headerB64, ".");
let signingInputFull: String = String_Concat(signingInput, payloadB64);
let sigB64: String = Jwt_Sign(alg, signingInputFull, key);
let part1: String = String_Concat(signingInputFull, ".");
return String_Concat(part1, sigB64);
}
// --- Decode ---
// Jwt_Decode: decode and verify a JWT.
// token — the full "header.payload.signature" string
// alg — expected algorithm
// key — verification key
// headerOut — receives decoded header JSON
// payloadOut — receives decoded payload JSON
// Returns true if signature is valid.
func Jwt_Decode(token: String, alg: JwtAlg, key: String,
headerOut: *String, payloadOut: *String) -> bool {
// Split by "."
let partCount: uint = bux_str_split_count(token, ".");
if partCount != 3 { return false; }
let headerB64: String = bux_str_split_part(token, ".", 0);
let payloadB64: String = bux_str_split_part(token, ".", 1);
let sigB64: String = bux_str_split_part(token, ".", 2);
// Build signing input
let input: String = String_Concat(headerB64, ".");
let signingInput: String = String_Concat(input, payloadB64);
// Verify signature
if !Jwt_Verify(alg, signingInput, sigB64, key) {
return false;
}
// Decode
headerOut[0] = Base64URL_Decode(headerB64);
payloadOut[0] = Base64URL_Decode(payloadB64);
return true;
}
// --- Convenience: Encode with standard header ---
func Jwt_EncodeHS256(payloadJson: String, secret: String) -> String {
let header: String = Jwt_MakeHeader(JwtAlg { tag: JwtAlg_HS256 });
return Jwt_Encode(header, payloadJson, JwtAlg { tag: JwtAlg_HS256 }, secret);
}
func Jwt_EncodeHS384(payloadJson: String, secret: String) -> String {
let header: String = Jwt_MakeHeader(JwtAlg { tag: JwtAlg_HS384 });
return Jwt_Encode(header, payloadJson, JwtAlg { tag: JwtAlg_HS384 }, secret);
}
func Jwt_EncodeHS512(payloadJson: String, secret: String) -> String {
let header: String = Jwt_MakeHeader(JwtAlg { tag: JwtAlg_HS512 });
return Jwt_Encode(header, payloadJson, JwtAlg { tag: JwtAlg_HS512 }, secret);
}
func Jwt_EncodeRS256(payloadJson: String, pemPrivateKey: String) -> String {
let header: String = Jwt_MakeHeader(JwtAlg { tag: JwtAlg_RS256 });
return Jwt_Encode(header, payloadJson, JwtAlg { tag: JwtAlg_RS256 }, pemPrivateKey);
}
func Jwt_EncodeES256(payloadJson: String, pemPrivateKey: String) -> String {
let header: String = Jwt_MakeHeader(JwtAlg { tag: JwtAlg_ES256 });
return Jwt_Encode(header, payloadJson, JwtAlg { tag: JwtAlg_ES256 }, pemPrivateKey);
}
func Jwt_EncodeEdDSA(payloadJson: String, rawPrivKey: String) -> String {
let header: String = Jwt_MakeHeader(JwtAlg { tag: JwtAlg_EdDSA });
return Jwt_Encode(header, payloadJson, JwtAlg { tag: JwtAlg_EdDSA }, rawPrivKey);
}
}
+63
View File
@@ -0,0 +1,63 @@
// =============================================================================
// Std::Crypto::Random — cryptographically secure random bytes
// =============================================================================
module Std::Crypto::Random {
import Std::Mem::{Alloc, Free};
extern func bux_random_bytes(buf: *void, len: int) -> int;
extern func bux_base64_encode(data: String, len: int) -> String;
extern func bux_bytes_to_hex(data: *void, len: int) -> String;
// RandomBytes: returns n cryptographically secure random bytes as a raw string
func Random_Bytes(n: int) -> String {
if n <= 0 { return ""; }
let buf: *void = Alloc(n as uint);
if bux_random_bytes(buf, n) != 1 {
Free(buf);
return "";
}
// Return raw buffer as string (binary-safe)
return buf as String;
}
// RandomHex: returns n random bytes as lowercase hex
func Random_Hex(n: int) -> String {
if n <= 0 { return ""; }
let buf: *void = Alloc(n as uint);
if bux_random_bytes(buf, n) != 1 {
Free(buf);
return "";
}
let result: String = bux_bytes_to_hex(buf, n);
Free(buf);
return result;
}
// RandomBase64: returns n random bytes as base64-encoded string
func Random_Base64(n: int) -> String {
if n <= 0 { return ""; }
let buf: *void = Alloc(n as uint);
if bux_random_bytes(buf, n) != 1 {
Free(buf);
return "";
}
let result: String = bux_base64_encode(buf as String, n);
Free(buf);
return result;
}
// RandomUint32: returns a random 32-bit unsigned integer
func Random_Uint32() -> uint {
let buf: *void = Alloc(4);
if bux_random_bytes(buf, 4) != 1 {
Free(buf);
return 0;
}
// Interpret first 4 bytes as uint (native endian)
let ptr: *uint = buf as *uint;
let val: uint = *ptr;
Free(buf);
return val;
}
}
+98
View File
@@ -0,0 +1,98 @@
// =============================================================================
// Std::Crypto::Rsa — RSA PKCS#1 v1.5 sign/verify (SHA-256, SHA-384, SHA-512)
// =============================================================================
module Std::Crypto::Rsa {
import Std::Mem::{Alloc, Free};
import Std::String::{String_Len};
extern func bux_rsa_sign_sha256(pemKey: String, keylen: int, data: String, datalen: int, siglen: *int) -> String;
extern func bux_rsa_sign_sha384(pemKey: String, keylen: int, data: String, datalen: int, siglen: *int) -> String;
extern func bux_rsa_sign_sha512(pemKey: String, keylen: int, data: String, datalen: int, siglen: *int) -> String;
extern func bux_rsa_verify_sha256(pemKey: String, keylen: int, data: String, datalen: int, sig: String, siglen: int) -> int;
extern func bux_rsa_verify_sha384(pemKey: String, keylen: int, data: String, datalen: int, sig: String, siglen: int) -> int;
extern func bux_rsa_verify_sha512(pemKey: String, keylen: int, data: String, datalen: int, sig: String, siglen: int) -> int;
extern func bux_base64_encode(data: String, len: int) -> String;
extern func bux_base64_decode(data: String, len: int, outlen: *int) -> String;
// --- RSA Sign ---
// Rsa_SignSha256: sign data with RSA private key (PEM format), returns raw signature
func Rsa_SignSha256(pemPrivateKey: String, data: String) -> String {
let siglen: int = 0;
return bux_rsa_sign_sha256(pemPrivateKey, String_Len(pemPrivateKey) as int,
data, String_Len(data) as int, &siglen);
}
func Rsa_SignSha384(pemPrivateKey: String, data: String) -> String {
let siglen: int = 0;
return bux_rsa_sign_sha384(pemPrivateKey, String_Len(pemPrivateKey) as int,
data, String_Len(data) as int, &siglen);
}
func Rsa_SignSha512(pemPrivateKey: String, data: String) -> String {
let siglen: int = 0;
return bux_rsa_sign_sha512(pemPrivateKey, String_Len(pemPrivateKey) as int,
data, String_Len(data) as int, &siglen);
}
// Convenience: sign and return base64-encoded signature
func Rsa_SignSha256Base64(pemPrivateKey: String, data: String) -> String {
let sig: String = Rsa_SignSha256(pemPrivateKey, data);
return bux_base64_encode(sig, String_Len(sig) as int);
}
func Rsa_SignSha384Base64(pemPrivateKey: String, data: String) -> String {
let sig: String = Rsa_SignSha384(pemPrivateKey, data);
return bux_base64_encode(sig, String_Len(sig) as int);
}
func Rsa_SignSha512Base64(pemPrivateKey: String, data: String) -> String {
let sig: String = Rsa_SignSha512(pemPrivateKey, data);
return bux_base64_encode(sig, String_Len(sig) as int);
}
// --- RSA Verify ---
// Rsa_VerifySha256: verify raw signature against data with RSA public key (PEM)
// Returns true if signature is valid.
func Rsa_VerifySha256(pemPublicKey: String, data: String, signature: String) -> bool {
let r: int = bux_rsa_verify_sha256(pemPublicKey, String_Len(pemPublicKey) as int,
data, String_Len(data) as int,
signature, String_Len(signature) as int);
return r == 1;
}
func Rsa_VerifySha384(pemPublicKey: String, data: String, signature: String) -> bool {
let r: int = bux_rsa_verify_sha384(pemPublicKey, String_Len(pemPublicKey) as int,
data, String_Len(data) as int,
signature, String_Len(signature) as int);
return r == 1;
}
func Rsa_VerifySha512(pemPublicKey: String, data: String, signature: String) -> bool {
let r: int = bux_rsa_verify_sha512(pemPublicKey, String_Len(pemPublicKey) as int,
data, String_Len(data) as int,
signature, String_Len(signature) as int);
return r == 1;
}
// Convenience: verify base64-encoded signature
func Rsa_VerifySha256Base64(pemPublicKey: String, data: String, signatureB64: String) -> bool {
let outlen: int = 0;
let sig: String = bux_base64_decode(signatureB64, String_Len(signatureB64) as int, &outlen);
return Rsa_VerifySha256(pemPublicKey, data, sig);
}
func Rsa_VerifySha384Base64(pemPublicKey: String, data: String, signatureB64: String) -> bool {
let outlen: int = 0;
let sig: String = bux_base64_decode(signatureB64, String_Len(signatureB64) as int, &outlen);
return Rsa_VerifySha384(pemPublicKey, data, sig);
}
func Rsa_VerifySha512Base64(pemPublicKey: String, data: String, signatureB64: String) -> bool {
let outlen: int = 0;
let sig: String = bux_base64_decode(signatureB64, String_Len(signatureB64) as int, &outlen);
return Rsa_VerifySha512(pemPublicKey, data, sig);
}
}