crypto

package
v0.0.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 13, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package crypto implements Authenticated Encryption with Associated Data (AEAD).

This file (aead.go) supports two AEAD algorithms:

  • AES-256-GCM: FIPS-approved, hardware-accelerated on modern CPUs
  • ChaCha20-Poly1305: High performance without hardware support

Mathematical Foundation:

AES-256-GCM:

  • AES: Block cipher with 256-bit key, 128-bit blocks
  • GCM: Galois/Counter Mode for authenticated encryption
  • Security: IND-CCA2 secure, 128-bit authentication tag
  • Nonce: 96-bit, MUST be unique per (key, plaintext) pair

ChaCha20-Poly1305:

  • ChaCha20: Stream cipher with 256-bit key, 96-bit nonce
  • Poly1305: One-time authenticator for MAC
  • Security: IND-CCA2 secure, 128-bit authentication tag
  • Nonce: 96-bit, MUST be unique per (key, plaintext) pair

CRITICAL: Nonce reuse completely breaks security. Each (key, nonce) pair MUST be used at most once. This implementation uses counters for nonce generation and tracks usage to prevent reuse.

Package crypto implements cryptographic primitives for the Quantum-Go VPN.

This file (buffer_pool.go) provides buffer pooling to reduce memory allocations during encryption/decryption, which is critical for high-throughput scenarios. The pool uses size classes optimized for typical AEAD operations.

Package crypto implements Conditional Self-Tests (CST) for FIPS 140-3 compliance.

Conditional Self-Tests differ from Power-On Self-Tests (POST) in that they run during specific cryptographic operations rather than at module initialization. They verify that each operation produces consistent, correct results.

FIPS 140-3 requires two types of conditional self-tests:

  1. Pairwise Consistency Test: Verifies that a newly generated key pair is consistent (the private and public keys correspond correctly).

  2. DRBG Health Check: Verifies that the random number generator produces non-repeating, non-zero output.

In FIPS mode, CST failures cause a panic to prevent use of potentially compromised keys or random data. In standard mode, failures return errors.

Package crypto implements cryptographic primitives for the Quantum-Go VPN.

This file is compiled when the "fips" build tag is NOT specified. In standard mode, all supported algorithms are available.

Package crypto implements key derivation functions using SHAKE-256 (SHA-3 XOF).

This file (kdf.go) uses SHAKE-256 (FIPS 202), an extendable-output function (XOF) based on the Keccak sponge construction. It provides 256-bit security against collision and preimage attacks, and 128-bit security against length-extension attacks.

Mathematical Foundation:

SHAKE-256 uses the Keccak-f[1600] permutation with rate r = 1088 and capacity c = 512. The sponge construction:

1. Absorb: Process message blocks through the permutation 2. Squeeze: Extract arbitrary-length output

Security Properties:

  • 256-bit preimage and collision resistance
  • Extendable output: can generate arbitrary length keys
  • No length-extension attacks (unlike SHA-2)
  • Domain separation prevents key/message confusion

Usage in CH-KEM: The KDF combines multiple secret values with domain separation to derive the final shared secret:

K = SHAKE-256(K_x25519 || K_mlkem || transcript_hash || context_info, 256)

Package crypto implements ML-KEM-1024 key encapsulation mechanism wrapper.

This file (mlkem.go) wraps ML-KEM, which is standardized in NIST FIPS 203. The security of ML-KEM is based on the computational difficulty of the Module Learning With Errors (MLWE) problem.

Mathematical Foundation:

The MLWE problem is defined over the polynomial ring R_q = Z_q[X]/(X^n + 1) where n = 256 and q = 3329 for ML-KEM-1024.

Given (A, b = As + e) where:

  • A ∈ R_q^{k×k} is a uniformly random matrix (k=4 for ML-KEM-1024)
  • s ∈ R_q^k is the secret vector
  • e is an error vector sampled from a centered binomial distribution

It is computationally infeasible to distinguish (A, As + e) from uniform random.

Security Level: NIST Category 5 (equivalent to AES-256 against quantum adversaries)

Package crypto implements Power-On Self-Tests (POST) for FIPS 140-3 compliance.

IMPORTANT: POST is production code, not test code. FIPS 140-3 requires self-tests to run at module load time (not just during development testing) to verify the cryptographic implementation before any operations are performed. This catches issues like corrupted binaries, hardware failures, or tampered code.

POST runs automatically when the crypto package is loaded and verifies that all cryptographic primitives produce expected outputs using Known Answer Tests (KAT).

The tests verify:

  • SHAKE-256 (key derivation function)
  • AES-256-GCM (authenticated encryption)
  • ML-KEM-1024 (post-quantum key encapsulation)

In FIPS mode, POST failures cause a panic to prevent use of potentially compromised cryptographic implementations. In standard mode, failures are logged but do not prevent operation.

Package crypto provides cryptographic primitives for the Quantum-Go VPN system. This package wraps Go's standard library cryptographic functions with additional safety checks and consistent error handling.

Security Note: All random number generation uses crypto/rand which provides cryptographically secure random bytes from the operating system's CSPRNG.

Package crypto implements X25519 Elliptic Curve Diffie-Hellman operations.

This file (x25519.go) implements X25519 (RFC 7748), an elliptic curve Diffie-Hellman function using Curve25519. It provides approximately 128 bits of security against classical computers.

Mathematical Foundation:

Curve25519 is a Montgomery curve defined by: y² = x³ + 486662x² + x over the prime field F_p where p = 2²⁵⁵ - 19.

The group operation uses x-coordinate-only arithmetic (Montgomery ladder), which provides constant-time execution and resistance to timing attacks.

Security Properties:

  • IND-CCA2 secure under the Computational Diffie-Hellman assumption on Curve25519
  • Constant-time implementation prevents timing side-channels
  • Twist-secure: operations on the twist are as hard as on the curve

Note: X25519 is NOT quantum-resistant. In CH-KEM, it provides defense-in-depth and maintains security if the post-quantum algorithm (ML-KEM) is broken.

Index

Constants

View Source
const POSTDomain = "POST-KAT-TEST"

POSTDomain is the domain separator used in POST KDF tests

Variables

View Source
var Reader = rand.Reader

Reader is an io.Reader that returns cryptographically secure random bytes. It wraps crypto/rand.Reader for consistent error handling.

Functions

func CSTEnabled added in v0.0.7

func CSTEnabled() bool

CSTEnabled returns true if Conditional Self-Tests are enabled.

func ConstantTimeCompare

func ConstantTimeCompare(a, b []byte) bool

ConstantTimeCompare compares two byte slices in constant time. Returns true if the slices are equal, false otherwise. This prevents timing attacks when comparing secrets.

func DeriveCHKEMSecret

func DeriveCHKEMSecret(x25519Secret, mlkemSecret, transcriptHash []byte) ([]byte, error)

DeriveCHKEMSecret derives the final shared secret for CH-KEM.

This is the core key derivation for the Cascaded Hybrid KEM:

K_final = SHAKE-256(
    K_classical || K_pq || transcript_hash || context_info,
    output_length = 256 bits
)

Security Properties:

  • If EITHER X25519 OR ML-KEM is secure, the output is indistinguishable from random
  • Transcript binding prevents man-in-the-middle attacks
  • Domain separation prevents cross-protocol attacks

Parameters:

  • x25519Secret: 32-byte X25519 shared secret
  • mlkemSecret: 32-byte ML-KEM shared secret
  • transcriptHash: 32-byte hash of the handshake transcript

Returns:

  • sharedSecret: 32-byte final shared secret
  • error: Non-nil if inputs are invalid

func DeriveHandshakeKeys

func DeriveHandshakeKeys(masterSecret []byte) (initiatorKey, responderKey, initiatorIV, responderIV []byte, err error)

DeriveHandshakeKeys derives keys for handshake message encryption.

From the master secret, derives:

  • Initiator write key (32 bytes)
  • Responder write key (32 bytes)
  • Initiator write IV (12 bytes)
  • Responder write IV (12 bytes)

Parameters:

  • masterSecret: The CH-KEM shared secret

Returns:

  • initiatorKey, responderKey: 32-byte encryption keys
  • initiatorIV, responderIV: 12-byte IVs for AEAD
  • error: Non-nil if derivation fails

func DeriveKey

func DeriveKey(domain string, input []byte, outputLen int) ([]byte, error)

DeriveKey derives a key using SHAKE-256 with domain separation.

The derivation follows the construction:

output = SHAKE-256(
    domain_separator_length || domain_separator ||
    input_length || input,
    output_length
)

Length prefixes are 4-byte big-endian integers to ensure unambiguous parsing.

Parameters:

  • domain: Domain separation string (prevents cross-protocol attacks)
  • input: Secret input material to derive from
  • outputLen: Desired output length in bytes

Returns:

  • derived: The derived key material
  • error: Non-nil if parameters are invalid

func DeriveKeyMultiple

func DeriveKeyMultiple(domain string, inputs [][]byte, outputLen int) ([]byte, error)

DeriveKeyMultiple derives a key from multiple inputs with domain separation.

This is used for CH-KEM key derivation where we combine:

  • X25519 shared secret
  • ML-KEM shared secret
  • Transcript hash
  • Context info

Parameters:

  • domain: Domain separation string
  • inputs: Multiple input values to combine
  • outputLen: Desired output length in bytes

Returns:

  • derived: The derived key material
  • error: Non-nil if parameters are invalid

func DeriveRekeySecret

func DeriveRekeySecret(currentSecret, additionalData []byte) ([]byte, error)

DeriveRekeySecret derives a new master secret for session rekeying.

The rekey process: 1. Derive new secret from current master secret + additional entropy 2. Use new secret to derive fresh traffic keys 3. Zeroize old keys

Parameters:

  • currentSecret: The current master secret
  • additionalData: Additional entropy (e.g., timestamp, counter)

Returns:

  • newSecret: New 32-byte master secret
  • error: Non-nil if derivation fails

func DeriveResumptionSecret added in v0.0.9

func DeriveResumptionSecret(psk, freshSecret []byte) ([]byte, error)

DeriveResumptionSecret derives a new master secret for resumed sessions.

This combines the PSK (ticket secret) with a fresh KEM shared secret, providing forward secrecy even when the ticket is compromised. Similar to TLS 1.3's PSK+ECDHE mode.

Parameters:

  • psk: Pre-shared key from the session ticket
  • freshSecret: Fresh shared secret from new CH-KEM exchange

Returns:

  • newSecret: New 32-byte master secret
  • error: Non-nil if inputs are invalid

func DeriveTrafficKeys

func DeriveTrafficKeys(masterSecret []byte) (initiatorKey, responderKey []byte, err error)

DeriveTrafficKeys derives keys for tunnel traffic encryption.

Similar to handshake keys but uses a different domain separator to ensure traffic keys are independent from handshake keys.

Parameters:

  • masterSecret: The CH-KEM shared secret

Returns:

  • initiatorKey, responderKey: 32-byte encryption keys
  • error: Non-nil if derivation fails

func FIPSMode added in v0.0.7

func FIPSMode() bool

FIPSMode reports whether the binary was built in FIPS mode. When false, all supported algorithms (AES-256-GCM and ChaCha20-Poly1305) are available.

func GetCryptoBuffer added in v0.0.6

func GetCryptoBuffer(size int) []byte

GetCryptoBuffer returns a buffer from the global crypto pool.

func GetNonceBuffer added in v0.0.6

func GetNonceBuffer() []byte

GetNonceBuffer returns a nonce buffer from the global pool.

func InitCST added in v0.0.7

func InitCST(config CSTConfig)

InitCST initializes Conditional Self-Tests with the given configuration. Must be called before any cryptographic operations if custom configuration is needed. If not called, default configuration is used.

func MLKEMDecapsulate

func MLKEMDecapsulate(dk *MLKEMPrivateKey, ciphertext []byte) ([]byte, error)

MLKEMDecapsulate performs key decapsulation using ML-KEM-1024.

Decapsulation process (IND-CCA2 secure via Fujisaki-Okamoto transform): 1. Decrypt ciphertext c to obtain m' 2. Recompute (K̄', r') = G(m' || H(pk)) 3. Re-encrypt m' with r' to get c' 4. If c == c': return K = KDF(K̄' || H(c)) 5. If c != c': return K = KDF(z || H(c)) (implicit rejection)

The implicit rejection (step 5) ensures that decapsulation always returns a value that looks random, preventing distinguishing attacks.

Parameters:

  • dk: The decapsulation key (private key)
  • ciphertext: The ciphertext to decapsulate

Returns:

  • sharedSecret: The shared secret (32 bytes)
  • error: Non-nil if ciphertext is malformed

func MLKEMEncapsulate

func MLKEMEncapsulate(ek *MLKEMPublicKey) (ciphertext, sharedSecret []byte, err error)

MLKEMEncapsulate performs key encapsulation using ML-KEM-1024.

Encapsulation process: 1. Sample random coins m ← {0,1}^256 2. Compute (K̄, r) = G(m || H(pk)) where G is SHA3-512 3. Compute ciphertext c using r as randomness 4. Compute K = KDF(K̄ || H(c)) as the final shared secret

Parameters:

  • ek: The recipient's encapsulation key (public key)

Returns:

  • ciphertext: The encapsulated ciphertext (1568 bytes for ML-KEM-1024)
  • sharedSecret: The shared secret (32 bytes)
  • error: Non-nil if encapsulation fails

func MustSecureRandom

func MustSecureRandom(b []byte)

MustSecureRandom reads cryptographically secure random bytes into the provided slice. It panics if the system's CSPRNG fails, as this indicates a critical system failure.

Use this function only in contexts where CSPRNG failure should be unrecoverable.

func MustSecureRandomBytes

func MustSecureRandomBytes(n int) []byte

MustSecureRandomBytes returns n cryptographically secure random bytes. It panics if the system's CSPRNG fails.

func POSTPassed added in v0.0.7

func POSTPassed() bool

POSTPassed returns true if POST has run and all tests passed

func POSTRan added in v0.0.7

func POSTRan() bool

POSTRan returns true if POST has been executed

func ParseX25519PublicKey

func ParseX25519PublicKey(data []byte) (*ecdh.PublicKey, error)

ParseX25519PublicKey parses an X25519 public key from its encoded form.

func PutCryptoBuffer added in v0.0.6

func PutCryptoBuffer(buf []byte)

PutCryptoBuffer returns a buffer to the global crypto pool.

func PutNonceBuffer added in v0.0.6

func PutNonceBuffer(buf []byte)

PutNonceBuffer returns a nonce buffer to the global pool.

func SecureRandom

func SecureRandom(b []byte) error

SecureRandom reads cryptographically secure random bytes into the provided slice. It uses crypto/rand.Read which sources entropy from the OS CSPRNG.

This function will only return an error if the system's random number generator fails, which should be treated as a critical system failure.

func SecureRandomBytes

func SecureRandomBytes(n int) ([]byte, error)

SecureRandomBytes returns n cryptographically secure random bytes. Returns an error if the system's CSPRNG fails.

func SecureRandomWithCST added in v0.0.7

func SecureRandomWithCST(b []byte) error

SecureRandomWithCST reads cryptographically secure random bytes and runs the continuous RNG test in FIPS mode.

func TranscriptHash

func TranscriptHash(components ...[]byte) ([]byte, error)

TranscriptHash computes a hash of the handshake transcript.

The transcript includes all public values exchanged during the handshake:

  • Initiator's public keys (X25519 + ML-KEM)
  • Responder's public keys (X25519 + ML-KEM ciphertext)
  • Protocol version and cipher suite

Using SHA3-256 for the transcript hash provides:

  • 128-bit collision resistance
  • Binding: changes to any transcript component change the hash
  • Non-malleability: prevents transcript manipulation attacks

Parameters:

  • components: Ordered list of transcript components

Returns:

  • hash: 32-byte transcript hash

func X25519

func X25519(privateKey *ecdh.PrivateKey, peerPublic *ecdh.PublicKey) ([]byte, error)

X25519 performs X25519 Diffie-Hellman shared secret computation.

The computation: 1. Validate that peerPublic is a valid point on the curve 2. Compute sharedSecret = privateKey * peerPublic (scalar multiplication) 3. Return the 32-byte x-coordinate of the result

Security Note: The result should never be used directly as a key. Always derive keys using a KDF (e.g., HKDF or SHAKE).

Parameters:

  • privateKey: The local private key
  • peerPublic: The peer's public key

Returns:

  • sharedSecret: 32-byte shared secret
  • error: Non-nil if the peer's public key is invalid

func Zeroize

func Zeroize(b []byte)

Zeroize securely erases sensitive data from memory by overwriting with zeros. This should be called on sensitive keys and secrets when they are no longer needed.

Note: The Go runtime may have already copied the data. runtime.KeepAlive prevents the compiler from optimizing away the zeroing as dead stores. For maximum security, consider using memory protections at the OS level in production deployments.

func ZeroizeMultiple

func ZeroizeMultiple(slices ...[]byte)

ZeroizeMultiple securely erases multiple byte slices.

Types

type AEAD

type AEAD struct {
	// contains filtered or unexported fields
}

AEAD represents an authenticated encryption cipher.

func NewAEAD

func NewAEAD(suite constants.CipherSuite, key []byte) (*AEAD, error)

NewAEAD creates a new AEAD cipher with the specified suite and key.

Parameters:

  • suite: CipherSuiteAES256GCM or CipherSuiteChaCha20Poly1305
  • key: 32-byte encryption key

Returns:

  • AEAD: The initialized cipher
  • error: Non-nil if the key size is wrong, suite unsupported, or not FIPS approved in FIPS mode

func (*AEAD) Counter

func (a *AEAD) Counter() uint64

Counter returns the current nonce counter value. This can be used to check how many messages have been sent.

func (*AEAD) NeedsRekey

func (a *AEAD) NeedsRekey() bool

NeedsRekey returns true if the cipher is approaching nonce exhaustion. Callers should initiate rekey when this returns true.

func (*AEAD) NonceSize

func (a *AEAD) NonceSize() int

NonceSize returns the required nonce size in bytes.

func (*AEAD) Open

func (a *AEAD) Open(ciphertext, additionalData []byte) ([]byte, error)

Open decrypts and verifies ciphertext.

The operation: 1. Extract nonce from ciphertext prefix 2. Verify authentication tag 3. Decrypt: plaintext = AEAD.Open(nonce, ciphertext, additionalData)

Parameters:

  • ciphertext: nonce || encrypted_data || auth_tag
  • additionalData: Must match the additionalData used during Seal

Returns:

  • plaintext: Decrypted data
  • error: Non-nil if authentication fails or ciphertext malformed

func (*AEAD) OpenWithNonce

func (a *AEAD) OpenWithNonce(nonce, ciphertext, additionalData []byte) ([]byte, error)

OpenWithNonce decrypts using an explicit nonce.

Parameters:

  • nonce: 12-byte nonce used during encryption
  • ciphertext: encrypted_data || auth_tag (nonce not included)
  • additionalData: Must match the additionalData used during Seal

Returns:

  • plaintext: Decrypted data
  • error: Non-nil if authentication fails

func (*AEAD) Overhead

func (a *AEAD) Overhead() int

Overhead returns the number of bytes of overhead added by encryption. This is nonce size + authentication tag size.

func (*AEAD) Seal

func (a *AEAD) Seal(plaintext, additionalData []byte) ([]byte, error)

Seal encrypts and authenticates plaintext, returning ciphertext.

The operation: 1. Generate nonce from counter (auto-incrementing) 2. Encrypt: ciphertext = AEAD.Seal(nonce, plaintext, additionalData) 3. Return: nonce || ciphertext (includes auth tag)

Parameters:

  • plaintext: Data to encrypt
  • additionalData: Additional data to authenticate (not encrypted)

Returns:

  • ciphertext: nonce || encrypted_data || auth_tag
  • error: Non-nil if nonce space exhausted

func (*AEAD) SealPooled added in v0.0.6

func (a *AEAD) SealPooled(plaintext, additionalData []byte) ([]byte, error)

SealPooled encrypts using a pooled ciphertext buffer. The caller must call PutCryptoBuffer on the returned ciphertext when done. This is more efficient for high-throughput scenarios.

func (*AEAD) SealWithNonce

func (a *AEAD) SealWithNonce(nonce, plaintext, additionalData []byte) ([]byte, error)

SealWithNonce encrypts using an explicit nonce (for specific protocol needs).

WARNING: The caller is responsible for ensuring nonce uniqueness. Prefer Seal() with automatic nonce generation when possible.

Parameters:

  • nonce: 12-byte unique nonce
  • plaintext: Data to encrypt
  • additionalData: Additional data to authenticate

Returns:

  • ciphertext: encrypted_data || auth_tag (nonce not included)
  • error: Non-nil if nonce size is wrong

func (*AEAD) SetCounter

func (a *AEAD) SetCounter(counter uint64) error

SetCounter sets the nonce counter value. Use with caution - only for resuming sessions with known state.

func (*AEAD) Suite

func (a *AEAD) Suite() constants.CipherSuite

Suite returns the cipher suite identifier.

type BufferPool added in v0.0.6

type BufferPool struct {
	// contains filtered or unexported fields
}

BufferPool provides pooled byte slices for cryptographic operations.

func NewBufferPool added in v0.0.6

func NewBufferPool() *BufferPool

NewBufferPool creates a new crypto buffer pool.

func (*BufferPool) GetCiphertext added in v0.0.6

func (p *BufferPool) GetCiphertext(size int) []byte

GetCiphertext returns a ciphertext buffer of at least the requested size. The size should include space for nonce and tag overhead.

func (*BufferPool) GetNonce added in v0.0.6

func (p *BufferPool) GetNonce() []byte

GetNonce returns a nonce buffer from the pool.

func (*BufferPool) PutCiphertext added in v0.0.6

func (p *BufferPool) PutCiphertext(buf []byte)

PutCiphertext returns a ciphertext buffer to the pool.

func (*BufferPool) PutNonce added in v0.0.6

func (p *BufferPool) PutNonce(buf []byte)

PutNonce returns a nonce buffer to the pool.

type CSTConfig added in v0.0.7

type CSTConfig struct {
	// EnablePairwiseTest enables pairwise consistency tests on key generation
	EnablePairwiseTest bool

	// EnableRNGHealthCheck enables health checks on RNG output
	EnableRNGHealthCheck bool

	// RNGHealthCheckInterval is how often to run full RNG health checks
	// (number of SecureRandom calls between checks)
	RNGHealthCheckInterval uint64
}

CSTConfig configures Conditional Self-Test behavior

func DefaultCSTConfig added in v0.0.7

func DefaultCSTConfig() CSTConfig

DefaultCSTConfig returns the default CST configuration. In FIPS mode, all tests are enabled; in standard mode, tests are disabled by default.

func GetCSTConfig added in v0.0.7

func GetCSTConfig() CSTConfig

GetCSTConfig returns the current CST configuration.

type CSTResult added in v0.0.7

type CSTResult struct {
	Passed bool
	Error  error
}

CSTResult contains the results of a Conditional Self-Test

func ContinuousRNGTest added in v0.0.7

func ContinuousRNGTest(output []byte) *CSTResult

ContinuousRNGTest implements the continuous RNG test required by FIPS 140-3. It compares each RNG output to the previous output and fails if they match. This function should be called after each SecureRandom call in FIPS mode.

func PairwiseConsistencyTestMLKEM added in v0.0.7

func PairwiseConsistencyTestMLKEM(kp *MLKEMKeyPair) *CSTResult

PairwiseConsistencyTestMLKEM verifies that an ML-KEM key pair is consistent by performing encapsulation and decapsulation.

func PairwiseConsistencyTestX25519 added in v0.0.7

func PairwiseConsistencyTestX25519(kp *X25519KeyPair) *CSTResult

PairwiseConsistencyTestX25519 verifies that an X25519 key pair is consistent by performing a DH operation with a test key pair.

func RNGHealthCheck added in v0.0.7

func RNGHealthCheck() *CSTResult

RNGHealthCheck performs a health check on the random number generator. It verifies that: 1. The RNG produces non-zero output 2. The RNG produces non-repeating output 3. The RNG produces output with reasonable entropy distribution

type MLKEMKeyPair

type MLKEMKeyPair struct {
	// EncapsulationKey is the public key used by others to encapsulate secrets
	EncapsulationKey *MLKEMPublicKey

	// DecapsulationKey is the private key used to decapsulate secrets
	DecapsulationKey *MLKEMPrivateKey
}

MLKEMKeyPair represents an ML-KEM-1024 key pair for post-quantum key encapsulation.

func GenerateMLKEMKeyPair

func GenerateMLKEMKeyPair() (*MLKEMKeyPair, error)

GenerateMLKEMKeyPair generates a new ML-KEM-1024 key pair.

The key generation process: 1. Sample random seed d ← {0,1}^256 2. Sample random seed z ← {0,1}^256 3. Expand matrix A from seed using SHAKE-128 4. Sample secret vector s and error vector e from CBD(η₁) 5. Compute public key pk = (A, As + e) 6. Compute private key sk = (s, pk, H(pk), z)

Returns error if the system's CSPRNG fails.

func GenerateMLKEMKeyPairWithCST added in v0.0.7

func GenerateMLKEMKeyPairWithCST() (*MLKEMKeyPair, error)

GenerateMLKEMKeyPairWithCST generates an ML-KEM key pair and runs the pairwise consistency test.

func NewMLKEMKeyPairFromSeed

func NewMLKEMKeyPairFromSeed(seed []byte) (*MLKEMKeyPair, error)

NewMLKEMKeyPairFromSeed generates an ML-KEM-1024 key pair from a 64-byte seed. This is deterministic: the same seed will always produce the same key pair.

The seed should be generated from a cryptographically secure source. This function is useful for key derivation from a master secret.

func (*MLKEMKeyPair) PublicKeyBytes

func (kp *MLKEMKeyPair) PublicKeyBytes() []byte

PublicKeyBytes returns the encoded bytes of the encapsulation key.

func (*MLKEMKeyPair) Zeroize

func (kp *MLKEMKeyPair) Zeroize()

Zeroize securely erases the private key material. This should be called when the key pair is no longer needed.

type MLKEMPrivateKey

type MLKEMPrivateKey struct {
	// contains filtered or unexported fields
}

MLKEMPrivateKey wraps an ML-KEM-1024 private key

type MLKEMPublicKey

type MLKEMPublicKey struct {
	// contains filtered or unexported fields
}

MLKEMPublicKey wraps an ML-KEM-1024 public key

func ParseMLKEMPublicKey

func ParseMLKEMPublicKey(data []byte) (*MLKEMPublicKey, error)

ParseMLKEMPublicKey parses an ML-KEM-1024 public key from its encoded form.

func (*MLKEMPublicKey) Bytes

func (pk *MLKEMPublicKey) Bytes() []byte

Bytes returns the encoded bytes of the public key.

type ModuleIntegrity added in v0.0.7

type ModuleIntegrity struct {
	// ExpectedHash is the expected SHA-256 hash of critical code sections
	// In a real FIPS implementation, this would be computed at build time
	ExpectedHash string

	// ActualHash is computed at runtime
	ActualHash string

	// Verified indicates if the integrity check passed
	Verified bool
}

ModuleIntegrity contains information about the crypto module's integrity

func CheckModuleIntegrity added in v0.0.7

func CheckModuleIntegrity() *ModuleIntegrity

CheckModuleIntegrity performs a module integrity check. This is a simplified implementation - a full FIPS implementation would hash the actual binary code sections.

For this implementation, we verify that the KAT values themselves have not been tampered with by checking their hash.

type POSTResult added in v0.0.7

type POSTResult struct {
	Passed      bool
	KDFPassed   bool
	AESPassed   bool
	MLKEMPassed bool
	Errors      []string
}

POSTResult contains the results of Power-On Self-Tests

func RunPOST added in v0.0.7

func RunPOST() *POSTResult

RunPOST executes the Power-On Self-Tests and returns the results. This function is safe to call multiple times; tests only run once.

type X25519KeyPair

type X25519KeyPair struct {
	// PublicKey is the public component for sharing
	PublicKey *ecdh.PublicKey

	// PrivateKey is the secret component
	PrivateKey *ecdh.PrivateKey
}

X25519KeyPair represents an X25519 key pair for classical ECDH.

func GenerateX25519KeyPair

func GenerateX25519KeyPair() (*X25519KeyPair, error)

GenerateX25519KeyPair generates a new X25519 key pair.

The key generation process: 1. Generate 32 random bytes as the private scalar 2. Apply clamping: clear bits 0,1,2,255; set bit 254 3. Compute public key as scalar multiplication of basepoint

Returns error if the system's CSPRNG fails.

func GenerateX25519KeyPairWithCST added in v0.0.7

func GenerateX25519KeyPairWithCST() (*X25519KeyPair, error)

GenerateX25519KeyPairWithCST generates an X25519 key pair and runs the pairwise consistency test.

func NewX25519KeyPairFromBytes

func NewX25519KeyPairFromBytes(privateKeyBytes []byte) (*X25519KeyPair, error)

NewX25519KeyPairFromBytes creates an X25519 key pair from a 32-byte private key. This is deterministic: the same private key bytes always produce the same key pair.

func (*X25519KeyPair) PrivateKeyBytes

func (kp *X25519KeyPair) PrivateKeyBytes() []byte

PrivateKeyBytes returns the encoded bytes of the private key. Warning: Handle with care - this exposes the secret key material.

func (*X25519KeyPair) PublicKeyBytes

func (kp *X25519KeyPair) PublicKeyBytes() []byte

PublicKeyBytes returns the encoded bytes of the public key.

func (*X25519KeyPair) Zeroize

func (kp *X25519KeyPair) Zeroize()

Zeroize securely erases the private key material.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL