quarkdash

package module
v0.0.0-...-f1d92c9 Latest Latest
Warning

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

Go to latest
Published: Aug 28, 2026 License: MIT Imports: 11 Imported by: 0

README ยถ

Welcome to QuarkDash Go ๐Ÿ”’ Repository

Current version: 1.2.1 LTS (August 2026)

QuarkDash Crypto Protocol

QuarkDash Go - pure Golang implementation of hybrid post-quantum algorythm. It provides provides post-quantum security, high performance, and attack resistance.

**This is an official protocol port from QuarkDash Typescript Implementation v1.2.0 (clean Go, minimum of dependencies).

Go 1.23 Tests

Have a questions? Contact me


Paper | About | Get Started | TypeScript Version


About QuarkDash Crypto

QuarkDash Crypto - It is a hybrid cryptographic protocol that provides post-quantum security, high performance, and attack resistance. This library can be used as shared solution for your Go applications / server. Written on pure Go (carefully ported from TS). Dependency-free.

Algorithm Scheme can be found here

Read full paper


โ“ Why QuarkDash Crypto?

๐Ÿ”น Lightweight library with zero dependencies;
๐Ÿ”น Powerful crypto algorithm written in Go;
๐Ÿ”น Extremely fast (great for realtime and IoT applications);
๐Ÿ”น Production ready with benchmarks;

๐Ÿ”’ General Components
  • Asymmetric key exchange: Ring-LWE (N=256, Q=7681, ROOT=5685) / R-Ring-LWE (Q=12289, ROOT=8340);
  • Symmetric encryption: ChaCha20 (RFC 7539, 64B block) or lightweight Gimli (48B block) with lazy keystream generation;
  • Key Derivation Function (KDF): SHAKE256 + HKDF-style expand;
  • Message Authentication Code (MAC): SHAKE256(keyโ€–data) 32B, constant-time verify, reusable buffer;
  • Hash: SHA-256 / SHA-512 and SHAKE-256;
  • Replay protection: timestamp (LE64) + sequence number (LE32) + sliding window;
  • Passphrase KDF: PBKDF2-HMAC-SHA256 / Argon2id-lite;
  • Transports: WebSocket / HTTP / gRPC wrappers.
  • Key rotation: by bytes / messages / time.

๐Ÿ“ Project structure

quarkdash-go/
โ”œโ”€โ”€ go.mod                 # module github.com/DevsDaddy/quarkdash-go (Go 1.23)
โ”œโ”€โ”€ quarkdash.go           # QuarkDash protocol core (handshake, Encrypt/Decrypt, rekey)
โ”œโ”€โ”€ api.go                 # public facade - reexport for TS API compatible
โ”œโ”€โ”€ cipher/                # symmetric ciphers with lazy keystream
โ”‚   โ”œโ”€โ”€ cipher.go          # CipherType, NewCipher
โ”‚   โ”œโ”€โ”€ keystream.go       # LazyKeystream (LRU 64 blocks, Seek/Tell/XorInto)
โ”‚   โ”œโ”€โ”€ chacha.go          # ChaCha20 (20 rounds, 64B block)
โ”‚   โ””โ”€โ”€ gimli.go           # Gimli (24 rounds, 48B block)
โ”œโ”€โ”€ hash/                  # Hashes
โ”‚   โ”œโ”€โ”€ shake.go           # SHAKE256 (Keccak-f[1600], 24 rounds, rate 136)
โ”‚   โ””โ”€โ”€ sha.go             # SHA-256 / SHA-512 (stdlib, wrappers)
โ”œโ”€โ”€ core/                  # Basic primitives
โ”‚   โ”œโ”€โ”€ utils.go           # Core helpers: ConcatBytes, RandomBytes, SecureZero, ConstantTimeEqual, LE helpers
โ”‚   โ”œโ”€โ”€ kdf.go             # QuarkDashKDF (SHAKE256, HKDF-like)
โ”‚   โ””โ”€โ”€ mac.go             # QuarkDashMAC (SHAKE256, reusable buffer)
โ”œโ”€โ”€ ringlwe/               # Postquantum exchange (KEM)
โ”‚   โ””โ”€โ”€ ringlwe.go         # BaseRingLWE, RingLWE, RRLWE, NTT, polynomes, security
โ”œโ”€โ”€ rekey/                 # Key rotation
โ”‚   โ””โ”€โ”€ rekey.go           # RekeyPolicy, Build/ParseRekeyPayload, DeriveRekeyMaterial
โ”œโ”€โ”€ passphrase/            # KDF from password
โ”‚   โ””โ”€โ”€ passphrase.go      # PBKDF2, Argon2id-lite, DerivePassphrase
โ”œโ”€โ”€ transport/             # Transport wrappers
โ”‚   โ”œโ”€โ”€ http.go            # QDHTTP (EncryptBody, Middleware, EncryptRequest)
โ”‚   โ”œโ”€โ”€ grpc.go            # QDGRPC (EncryptMessage, ServerInterceptor, WrapClient)
โ”‚   โ””โ”€โ”€ websocket.go       # QDWebSocket (Send/SendJSON, OnDecrypted)
โ”œโ”€โ”€ quarkdash_test.go      # Main algorythm tests
โ”œโ”€โ”€ features_test.go       # Main features tests
โ”œโ”€โ”€ bench_test.go          # Benchmarks
โ””โ”€โ”€ README.md

If you need a full description of algorythm - Welcome to our WIKI


๐Ÿš€ Installation

go get github.com/DevsDaddy/quarkdash-go

Requires Go 1.23+. Without cgo, without external dependencies (only stdlib).


โšก Quick Start

import qd "github.com/DevsDaddy/quarkdash-go"

alice := qd.New(qd.WithCipher(qd.CipherChaCha20))
bob   := qd.New(qd.WithCipher(qd.CipherChaCha20))

aPub := alice.GenerateKeyPair() // 1024B
bPub := bob.GenerateKeyPair()

ct, _ := alice.InitializeSession(bPub, true)  // Alice โ€” initiator
_, _   = bob.InitializeSession(aPub, false)
_      = bob.FinalizeSession(ct)              // Bob โ€” receiver

plain := qd.TextToBytes("Hello QuarkDash ๐Ÿ”’!")
enc, _ := alice.Encrypt(plain) // [12B meta | ciphertext | 32B MAC]
dec, _ := bob.Decrypt(enc)
fmt.Println(qd.BytesToText(dec)) // Hello QuarkDash ๐Ÿ”’!
Gimli (IoT)
alice := qd.New(qd.WithCipher(qd.CipherGimli))
bob   := qd.New(qd.WithCipher(qd.CipherGimli))
// same handshake
Lazy keystream (zero-copy, seek)
key, nonce := qd.RandomBytes(32), qd.RandomBytes(12)
chacha, _ := qd.NewQuarkDashChaCha(key, nonce)
ks := chacha.CreateKeystream()          // ChaChaKeystream (64B block)

chunk := ks.GetBytes(1024, 512)         // custom offset without recompute of all stream
enc   := ks.Xor(plain, 1024)            // XOR with offset
ks.Seek(0)
block := ks.GenerateBlock(1)            // 64B block #1

// Gimli works same - but with 48B block
gimli, _ := qd.NewQuarkDashGimli(key, nonce)
gks := gimli.CreateKeystream()
Key rotation
alice := qd.New(qd.WithCipher(qd.CipherChaCha20), qd.WithRekeyPolicy(qd.RekeyPolicy{AfterBytes: 64*1024*1024, AfterMessages: 10000}))
bob := qd.New(qd.WithCipher(qd.CipherChaCha20))
// ... handshake ...
token, _ := alice.Rekey() // encrypt payload with old session, when derive new keys
_ = bob.ApplyRekey(token)  // decrypt using old session, when derive

if alice.NeedsRekey() { token, _ := alice.Rekey(); bob.ApplyRekey(token) }
cnt, bytes, msgs, _, _ := alice.GetRekeyStats()
Passphrase (PBKDF2 / Argon2id-lite)
salt := qd.GenerateSalt(32)
k1 := qd.PBKDF2SyncBytes([]byte("password"), salt, 100000, 32) // RFC 6070 compatible
k2 := qd.Argon2idSyncBytes([]byte("password"), salt, 32, 3, 32)

key, salt := qd.DerivePassphrase("my secret", qd.PassphraseOptions{Algorithm: "argon2id"})
sess, mac := qd.DeriveKeyForQuarkDash("password", salt, qd.PassphraseOptions{Algorithm: "pbkdf2"})
Transport Wrappers
// HTTP
httpAlice := qd.NewQDHTTP(alice)
httpBob   := qd.NewQDHTTP(bob)
body, hdr, _ := httpAlice.EncryptBodyWithHeaders(map[string]string{"hello":"world"})
var out map[string]string
_ = httpBob.DecryptToJSON(body, &out)
http.Handle("/", httpAlice.Middleware(handler))

// gRPC
grpcAlice := qd.NewQDGRPC(alice)
grpcBob   := qd.NewQDGRPC(bob)
enc, _ := grpcAlice.EncryptMessage([]byte("payload"))
dec, _ := grpcBob.DecryptMessage(enc)

// WebSocket
wsAlice := qd.WrapWebSocket(alice, rawWS) // rawWS implements transport.WSLike
_ = wsAlice.Send(qd.TextToBytes("hello ws"))
wsAlice.OnDecrypted(func(d []byte){ fmt.Println(string(d)) })

๐Ÿ“Š Benchmark

Launched at Intel i5-13420H, Go 1.25, Fedora linux, 16GB RAM:

# Basic benchmark with go bench:
go test -bench=. -benchmem

# Full featured benchmark with table:
go test -bench-report -v -run TestBenchmarkReport
Benchmark results with (ms/op)
Benchmark Time/op (ms) Ops/sec Speed (if available)
Key Generation 0.421 ms 2375 -
Encapsulate 0.812 ms 1231 -
Encrypt 1KB 0.011 ms 94994 -
Decrypt 1KB 0.002 ms 401375 -
Encrypt 1MB 10.275 ms 97 97.32 MB/s
Decrypt 1MB 2.295 ms 436 435.69 MB/s
ChaCha20 raw 1MB 6.805 ms 147 146.96 MB/s
Gimli raw 1MB 8.009 ms 125 124.85 MB/s

๐Ÿ“– API

Category Symbols
Core New(opts...) *QuarkDash, GenerateKeyPair() []byte, InitializeSession(peer []byte, initiator bool) ([]byte,error), FinalizeSession(ct []byte) error, Encrypt([]byte)([]byte,error), Decrypt([]byte)([]byte,error), Dispose()
KDF/MAC QuarkDashKDF, QuarkDashMAC, Shake256Hash, SHA256Hash
Cipher CipherType, NewQuarkDashChaCha, NewQuarkDashGimli, ChaChaKeystream, GimliKeystream
Utils TextToBytes, BytesToText, RandomBytes, ConcatBytes, BytesToHex
Passphrase GenerateSalt, PBKDF2SyncBytes, Argon2idSyncBytes, DerivePassphrase, DeriveKeyForQuarkDash
Rekey (Key rotation) RekeyPolicy, DefaultRekeyPolicy, NeedsRekey(), Rekey(), ApplyRekey()
Ring LWE NewRRLWE(), NewRingLWE(), NTTProtectionOptions
Transport NewQDHTTP, NewQDGRPC, WrapWebSocket, WSLike

๐Ÿงช Tests

go test ./... -cover          # 66%
go test -run TestLarge -count=1
go test -bench=. -benchtime=2x # benchmarks
go vet ./...                   # stats
go test -race ./...            # race

How it works?

Below I've outlined a brief step-by-step flowchart of how the algorithm works. If you need more detailed information, please visit the Wiki.

Step-by-Step Algorithm:

  1. Key Pair Generation (using Ringโ€‘LWE);
  2. Session Setup (using SHAKE-256 emulated KEM);
  3. Session Key Flow (KDF);
  4. Message Encryption (AEAD);
  5. Decryption;

Read more about algorithm in Wiki or View scheme

Have a questions? Contact me


Licensing

QuarkDash Crypto library is distributed under the MIT license. You can use it however you like. I would appreciate any feedback and suggestions for improvement. Full license text can be found here


Paper | About | Get Started | TypeScript Version

Documentation ยถ

Overview ยถ

QuarkDash Module

@git https://github.com/devsdaddy/quarkdash-go @version 1.2.1 @author Elijah Rastorguev @build 1023 @website https://dev.to/devsdaddy @updated 28.08.2026

QuarkDash Implementation ยถ

@git https://github.com/devsdaddy/quarkdash-go @version 1.2.1 @author Elijah Rastorguev @build 1023 @website https://dev.to/devsdaddy @updated 28.08.2026

Index ยถ

Constants ยถ

View Source
const (
	CipherChaCha20 = cipher.CipherChaCha20
	CipherGimli    = cipher.CipherGimli
)

Variables ยถ

View Source
var (
	ErrSessionNotEstablished = errors.New("session not established")
	ErrSessionNotInitialized = errors.New("session not initialized")
	ErrMACVerificationFailed = errors.New("MAC verification failed")
	ErrTimestampOutOfWindow  = errors.New("timestamp out of window")
	ErrReplayDetected        = errors.New("replay detected")
	ErrRekeyCounterMismatch  = errors.New("rekey counter mismatch")
	ErrInvalidNonce          = errors.New("nonce must be 12 bytes")
	ErrInvalidCiphertext     = errors.New("invalid ciphertext")
)
View Source
var DefaultNTTProtection = ringlwe.DefaultNTTProtection
View Source
var DefaultRekeyPolicy = rekey.DefaultRekeyPolicy

Functions ยถ

func Argon2idSync ยถ

func Argon2idSync(pass string, salt []byte, mc, tc, dkLen int) []byte

func Argon2idSyncBytes ยถ

func Argon2idSyncBytes(pass, salt []byte, mc, tc, dkLen int) []byte

func BytesToHex ยถ

func BytesToHex(b []byte) string

func BytesToText ยถ

func BytesToText(b []byte) string

func ConcatBytes ยถ

func ConcatBytes(arrays ...[]byte) []byte

func DeriveKeyForQuarkDash ยถ

func DeriveKeyForQuarkDash(pass string, salt []byte, opts PassphraseOptions) (sess, mac []byte)

func DerivePassphrase ยถ

func DerivePassphrase(pass string, opts PassphraseOptions) (key, salt []byte)

func GenerateSalt ยถ

func GenerateSalt(length int) []byte

func PBKDF2Sync ยถ

func PBKDF2Sync(pass string, salt []byte, iter, dkLen int) []byte

func PBKDF2SyncBytes ยถ

func PBKDF2SyncBytes(pass, salt []byte, iter, dkLen int) []byte

func RandomBytes ยถ

func RandomBytes(n int) []byte

func SHA256Hash ยถ

func SHA256Hash(data []byte) []byte

func SHA512Hash ยถ

func SHA512Hash(data []byte) []byte

func SecureZeroBytes ยถ

func SecureZeroBytes(b []byte)

func Shake256Hash ยถ

func Shake256Hash(data []byte, outLen int) []byte

============================================================================= Hashes =============================================================================

func TextToBytes ยถ

func TextToBytes(s string) []byte

============================================================================= Re-export core utils =============================================================================

func WithCipher ยถ

func WithCipher(ct CipherType) func(*Options)

func WithKDF ยถ

func WithKDF(k KDF) func(*Options)

func WithKeyExchange ยถ

func WithKeyExchange(kx KeyExchange) func(*Options)

func WithMAC ยถ

func WithMAC(m MAC) func(*Options)

func WithMaxPacketWindow ยถ

func WithMaxPacketWindow(n int) func(*Options)

func WithRekeyPolicy ยถ

func WithRekeyPolicy(p RekeyPolicy) func(*Options)

func WithTimestampToleranceMs ยถ

func WithTimestampToleranceMs(n int64) func(*Options)

func WithUsePerMessageNonce ยถ

func WithUsePerMessageNonce(v bool) func(*Options)

Types ยถ

type BaseRingLWE ยถ

type BaseRingLWE = ringlwe.BaseRingLWE

============================================================================= Ring LWE =============================================================================

type ChaChaKeystream ยถ

type ChaChaKeystream = cipher.ChaChaKeystream

type Cipher ยถ

type Cipher = cipher.Cipher

Cipher - a cipher interface

type CipherType ยถ

type CipherType = cipher.CipherType

CipherType - type of symmetric cipher

type Encryptor ยถ

type Encryptor = transport.Encryptor

Encryptor - alias for transport.Encryptor (for external usage)

type GimliKeystream ยถ

type GimliKeystream = cipher.GimliKeystream

type GrpcCall ยถ

type GrpcCall = transport.GrpcCall

type KDF ยถ

type KDF = core.KDF

KDF interface

type KeyExchange ยถ

type KeyExchange interface {
	GenerateKeyPair() (pub, priv []byte)
	Encapsulate(pubKey []byte) (ciphertext, sharedSecret []byte, err error)
	Decapsulate(privKey, peerPubKey, ciphertext []byte) ([]byte, error)
}

KeyExchange - key exchange interface (KEM).

type MAC ยถ

type MAC = core.MAC

MAC authentication interface

type NTTProtectionOptions ยถ

type NTTProtectionOptions = ringlwe.NTTProtectionOptions

NTTProtectionOptions - NTT security options

type Options ยถ

type Options struct {
	Cipher               CipherType
	KDF                  KDF
	MAC                  MAC
	KeyExchange          KeyExchange
	MaxPacketWindow      int
	TimestampToleranceMs int64
	Rekey                RekeyOptions
	UsePerMessageNonce   bool
}

Options - basic QuarkDash configuration.

type PassphraseOptions ยถ

type PassphraseOptions = passphrase.PassphraseOptions

============================================================================= Passphrase =============================================================================

type QDGRPC ยถ

type QDGRPC = transport.QDGRPC

func NewQDGRPC ยถ

func NewQDGRPC(enc Encryptor, metaKey ...string) *QDGRPC

type QDHTTP ยถ

type QDHTTP = transport.QDHTTP

============================================================================= Transport wrappers - Lightweight transport =============================================================================

func NewQDHTTP ยถ

func NewQDHTTP(enc Encryptor, opts ...QDHTTPOptions) *QDHTTP

type QDHTTPOptions ยถ

type QDHTTPOptions = transport.QDHTTPOptions

type QDWebSocket ยถ

type QDWebSocket = transport.QDWebSocket

func NewQDWebSocket ยถ

func NewQDWebSocket(enc Encryptor, ws WSLike) *QDWebSocket

func WrapWebSocket ยถ

func WrapWebSocket(enc Encryptor, ws WSLike) *QDWebSocket

type QuarkDash ยถ

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

QuarkDash - general protocol class. Threadsafety (sync.Mutex), support per-message nonce, replay-security and rekey (key rotation).

func New ยถ

func New(opts ...func(*Options)) *QuarkDash

New create a new QuarkDash Instance with options.

func (*QuarkDash) ApplyRekey ยถ

func (qd *QuarkDash) ApplyRekey(token []byte) error

ApplyRekey apply key rotation token from peer (decrypt using old session, when derive).

func (*QuarkDash) Decrypt ยถ

func (qd *QuarkDash) Decrypt(ciphertext []byte) ([]byte, error)

Decrypt decrypt data and check MAC with reply-security.

func (*QuarkDash) Dispose ยถ

func (qd *QuarkDash) Dispose()

Dispose cleanup keys in memory.

func (*QuarkDash) Encrypt ยถ

func (qd *QuarkDash) Encrypt(plaintext []byte) ([]byte, error)

Encrypt encrypt data: [12B metadata | ciphertext | 32B MAC].

func (*QuarkDash) FinalizeSession ยถ

func (qd *QuarkDash) FinalizeSession(ciphertext []byte) error

FinalizeSession complete handshake on receiver side.

func (*QuarkDash) GenerateKeyPair ยถ

func (qd *QuarkDash) GenerateKeyPair() []byte

GenerateKeyPair generates key pair (pub 1024B, private 512B).

func (*QuarkDash) GetMacKey ยถ

func (qd *QuarkDash) GetMacKey() []byte

func (*QuarkDash) GetRekeyCounter ยถ

func (qd *QuarkDash) GetRekeyCounter() int

GetRekeyCounter return key rotation counter.

func (*QuarkDash) GetRekeyStats ยถ

func (qd *QuarkDash) GetRekeyStats() (counter, bytesEnc, messagesEnc int, lastRekey time.Time, policy RekeyPolicy)

GetRekeyStats return key rotation static.

func (*QuarkDash) GetSessionKey ยถ

func (qd *QuarkDash) GetSessionKey() []byte

GetSessionKey / GetMacKey - for tests/debugging.

func (*QuarkDash) InitializeSession ยถ

func (qd *QuarkDash) InitializeSession(peerPublicKey []byte, isInitiator bool) ([]byte, error)

InitializeSession start a handshake. If isInitiator=true, return ciphertext to send to peer.

func (*QuarkDash) NeedsRekey ยถ

func (qd *QuarkDash) NeedsRekey() bool

NeedsRekey checks, need key rotation or not using current policy.

func (*QuarkDash) Rekey ยถ

func (qd *QuarkDash) Rekey() ([]byte, error)

Rekey generates a key rotation token (encrypt payload with old session, and derive new keys).

func (*QuarkDash) SetRekeyPolicy ยถ

func (qd *QuarkDash) SetRekeyPolicy(p RekeyPolicy)

SetRekeyPolicy update rotation policy.

type QuarkDashChaCha ยถ

type QuarkDashChaCha = cipher.QuarkDashChaCha

============================================================================= Ciphers (cipher) - re-export =============================================================================

func NewQuarkDashChaCha ยถ

func NewQuarkDashChaCha(key, nonce []byte) (*QuarkDashChaCha, error)

type QuarkDashGimli ยถ

type QuarkDashGimli = cipher.QuarkDashGimli

func NewQuarkDashGimli ยถ

func NewQuarkDashGimli(key, nonce []byte) (*QuarkDashGimli, error)

type QuarkDashKDF ยถ

type QuarkDashKDF = core.QuarkDashKDF

============================================================================= KDF / MAC =============================================================================

func NewQuarkDashKDF ยถ

func NewQuarkDashKDF() *QuarkDashKDF

type QuarkDashMAC ยถ

type QuarkDashMAC = core.QuarkDashMAC

func NewQuarkDashMAC ยถ

func NewQuarkDashMAC() *QuarkDashMAC

type QuarkDashRLWE ยถ

type QuarkDashRLWE = RingLWE

type QuarkDashRRLWE ยถ

type QuarkDashRRLWE = RRLWE

type RRLWE ยถ

type RRLWE = ringlwe.RRLWE

func NewQuarkDashRRLWE ยถ

func NewQuarkDashRRLWE() *RRLWE

func NewRRLWE ยถ

func NewRRLWE() *RRLWE

type RekeyOptions ยถ

type RekeyOptions struct {
	Policy    RekeyPolicy
	AutoRekey bool
	OnRekey   func(counter int)
}

RekeyOptions - key rotation options.

type RekeyPolicy ยถ

type RekeyPolicy = rekey.RekeyPolicy

RekeyPolicy key rotation policy

type RingLWE ยถ

type RingLWE = ringlwe.RingLWE

func NewQuarkDashRLWE ยถ

func NewQuarkDashRLWE() *RingLWE

func NewRingLWE ยถ

func NewRingLWE() *RingLWE

type WSLike ยถ

type WSLike = transport.WSLike

Directories ยถ

Path Synopsis
QuarkDash ChaCha20 Implementation
QuarkDash ChaCha20 Implementation
QuarkDash KDF Implementation
QuarkDash KDF Implementation
QuarkDash SHA Implementation
QuarkDash SHA Implementation
QuarkDash Passphrase Implementation
QuarkDash Passphrase Implementation
QuarkDash Key Rotation Implementation
QuarkDash Key Rotation Implementation
QuarkDash Key Ring-LWE Implementation
QuarkDash Key Ring-LWE Implementation
QuarkDash gRPC Wrapper
QuarkDash gRPC Wrapper

Jump to

Keyboard shortcuts

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