pqc-binary-format 2.0.2

Standardized binary format for post-quantum cryptography encrypted data interchange
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
// Package pqcbinaryformat provides pure Go implementation of PQC Binary Format v1.0
//
// This package implements the PQC Binary Format specification for post-quantum
// cryptographic data encapsulation. It provides constant-time parsing and
// serialization of encrypted data with support for 47 cryptographic algorithms
// including HQC, ML-KEM, ML-DSA, and SLH-DSA NIST FIPS standards.
//
// Example usage:
//
//	// Create a new format
//	format := &PqcBinaryFormat{
//		Version:     1,
//		AlgorithmID: AlgorithmHybrid,
//		Metadata:    []byte(`{"key":"value"}`),
//		Data:        encryptedData,
//	}
//	binary, err := format.Serialize()
//
//	// Parse existing format
//	format, err := Parse(binaryData)
//	fmt.Printf("Algorithm: %s\n", format.AlgorithmName())
package pqcbinaryformat

import (
	"bytes"
	"crypto/sha256"
	"encoding/binary"
	"errors"
	"fmt"
)

// Magic bytes identifying PQC Binary Format
var MagicBytes = []byte{0x50, 0x51, 0x43, 0x01} // "PQC\x01"

// Version constants
const (
	Version1 byte = 0x01
)

// Algorithm IDs - Core Algorithms
const (
	AlgorithmClassical         uint16 = 0x0050
	AlgorithmPasswordClassical uint16 = 0x0051
	AlgorithmHybrid            uint16 = 0x0100
	AlgorithmPostQuantum       uint16 = 0x0200
	AlgorithmMlKem1024         uint16 = 0x0202
	AlgorithmMultiAlgorithm    uint16 = 0x0201
)

// Algorithm IDs - Multi-KEM Series
const (
	AlgorithmMultiKem       uint16 = 0x0203
	AlgorithmMultiKemTriple uint16 = 0x0204
	AlgorithmQuadLayer      uint16 = 0x0205
)

// Algorithm IDs - Advanced Stacks
const (
	AlgorithmLatticeCodeHybrid uint16 = 0x0206
	AlgorithmPq3Stack          uint16 = 0x0207
)

// Algorithm IDs - Max Secure Series
const (
	AlgorithmMaxSecureLightweight      uint16 = 0x0300
	AlgorithmMaxSecurePurePQ           uint16 = 0x0301
	AlgorithmMaxSecureHybrid           uint16 = 0x0302
	AlgorithmMaxSecureStateless        uint16 = 0x0303
	AlgorithmMaxSecureCryptoAgile      uint16 = 0x0304
	AlgorithmMaxSecurePQCZK            uint16 = 0x0305
	AlgorithmMaxSecureHybridTransition uint16 = 0x0306
)

// Algorithm IDs - FN-DSA Signature Series
const (
	AlgorithmFnDsa512Compact      uint16 = 0x0400
	AlgorithmFnDsa1024Security    uint16 = 0x0401
	AlgorithmFnDsaFPHardened      uint16 = 0x0402
	AlgorithmFnDsaDualSignature   uint16 = 0x0403
	AlgorithmFnDsaTransition      uint16 = 0x0404
	AlgorithmFnDsaZK              uint16 = 0x0405
	AlgorithmFnDsaZKStack         uint16 = 0x0406
	AlgorithmFnDsaTransitionStack uint16 = 0x0407
)

// Algorithm IDs - Experimental Series
const (
	AlgorithmQuantumLatticeFusion      uint16 = 0x0500
	AlgorithmPostZKHomomorphic         uint16 = 0x0501
	AlgorithmQuantumResistantConsensus uint16 = 0x0502
	AlgorithmEntropyOrchestrated       uint16 = 0x0503
	AlgorithmLatticeCodeHybridFn       uint16 = 0x0504
	AlgorithmAISynthesizedCryptoAgile  uint16 = 0x0505
	AlgorithmExperimental              uint16 = 0x0506
)

// Algorithm IDs - HQC Code-Based Series (NIST 2025 Backup KEM)
const (
	AlgorithmHqc128 uint16 = 0x0600
	AlgorithmHqc192 uint16 = 0x0601
	AlgorithmHqc256 uint16 = 0x0602
)

// Algorithm IDs - NIST ML-KEM Variants (FIPS 203)
const (
	AlgorithmMlKem512 uint16 = 0x0700
	AlgorithmMlKem768 uint16 = 0x0701
)

// Algorithm IDs - NIST ML-DSA Variants (FIPS 204)
const (
	AlgorithmMlDsa44 uint16 = 0x0800
	AlgorithmMlDsa65 uint16 = 0x0801
	AlgorithmMlDsa87 uint16 = 0x0802
)

// Algorithm IDs - NIST SLH-DSA Variants (FIPS 205)
const (
	AlgorithmSlhDsaSha2_128s uint16 = 0x0900
	AlgorithmSlhDsaSha2_128f uint16 = 0x0901
	AlgorithmSlhDsaSha2_192s uint16 = 0x0902
	AlgorithmSlhDsaSha2_192f uint16 = 0x0903
	AlgorithmSlhDsaSha2_256s uint16 = 0x0904
	AlgorithmSlhDsaSha2_256f uint16 = 0x0905
)

// Algorithm name mappings
var algorithmNames = map[uint16]string{
	AlgorithmClassical:                 "Classical",
	AlgorithmPasswordClassical:         "Password-Classical",
	AlgorithmHybrid:                    "Hybrid",
	AlgorithmPostQuantum:               "Post-Quantum",
	AlgorithmMlKem1024:                 "ML-KEM-1024",
	AlgorithmMultiAlgorithm:            "Multi-Algorithm",
	AlgorithmMultiKem:                  "Multi-KEM Dual Layer",
	AlgorithmMultiKemTriple:            "Multi-KEM Triple Layer",
	AlgorithmQuadLayer:                 "Quad-Layer",
	AlgorithmLatticeCodeHybrid:         "Lattice-Code Hybrid",
	AlgorithmPq3Stack:                  "PQ3-Stack",
	AlgorithmMaxSecureLightweight:      "Max Secure: PQ Lightweight",
	AlgorithmMaxSecurePurePQ:           "Max Secure: Pure PQ",
	AlgorithmMaxSecureHybrid:           "Max Secure: Hybrid",
	AlgorithmMaxSecureStateless:        "Max Secure: Stateless",
	AlgorithmMaxSecureCryptoAgile:      "Max Secure: Crypto-Agile",
	AlgorithmMaxSecurePQCZK:            "Max Secure: PQC + ZK",
	AlgorithmMaxSecureHybridTransition: "Max Secure: Hybrid Transition",
	AlgorithmFnDsa512Compact:           "FN-DSA 512: Compact",
	AlgorithmFnDsa1024Security:         "FN-DSA 1024: High-Security",
	AlgorithmFnDsaFPHardened:           "FN-DSA: Floating-Point Hardened",
	AlgorithmFnDsaDualSignature:        "FN-DSA: Dual Signature",
	AlgorithmFnDsaTransition:           "FN-DSA: Transition Stack",
	AlgorithmFnDsaZK:                   "FN-DSA + ZK Stack",
	AlgorithmFnDsaZKStack:              "FN-DSA + ZK Stack Enhanced",
	AlgorithmFnDsaTransitionStack:      "FN-DSA: Transition Stack Enhanced",
	AlgorithmQuantumLatticeFusion:      "Quantum-Inspired Lattice Fusion",
	AlgorithmPostZKHomomorphic:         "Post-ZK Homomorphic",
	AlgorithmQuantumResistantConsensus: "Quantum-Resistant Consensus",
	AlgorithmEntropyOrchestrated:       "Entropy-Orchestrated",
	AlgorithmLatticeCodeHybridFn:       "Lattice-Code Hybrid FN",
	AlgorithmAISynthesizedCryptoAgile:  "AI-Synthesized Crypto-Agile",
	AlgorithmExperimental:              "Experimental Engine",
	AlgorithmHqc128:                    "HQC-128",
	AlgorithmHqc192:                    "HQC-192",
	AlgorithmHqc256:                    "HQC-256",
	AlgorithmMlKem512:                  "ML-KEM-512",
	AlgorithmMlKem768:                  "ML-KEM-768",
	AlgorithmMlDsa44:                   "ML-DSA-44",
	AlgorithmMlDsa65:                   "ML-DSA-65",
	AlgorithmMlDsa87:                   "ML-DSA-87",
	AlgorithmSlhDsaSha2_128s:           "SLH-DSA-SHA2-128s",
	AlgorithmSlhDsaSha2_128f:           "SLH-DSA-SHA2-128f",
	AlgorithmSlhDsaSha2_192s:           "SLH-DSA-SHA2-192s",
	AlgorithmSlhDsaSha2_192f:           "SLH-DSA-SHA2-192f",
	AlgorithmSlhDsaSha2_256s:           "SLH-DSA-SHA2-256s",
	AlgorithmSlhDsaSha2_256f:           "SLH-DSA-SHA2-256f",
}

// Errors
var (
	ErrInvalidMagic    = errors.New("invalid magic bytes")
	ErrInvalidVersion  = errors.New("invalid version")
	ErrInvalidChecksum = errors.New("invalid checksum")
	ErrInvalidLength   = errors.New("invalid data length")
	ErrBufferTooSmall  = errors.New("buffer too small")
)

// PqcBinaryFormat represents a PQC Binary Format structure
type PqcBinaryFormat struct {
	// Magic bytes (always "PQC\x01")
	Magic []byte

	// Version (currently 0x01)
	Version byte

	// Algorithm identifier (16-bit)
	AlgorithmID uint16

	// Feature flags (reserved, MUST be 0x00 in version 0x01)
	Flags byte

	// Metadata length (32-bit)
	MetadataLen uint32

	// Data length (64-bit)
	DataLen uint64

	// Algorithm-specific metadata
	Metadata []byte

	// Encrypted payload
	Data []byte

	// SHA-256 checksum (32 bytes)
	Checksum [32]byte
}

// New creates a new PqcBinaryFormat with the given parameters
func New(algorithmID uint16, metadata, data []byte) *PqcBinaryFormat {
	format := &PqcBinaryFormat{
		Magic:       make([]byte, 4),
		Version:     Version1,
		AlgorithmID: algorithmID,
		Flags:       0,
		MetadataLen: uint32(len(metadata)),
		DataLen:     uint64(len(data)),
		Metadata:    metadata,
		Data:        data,
	}
	copy(format.Magic, MagicBytes)
	return format
}

// Parse parses a PQC Binary Format from bytes
func Parse(data []byte) (*PqcBinaryFormat, error) {
	if len(data) < 52 { // Minimum size: 4 + 1 + 2 + 1 + 4 + 8 + 32 = 52 bytes
		return nil, ErrBufferTooSmall
	}

	format := &PqcBinaryFormat{}
	offset := 0

	// Parse magic bytes
	format.Magic = data[offset : offset+4]
	if !bytes.Equal(format.Magic, MagicBytes) {
		return nil, ErrInvalidMagic
	}
	offset += 4

	// Parse version
	format.Version = data[offset]
	if format.Version != Version1 {
		return nil, ErrInvalidVersion
	}
	offset += 1

	// Parse algorithm ID (little-endian)
	format.AlgorithmID = binary.LittleEndian.Uint16(data[offset : offset+2])
	offset += 2

	// Parse flags
	format.Flags = data[offset]
	offset += 1

	// Parse metadata length (little-endian)
	format.MetadataLen = binary.LittleEndian.Uint32(data[offset : offset+4])
	offset += 4

	// Parse metadata
	if int(format.MetadataLen) > len(data)-offset-32 {
		return nil, ErrInvalidLength
	}
	if format.MetadataLen > 0 {
		format.Metadata = data[offset : offset+int(format.MetadataLen)]
		offset += int(format.MetadataLen)
	}

	// Parse data length (little-endian)
	format.DataLen = binary.LittleEndian.Uint64(data[offset : offset+8])
	offset += 8

	// Validate total length
	totalLen := 52 + int(format.MetadataLen) + int(format.DataLen)
	if len(data) != totalLen {
		return nil, ErrInvalidLength
	}

	// Parse data (metadata was already consumed before the data length field)
	if format.DataLen > 0 {
		format.Data = data[offset : offset+int(format.DataLen)]
		offset += int(format.DataLen)
	}

	// Parse checksum
	copy(format.Checksum[:], data[offset:offset+32])
	offset += 32

	// Verify checksum
	if !format.VerifyChecksum() {
		return nil, ErrInvalidChecksum
	}

	return format, nil
}

// Serialize serializes the format to bytes with checksum
func (f *PqcBinaryFormat) Serialize() ([]byte, error) {
	// Calculate total size
	totalSize := 52 + len(f.Metadata) + len(f.Data)
	buf := make([]byte, totalSize)
	offset := 0

	// Write magic bytes
	copy(buf[offset:], MagicBytes)
	offset += 4

	// Write version
	buf[offset] = f.Version
	offset += 1

	// Write algorithm ID (little-endian)
	binary.LittleEndian.PutUint16(buf[offset:], f.AlgorithmID)
	offset += 2

	// Write flags
	buf[offset] = f.Flags
	offset += 1

	// Write metadata length (little-endian)
	binary.LittleEndian.PutUint32(buf[offset:], uint32(len(f.Metadata)))
	offset += 4

	// Write metadata
	if len(f.Metadata) > 0 {
		copy(buf[offset:], f.Metadata)
		offset += len(f.Metadata)
	}

	// Write data length (little-endian)
	binary.LittleEndian.PutUint64(buf[offset:], uint64(len(f.Data)))
	offset += 8

	// Write data
	if len(f.Data) > 0 {
		copy(buf[offset:], f.Data)
		offset += len(f.Data)
	}

	// Calculate checksum (everything except the checksum field itself)
	checksumData := buf[:offset]
	checksum := sha256.Sum256(checksumData)
	copy(buf[offset:], checksum[:])

	// Store checksum in struct
	f.Checksum = checksum

	return buf, nil
}

// VerifyChecksum verifies the SHA-256 checksum
func (f *PqcBinaryFormat) VerifyChecksum() bool {
	// Reconstruct the data that was checksummed
	buf := new(bytes.Buffer)

	// Write all fields except checksum, in spec order (little-endian)
	buf.Write(f.Magic)
	buf.WriteByte(f.Version)

	algID := make([]byte, 2)
	binary.LittleEndian.PutUint16(algID, f.AlgorithmID)
	buf.Write(algID)

	buf.WriteByte(f.Flags)

	metaLen := make([]byte, 4)
	binary.LittleEndian.PutUint32(metaLen, uint32(len(f.Metadata)))
	buf.Write(metaLen)

	buf.Write(f.Metadata)

	dataLen := make([]byte, 8)
	binary.LittleEndian.PutUint64(dataLen, uint64(len(f.Data)))
	buf.Write(dataLen)

	buf.Write(f.Data)

	// Calculate checksum
	calculated := sha256.Sum256(buf.Bytes())

	// Constant-time comparison
	return bytes.Equal(calculated[:], f.Checksum[:])
}

// AlgorithmName returns the human-readable algorithm name
func (f *PqcBinaryFormat) AlgorithmName() string {
	if name, ok := algorithmNames[f.AlgorithmID]; ok {
		return name
	}
	return fmt.Sprintf("Unknown-0x%04X", f.AlgorithmID)
}

// IsQuantumResistant returns true if the algorithm is quantum-resistant
func (f *PqcBinaryFormat) IsQuantumResistant() bool {
	// Classical algorithms are not quantum-resistant
	if f.AlgorithmID == AlgorithmClassical || f.AlgorithmID == AlgorithmPasswordClassical {
		return false
	}
	// All other algorithms in the spec are quantum-resistant or hybrid
	return true
}

// Size returns the total size of the serialized format in bytes
func (f *PqcBinaryFormat) Size() int {
	return 52 + len(f.Metadata) + len(f.Data)
}

// String returns a string representation of the format
func (f *PqcBinaryFormat) String() string {
	return fmt.Sprintf("PqcBinaryFormat{Version: %d, Algorithm: %s (0x%04X), MetadataLen: %d, DataLen: %d}",
		f.Version, f.AlgorithmName(), f.AlgorithmID, len(f.Metadata), len(f.Data))
}