{"id":29925408,"url":"https://github.com/jpkusumi/greenfieldpqc","last_synced_at":"2026-02-06T11:29:22.563Z","repository":{"id":305384113,"uuid":"1019145102","full_name":"JPKusumi/GreenfieldPQC","owner":"JPKusumi","description":"Side step quantum threats. Level up your encryption. Future proof your code. This cryptographic library for .NET development includes NIST standardized cryptographic primitives and Kusumi-512, a novel stream symmetric cipher with a 512 bit key size for enhanced quantum resistance.","archived":false,"fork":false,"pushed_at":"2026-02-05T00:32:49.000Z","size":2062,"stargazers_count":3,"open_issues_count":0,"forks_count":1,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-02-05T00:55:41.009Z","etag":null,"topics":["cipher","code","cryptography","csharp","dotnet","encryption","future-proof","green-field","kusumi","library","package","post-quantum","pqc","quantum-resistant","quantum-safe","streaming","symmetric"],"latest_commit_sha":null,"homepage":"https://www.nuget.org/packages/GreenfieldPQC","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/JPKusumi.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-07-13T20:49:59.000Z","updated_at":"2026-02-05T00:32:53.000Z","dependencies_parsed_at":"2025-07-19T21:46:52.109Z","dependency_job_id":"3f22cfde-bdaa-4143-8900-c9a1cf6682ff","html_url":"https://github.com/JPKusumi/GreenfieldPQC","commit_stats":null,"previous_names":["jpkusumi/greenfieldpqc"],"tags_count":3,"template":false,"template_full_name":null,"purl":"pkg:github/JPKusumi/GreenfieldPQC","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JPKusumi%2FGreenfieldPQC","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JPKusumi%2FGreenfieldPQC/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JPKusumi%2FGreenfieldPQC/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JPKusumi%2FGreenfieldPQC/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/JPKusumi","download_url":"https://codeload.github.com/JPKusumi/GreenfieldPQC/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JPKusumi%2FGreenfieldPQC/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29159590,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-06T07:18:23.844Z","status":"ssl_error","status_checked_at":"2026-02-06T07:13:32.659Z","response_time":59,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cipher","code","cryptography","csharp","dotnet","encryption","future-proof","green-field","kusumi","library","package","post-quantum","pqc","quantum-resistant","quantum-safe","streaming","symmetric"],"created_at":"2025-08-02T11:37:00.874Z","updated_at":"2026-02-06T11:29:22.554Z","avatar_url":"https://github.com/JPKusumi.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"﻿| **[JPKusumi.com](https://jpkusumi.com) presents—** |\n|:-----------------------:|\n\n# GreenfieldPQC\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![NuGet Version](https://img.shields.io/nuget/v/GreenfieldPQC.svg)](https://www.nuget.org/packages/GreenfieldPQC/)  \nNuGet URL - https://www.nuget.org/packages/GreenfieldPQC  \nGitHub URL - https://github.com/JPKusumi/GreenfieldPQC  \n\nv1.1 extends quantum safety to JWTs - JSON Web Tokens. New helpers support JSON Web Signature (JWS) and JSON Web Encryption (JWE) with post-quantum algorithms. Yes, you can easily implement quantum-safe encrypted JWTs with GreenfieldPQC. See sections below, and a related blog post at JPKusumi.com.\n\n## Overview: Quantum Resistance Available Now  \n\nThe world faces the threat of quantum computers with the ability to break current (or old normal) cryptographic systems. To use Post Quantum Cryptography (PQC) will become the new normal. GreenfieldPQC is a .NET library that provides post-quantum cryptographic primitives to secure applications against these future threats. It offers an opinionated subset drawn from available implementations of key encapsulation mechanisms (KEMs), symmetric encryption, digital signatures, and hashing algorithms designed to be resistant to quantum attacks. The goal is to sidestep threats like Grover's algorithm for symmetric ciphers and Shor's for asymmetric ones.  \n\nThe subset covers the bases to enable quantum safety from end-to-end. Combine components, e.g., use Kyber for key exchange, Kusumi512 for bulk encryption, Dilithium for signing, and SHA512 for hashing. Use CryptoFactory.GenerateKey and GenerateNonce for secure random generation. Note that Kusumi512 comes in two varieties (Kusumi512 and Kusumi512Poly1305, a MAC version to enable AEAD operation), and that two versions of hashing are included (SHA256 and SHA512).  \n\nWhere the old normal was to use 256-bit keys and hashes, the new normal is to use 512-bit keys and hashes. This library provides a simple way to implement this new normal in .NET applications.  \n\nHence, a key feature of the new normal is that devs and storage systems must accomodate larger data sizes for keys and hashes. While 256 bits is 32 bytes, 512 bits is 64 bytes.  \n\nPackage note. This package is best for green field development — new projects, not legacy systems. Corporate, legacy systems need more than code; database schemas may need to change, and they may choose to re-encrypt vulnerable data. Conversely, if you are on a green field project, then you can drop in this package and go. The name, GreenfieldPQC, indicates that brown field redevelopment on legacy systems is out of scope for this package.  \n\nUpon review, Grok has said, \"This library is suitable for greenfield projects transitioning to the 'new normal' of quantum-safe cryptography.\"  \n\nFor more commentary from Grok, see REVIEW.md and BENCHMARKS.md in the repo root. **Warning**: Not formally audited; use in production at your own risk.  \n\n\n**More Features:**\n- **API Simplicity**: Factory pattern for instantiation; synchronous and asynchronous methods.  \n- **Benchmarked**: Kusumi512 beats Threefish-512 in speed/memory.  \n- **NuGet Package**: Easy integration with .NET 8+; no additional configuration needed.\n- **Quantum Safe JWTs**: JWS (Dilithium) and JWE (Kyber + Kusumi512) support.\n- **Transitive Dependency**: Bundles oqs.dll for multi-platform (win/linux/osx, x64/arm64). Note that win-arm64 is not a supported platform.  \n\n## Installation  \n\nVia NuGet:\n```\ndotnet add package GreenfieldPQC --version 1.1.2\n```\nSupports .NET 8+ and .NET 10. Bundles oqs.dll, a native dll, as a transitive dependency for supported platforms (win/linux/osx, x64/arm64). No additional configuration needed. Note that win-arm64 is not a supported platform.  \n\n## Quick Start\n```csharp\nusing GreenfieldPQC.Cryptography;\nusing System.Text;\n\nvar key = CryptoFactory.GenerateKey(CipherAlgorithm.Kusumi512);\nvar nonce = CryptoFactory.GenerateNonce(CipherAlgorithm.Kusumi512);\nISymmetricCipher cipher = CryptoFactory.CreateKusumi512(key, nonce); // Use interface for mocking\n\nstring plaintext = \"Hello, PQC!\";\nbyte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);\nbyte[] ciphertext = cipher.Encrypt(plaintextBytes);\nbyte[] decrypted = cipher.Decrypt(ciphertext);\n\nConsole.WriteLine(Encoding.UTF8.GetString(decrypted)); // \"Hello, PQC!\"\n```\n\n## Old Normal vs. New Normal  \n\nGreenfieldPQC enables \"future-proof\" encryption upgrades with minimal disruption, targeting quantum-resistant primitives for new (\"greenfield\") projects. Key benefits:  \n\n- **Quantum Resistance**: Kusumi512 offers 512-bit keys for symmetric encryption (effective 256-bit security post-Grover), outperforming Threefish-512 in benchmarks (7-9% faster execution, 40-58% less memory). Kyber and Dilithium are NIST-standardized for asymmetric needs.  \n- **Efficiency**: Optimized for .NET (C#), with low overhead—ideal for high-throughput apps like cloud services, IoT, or data pipelines.  \n- **Ease of Adoption**: NuGet integration; bundles oqs.dll for native PQC support (via P/Invoke for Kyber and Dilithium); requires .NET 8+.  \n- **Risk Mitigation**: Addresses media \"drumbeat\" on quantum threats; supports compliance (e.g., FIPS-like standards pending NIST finalization).  \n- **Benchmarks Summary**: From BENCHMARKS.md (in repo root), Kusumi512 excels in speed and RAM vs. alternatives, making it a practical \"new normal\" for 512-bit symmetric crypto.  \n\nEvaluate via a proof-of-concept: Install the package and test Kusumi512 for your workload. For ROI, consider avoided breaches in a post-quantum world—contact NIST or consult [xAI's resources](https://x.ai) for broader AI/quantum insights.  \n\nResources:\n- **Cryptography Basics**: [Wikipedia: Cryptography](https://en.wikipedia.org/wiki/Cryptography) — A high-level intro to encryption concepts.  \n- **Symmetric vs. Asymmetric Encryption**: [Khan Academy: Cryptography](https://www.khanacademy.org/computing/computer-science/cryptography) — Free videos explaining keys, ciphers, and hashes.  \n- **Quantum Threats**: [NIST Post-Quantum Cryptography](https://csrc.nist.gov/projects/post-quantum-cryptography) — Explains why quantum computers could break current encryption and the shift to PQC.  \n- **Quantum Computing Primer**: [IBM: What is Quantum Computing?](https://www.ibm.com/topics/quantum-computing) — Simple explanation of the \"quantum threat\" in news stories.  \n- **Why Larger Keys Matter**: [Cloudflare: Post-Quantum Cryptography](https://blog.cloudflare.com/post-quantum-cryptography/) — Real-world context on urgency without deep math.  \n\n## End-to-End Example  \n\nAlice and Bob are old friends who love sharing secrets, but in this digital age, they're paranoid about eavesdroppers—like quantum computers that could one day crack traditional key exchanges. Alice wants to send Bob some confidential photos from their latest adventure, but she needs a super-secure way to encrypt them using her new favorite symmetric cipher, Kusumi512, which requires a 512-bit shared key. The problem? They don't have a secure way to agree on that key over the internet without someone intercepting it.\n\nEnter Kyber, the post-quantum hero of key encapsulation mechanisms (KEMs). It's like a magical lockbox that's safe even from future quantum villains. Here's how their story unfolds:\n\n1. **Alice Prepares the Lockbox**: Alice generates a Kyber key pair on her computer—a public key (like an open lock anyone can see) and a private key (the secret code to unlock it). She sends the public key to Bob over the open internet. No worries if someone like Eve intercepts it; the public key is useless without the private one.\n\n2. **Bob Seals the Secret**: Bob receives Alice's public key and decides on a random shared secret (this will become their 512-bit Kusumi512 key). Using Kyber, he \"encapsulates\" this secret inside a ciphertext—a digital envelope sealed with Alice's public key. Only Alice can open it. Bob sends this ciphertext back to Alice.\n\n3. **Alice Unlocks the Secret**: Alice uses her private key to \"decapsulate\" the ciphertext, revealing the exact shared secret Bob chose. Now both Alice and Bob have the same 512-bit key, and Eve (even with a quantum computer) can't figure it out because Kyber's lattice-based math is too tricky for Shor's algorithm.\n\n4. **Symmetric Bliss with Kusumi512**: With the shared key in hand, Alice encrypts her photos using Kusumi512 in a mode like CTR (counter mode) for fast streaming. For extra security, she adds authentication with Poly1305, creating an AEAD (Authenticated Encryption with Associated Data) tag to ensure the data isn't tampered with. She sends the encrypted photos and tag to Bob.\n\n5. **Bob Decrypts and Enjoys**: Bob uses the same shared Kusumi512 key to decrypt the photos and verify the Poly1305 tag. If everything checks out, he sees the images perfectly. If not, he knows something's fishy.\n\nIn the end, Alice and Bob's communication is quantum-safe from the start (thanks to Kyber) and blazing fast for the bulk data (thanks to Kusumi512's efficiency). This hybrid approach—post-quantum key exchange plus symmetric encryption—is the gold standard for future-proofing, enabled by this GreenfieldPQC toolkit for .NET developers. If quantum threats escalate, they're ready!\n\n### How to Implement the End-to-End Example  \n\nTo implement the Alice and Bob scenario in C#, we'll use Kyber for quantum-safe key exchange, SHA512 to derive a 512-bit symmetric key from Kyber's 256-bit shared secret, and Kusumi512Poly1305 for authenticated bulk encryption (AEAD mode). This ensures confidentiality, integrity, and authenticity.  \n\nAssume Alice and Bob have a way to exchange data (e.g., via files or a network channel—out of scope here). We'll use level 1024 for Kyber (high security) and focus on synchronous methods for simplicity. Use using statements for disposal.  \n\n#### Alice's Code (Generate Key Pair, Send Public Key, Receive Ciphertext, Derive Key, Encrypt Data)\n```csharp\nusing GreenfieldPQC.Cryptography;\nusing System.IO;\nusing System.Security.Cryptography;\nusing System.Text;\n\n// Step 1: Alice generates Kyber key pair\nvar kem = CryptoFactory.CreateKyber(KyberSecurityLevel.ML_KEM_1024);  // Level 5 for highest security\nvar (alicePublicKey, alicePrivateKey) = kem.GenerateKeyPair();\n\n// Send alicePublicKey to Bob (e.g., save to file)\nFile.WriteAllBytes(\"alice_public_key.bin\", alicePublicKey);\n\n// Step 3: Alice receives ciphertext from Bob (e.g., read from file)\nbyte[] bobCiphertext = File.ReadAllBytes(\"bob_ciphertext.bin\");\n\n// Decapsulate to get 256-bit shared secret\nbyte[] sharedSecret256 = kem.Decapsulate(bobCiphertext, alicePrivateKey);\n\n// Derive 512-bit key via SHA512 hash\nbyte[] kusumiKey = CryptoFactory.ComputeSHA512(sharedSecret256);  // 64 bytes\n\n// Generate nonce for symmetric encryption\nbyte[] nonce = CryptoFactory.GenerateNonce(CipherAlgorithm.Kusumi512Poly1305);\n\n// Create AEAD cipher\nISymmetricCipher cipher = CryptoFactory.CreateKusumi512Poly1305(kusumiKey, nonce);\n\n// Encrypt data (e.g., a message or file stream)\nstring plaintext = \"Confidential photos data\";  // Or read from file/stream\nbyte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);\nbyte[] ciphertextWithTag = cipher.Encrypt(plaintextBytes);\n\n// Send ciphertextWithTag to Bob (e.g., save to file)\nFile.WriteAllBytes(\"encrypted_data.bin\", ciphertextWithTag);\n```  \n\n#### Bob's Code (Receive Public Key, Encapsulate, Send Ciphertext, Derive Key, Decrypt Data)\n```csharp\nusing GreenfieldPQC.Cryptography;\nusing System.IO;\nusing System.Security.Cryptography;\nusing System.Text;\n\n// Step 2: Bob receives Alice's public key (e.g., read from file)\nbyte[] alicePublicKey = File.ReadAllBytes(\"alice_public_key.bin\");\n\n// Create Kyber instance (same level as Alice)\nvar kem = CryptoFactory.CreateKyber(KyberSecurityLevel.ML_KEM_1024);  // Level 5 for highest security\n\n// Encapsulate to get 256-bit shared secret and ciphertext\nvar (sharedSecret256, ciphertext) = kem.Encapsulate(alicePublicKey);\n\n// Send ciphertext to Alice (e.g., save to file)\nFile.WriteAllBytes(\"bob_ciphertext.bin\", ciphertext);\n\n// Derive 512-bit key via SHA512 hash (same as Alice)\nbyte[] kusumiKey = CryptoFactory.ComputeSHA512(sharedSecret256);  // 64 bytes\n\n// Generate same nonce (or receive from Alice; here assuming shared or generated identically)\nbyte[] nonce = CryptoFactory.GenerateNonce(CipherAlgorithm.Kusumi512Poly1305);\n\n// Create AEAD cipher\nISymmetricCipher cipher = CryptoFactory.CreateKusumi512Poly1305(kusumiKey, nonce);\n\n// Step 5: Bob receives encrypted data (e.g., read from file)\nbyte[] ciphertextWithTag = File.ReadAllBytes(\"encrypted_data.bin\");\n\n// Decrypt and verify tag (throws if tampered)\nbyte[] decryptedBytes = cipher.Decrypt(ciphertextWithTag);\nstring decrypted = Encoding.UTF8.GetString(decryptedBytes);\n\nConsole.WriteLine(decrypted);  // \"Confidential photos data\"\n```\n**Notes:**  \n- Use secure channels for exchanges if possible, but Kyber ensures the shared secret is safe even over insecure ones.  \n- For files/streams: Replace byte arrays with EncryptStreamAsync/DecryptStreamAsync for large data like photos.  \n- Verify equality of shared secrets with CryptographicOperations.FixedTimeEquals in tests.  \n- Rotate nonces/keys per session; include timestamps in data for replay protection.  \n- Error handling: Wrap in try-catch for exceptions like invalid tags.  \n\n### Another Usage Example: Stream Encryption  \n```csharp\nusing var input = File.OpenRead(\"file.dat\");\nusing var output = File.Create(\"enc.dat\");\nISymmetricCipher cipher = CryptoFactory.CreateKusumi512(key, nonce);\nvar progress = new Progress\u003cdouble\u003e(p =\u003e Console.WriteLine($\"{p:P}\"));\nFunc\u003clong, Task\u003cbyte[]\u003e\u003e nonceGen = async bytes =\u003e CryptoFactory.GenerateNonce(CipherAlgorithm.Kusumi512);\nawait cipher.EncryptStreamAsync(input, output, progress: progress, nonceGenerator: nonceGen);\n```\n\n## Quantum Safe JSON Web Signature (JWS)\nJWS provides signed JWTs (three-segment format: header.payload.signature) for integrity and authenticity using Dilithium.\n\n### In Theory\nCompact tokens with post-quantum signatures, suitable for auth flows like OAuth.\n\n### In Practice\nAPI Highlights (Dilithium levels: 2, 3, 5):\n- CryptoFactory.CreateJwsProvider(level): Returns IJwsProvider.\n- CreateJws(payload, privateKey): Returns JWS string.\n- VerifyJws(jwsToken, publicKey): Returns payload if valid, throws otherwise.\n\nRound-Trip Example:\n```csharp\nvar jwsProvider = CryptoFactory.CreateJwsProvider(DilithiumSecurityLevel.ML_DSA_65);\nvar (pubKey, privKey) = CryptoFactory.CreateDilithium(DilithiumSecurityLevel.ML_DSA_65).GenerateKeyPair();\nvar payload = new { sub = \"user123\", exp = DateTimeOffset.UtcNow.AddHours(1).ToUnixTimeSeconds() };\nstring jwsToken = jwsProvider.CreateJws(payload, privKey);\nvar verified = jwsProvider.VerifyJws(jwsToken, pubKey) as dynamic;\nAssert.Equal(payload.sub, verified.sub);\n```\n\nBest Practices: Use short expirations; validate claims post-verification.\n\n## Quantum Safe JSON Web Encryption (JWE)\nJWE provides encrypted JWTs (five-segment format: header.encrypted_key.iv.ciphertext.tag) for confidentiality using Kyber and Kusumi512.\n\n### In Theory\nHybrid encryption: Kyber for key wrapping, Kusumi512 for payload.\n\n### In Practice\nAPI Highlights (Kyber levels: 1, 3, 5; Kusumi algorithm: Kusumi512 plain or Kusumi512Poly1305 AEAD):\n- CryptoFactory.CreateJweProvider(kyberLevel, kusumiAlgorithm): Returns IJweProvider.\n- CreateJwe(payload, publicKey): Returns JWE string.\n- DecryptJwe(jweToken, privateKey): Returns raw decrypted payload as string (JSON); deserialize as needed if valid, throws otherwise.\n\nRound-Trip Example:\n```csharp\nvar jweProvider = CryptoFactory.CreateJweProvider(KyberSecurityLevel.ML_KEM_768, CryptoFactory.CipherAlgorithm.Kusumi512Poly1305);  // Level 3 Kyber, AEAD Kusumi\nvar (pubKey, privKey) = CryptoFactory.CreateKyber(KyberSecurityLevel.ML_KEM_768).GenerateKeyPair();\nvar payload = new { sub = \"user123\", secret = \"confidential\" };\nstring jweToken = jweProvider.CreateJwe(payload, pubKey);\nstring decryptedJson = jweProvider.DecryptJwe(jweToken, privKey);\ndynamic decrypted = JsonSerializer.Deserialize\u003cdynamic\u003e(decryptedJson);\nAssert.Equal(payload.secret, decrypted.secret);\n```\n\nBest Practices: Use HTTPS; rotate keys; nest JWS in JWE for signed-encrypted tokens.\n\n## Kyber\n\nKyber is a post-quantum key encapsulation mechanism (KEM) standardized by NIST as ML-KEM (Module-Lattice-Based Key-Encapsulation Mechanism) under FIPS 203 in August 2024. It provides secure key exchange resistant to quantum attacks. In the GreenfieldPQC API, it is referred to as Kyber, with implementation details relying on P/Invoke to a native DLL from liboqs as a transitive dependency.\n\n### In Theory\n\nA key encapsulation mechanism (KEM) is a cryptographic primitive that enables two parties to securely establish a shared secret key over an insecure channel without transmitting the key itself. Unlike traditional key exchange methods like Diffie-Hellman, which are vulnerable to quantum computers via Shor's algorithm, Kyber uses lattice-based problems that remain hard for quantum adversaries.\n\nIn practice, one party (the sender) uses the recipient's public key to generate a shared secret and a ciphertext (encapsulated key). The recipient then uses their private key to decapsulate the ciphertext and recover the same shared secret. The output is typically a 32-byte (256-bit) shared secret, which can be hashed (e.g., with SHA512) to derive longer symmetric keys. Key sizes vary by security level: for level 1 (ML-KEM-512), public keys are 800 bytes, private keys 1632 bytes, and ciphertexts 768 bytes; for level 3 (ML-KEM-768), they are 1184, 2400, and 1088 bytes; for level 5 (ML-KEM-1024), 1568, 3168, and 1568 bytes.\n\nCommon use cases include establishing session keys for secure communication protocols, replacing classical methods like ECDH in TLS handshakes, or bootstrapping symmetric encryption in hybrid cryptosystems. This ensures forward secrecy and quantum resistance for applications like secure messaging or VPNs.\n\n| Security Level | Public Key (pk) | Private Key (sk) | Ciphertext (ct) |\n| -------------- | --------------- | ---------------- | --------------- |\n| 1 (ML-KEM-512) | 800 bytes | 1632 bytes | 768 bytes |\n| 3 (ML-KEM-768) | 1184 bytes | 2400 bytes | 1088 bytes |\n| 5 (ML-KEM-1024) | 1568 bytes | 3168 bytes | 1568 bytes |\n\n### In Practice\n\n**API Highlights** (Security levels: 1, 3, 5 via enum or direct parameters 512, 768, 1024):\n\n- CryptoFactory.CreateKyber(KyberSecurityLevel level): Returns IKeyEncapsulationMechanism (enum: ML_KEM_512 = 1, ML_KEM_768 = 3, ML_KEM_1024 = 5).\n- CryptoFactory.CreateKyber(int parameter): Returns IKeyEncapsulationMechanism (parameter: 512, 768, 1024 for backward compatibility).\n- IKeyEncapsulationMechanism.GenerateKeyPair(): Returns (publicKey, privateKey).\n- IKeyEncapsulationMechanism.Encapsulate(byte[] publicKey): Returns (sharedSecret, ciphertext).\n- IKeyEncapsulationMechanism.Decapsulate(byte[] ciphertext, byte[] privateKey): Returns sharedSecret.\n\n**Example** (using enum for level 3 / ML-KEM-768):\n```csharp\nusing GreenfieldPQC.Cryptography;\n\nvar kem = CryptoFactory.CreateKyber(KyberSecurityLevel.ML_KEM_768);\nvar (pk, sk) = kem.GenerateKeyPair();\nvar (ssSender, ct) = kem.Encapsulate(pk);\nbyte[] ssReceiver = kem.Decapsulate(ct, sk);  // ssSender matches ssReceiver (use CryptographicOperations.FixedTimeEquals to verify)\n```\n\nFor use with Kyber, it is good to be aware of this enum:\n```csharp\npublic enum KyberSecurityLevel\n{\n    ML_KEM_512 = 1,\n    ML_KEM_768 = 3,\n    ML_KEM_1024 = 5\n}\n```\n**Best Practices**: Use Kyber to replace quantum-vulnerable classical methods like ECDH for key exchange. Store private keys securely, e.g., in hardware security modules. Prefer the enum overload for new code to align with NIST levels.\n\n## Dilithium\n\nDilithium is a post-quantum digital signature algorithm standardized by NIST as ML-DSA (Module-Lattice-Based Digital Signature Algorithm) under FIPS 204 in August 2024. It ensures message authenticity and integrity against quantum threats. In the GreenfieldPQC API, it is referred to as Dilithium, with implementation via P/Invoke to a native DLL from liboqs as a transitive dependency.\n\n### In Theory\n\nA digital signature algorithm allows a signer to prove the authenticity and integrity of a message using a private key, while anyone with the corresponding public key can verify it. Dilithium, based on lattice problems, resists quantum attacks like those that break RSA or ECDSA with Shor's algorithm.\n\nIn practice, the signer generates a key pair, signs a message (or its hash) with the private key to produce a signature, and the verifier checks the signature against the message and public key. Signatures are fixed-size outputs varying by security level: for level 2 (ML-DSA-44), public keys are 1312 bytes, private keys 2560 bytes, and signatures 2420 bytes; for 3 (ML-DSA-65), 1952, 4032, and 3309 bytes; for 5 (ML-DSA-87), 2592, 4896, and 4627 bytes.\n\nUse cases include signing software updates, certificates in PKI, or documents for non-repudiation, ensuring long-term security in scenarios like blockchain transactions or legal electronic signatures where quantum threats are a concern.\n\n| Security Level | Public Key (pk) | Private Key (sk) | Signature (sig) |\n|----------------|-----------------|------------------|-----------------|\n| 2 (ML-DSA-44) | 1312 bytes     | 2560 bytes      | 2420 bytes     |\n| 3 (ML-DSA-65) | 1952 bytes     | 4032 bytes      | 3309 bytes     |\n| 5 (ML-DSA-87) | 2592 bytes     | 4896 bytes      | 4627 bytes     |\n\n### In Practice\n\n**API Highlights** (Security levels: 2, 3, 5 via enum or direct levels):\n- CryptoFactory.CreateDilithium(DilithiumSecurityLevel level): Returns ISigner (enum: ML_DSA_44 = 2, ML_DSA_65 = 3, ML_DSA_87 = 5).\n- CryptoFactory.CreateDilithium(int level): Returns ISigner (level: 2, 3, 5 for backward compatibility).\n- ISigner.GenerateKeyPair(): Returns (publicKey, privateKey).\n- ISigner.Sign(byte[] message, byte[] privateKey): Returns signature.\n- ISigner.Verify(byte[] message, byte[] signature, byte[] publicKey): Returns bool.\n- ISigner.GetSignatureLength(): Expected sig size.\n\n**Example** (using enum for level 3 / ML-DSA-65):\n```csharp\nusing GreenfieldPQC.Cryptography;\n\nvar signer = CryptoFactory.CreateDilithium(DilithiumSecurityLevel.ML_DSA_65);\nvar (pubKey, privKey) = signer.GenerateKeyPair();\nbyte[] message = Encoding.UTF8.GetBytes(\"Sign me\");\nbyte[] sig = signer.Sign(message, privKey);\nbool valid = signer.Verify(message, sig, pubKey);  // true\n```\n\nFor use with Dilithium, it is good to be aware of this enum:\n```csharp\npublic enum DilithiumSecurityLevel\n{\n    ML_DSA_44 = 2,\n    ML_DSA_65 = 3,\n    ML_DSA_87 = 5\n}\n```\n**Best Practices**: Hash messages first if large; use for certificates or code signing. Prefer the enum overload for new code to align with NIST levels.\n\n## Kusumi512\n\nKusumi512 is a post-quantum symmetric encryption algorithm using a 512-bit key, designed for efficiency and resistance to quantum attacks like Grover's algorithm. It operates as a stream cipher with a 64-bit block counter, suitable for encrypting large or streaming data.\n\n### In Theory\n\nSymmetric encryption uses the same key for both encryption and decryption, providing confidentiality by transforming plaintext into ciphertext that appears random without the key. Kusumi512, as a stream cipher, generates a keystream from the key and nonce, XORing it with the data for encryption (and decryption, since XOR is reversible).\n\nIn practice, inputs include a 64-byte key, a 12-byte nonce, and plaintext of any length; outputs are ciphertext of matching length. The 64-bit counter prevents nonce reuse issues over long streams, avoiding resets needed with shorter counters (e.g., in 4K video streaming, a 32-bit counter might require daily resets).\n\nUse cases involve securing data at rest (e.g., file encryption) or in transit (e.g., streaming media), especially where high throughput is needed in quantum-safe environments like cloud storage or real-time communications.\n\n### In Practice\n\n**API Highlights**:\n- `CryptoFactory.CreateKusumi512(byte[] key, byte[] nonce)`: Creates an `ISymmetricCipher` instance (key: 64 bytes, nonce: 12 bytes).\n- `ISymmetricCipher.Encrypt(byte[] plaintext)`: Returns ciphertext (stream mode).\n- `ISymmetricCipher.Decrypt(byte[] ciphertext)`: Returns plaintext.\n- `ISymmetricCipher.EncryptInPlace(Span\u003cbyte\u003e data)`: In-place encryption for performance.\n- `ISymmetricCipher.DecryptInPlace(Span\u003cbyte\u003e data)`: Symmetric to above.\n- `ISymmetricCipher.EncryptStream(Stream input, Stream output, int bufferSize=4096, Func\u003clong, byte[]\u003e? nonceGenerator=null)`: Stream encryption.\n- `ISymmetricCipher.DecryptStream(Stream input, Stream output, int bufferSize=4096, Func\u003clong, byte[]\u003e? nonceGenerator=null)`: Stream decryption.\n- `ISymmetricCipher.EncryptAsync/DecryptAsync`: Task-wrapped with cancellation.\n- `ISymmetricCipher.EncryptInPlaceAsync/DecryptInPlaceAsync`: Memory\u003cbyte\u003e versions with cancellation.\n- `ISymmetricCipher.EncryptStreamAsync/DecryptStreamAsync`: With progress, cancellation, async nonceGen.\n\n**Example**:\n```csharp\nusing GreenfieldPQC.Cryptography;\nusing System.Security.Cryptography;\n\n// Generate key and nonce\nbyte[] key = CryptoFactory.GenerateKey(CipherAlgorithm.Kusumi512);\nbyte[] nonce = CryptoFactory.GenerateNonce(CipherAlgorithm.Kusumi512);\n\nISymmetricCipher cipher = CryptoFactory.CreateKusumi512(key, nonce);\nbyte[] plaintext = Encoding.UTF8.GetBytes(\"Hello, quantum-safe world!\");\nbyte[] ciphertext = cipher.Encrypt(plaintext);\nbyte[] decrypted = cipher.Decrypt(ciphertext);  // Matches plaintext\n```\n\n**Best Practices**: Use unique nonces per session; rotate keys frequently. For benchmarks, see repo's BENCHMARKS.md.\n\n## Kusumi512Poly1305\n\nKusumi512Poly1305 is an authenticated encryption with associated data (AEAD) scheme combining Kusumi512 for confidentiality with Poly1305 for integrity, using a 512-bit key for post-quantum security.\n\n### In Theory\n\nAEAD primitives provide both encryption (confidentiality) and authentication (integrity and authenticity), detecting tampering or forgery. Kusumi512Poly1305 encrypts data while appending a MAC tag computed over the ciphertext.\n\nIn practice, inputs are a 64-byte key, 12-byte nonce, and plaintext; outputs include ciphertext plus a 16-byte tag. Decryption verifies the tag before returning plaintext, throwing an exception on failure. This prevents attacks like chosen-ciphertext or replay.\n\nUse cases include secure messaging or file storage, where detecting modifications is crucial, such as in quantum-resistant protocols for IoT or financial transactions.\n\n### In Practice\n\n**API Highlights**:\n- `CryptoFactory.CreateKusumi512Poly1305(byte[] key, byte[] nonce)`: Creates an `ISymmetricCipher` instance (key: 64 bytes, nonce: 12 bytes).\n- `ISymmetricCipher.Encrypt(byte[] plaintext)`: Returns ciphertext + tag.\n- `ISymmetricCipher.Decrypt(byte[] ciphertextWithTag)`: Returns plaintext or throws on tamper.\n- Note that EncryptInPlace (and DecryptInPlace) are not supported in the Poly1305 version of Kusumi512.\n\n**Example**:\n```csharp\nusing GreenfieldPQC.Cryptography;\nusing System.Security.Cryptography;\n\nbyte[] key = CryptoFactory.GenerateKey(CipherAlgorithm.Kusumi512Poly1305);\nbyte[] nonce = CryptoFactory.GenerateNonce(CipherAlgorithm.Kusumi512Poly1305);\n\nISymmetricCipher cipher = CryptoFactory.CreateKusumi512Poly1305(key, nonce);\nbyte[] plaintext = Encoding.UTF8.GetBytes(\"Authenticated data\");\nbyte[] ciphertextWithTag = cipher.Encrypt(plaintext);\nbyte[] decrypted = cipher.Decrypt(ciphertextWithTag);  // Matches plaintext\n```\n\n**Best Practices**: Always verify integrity via the combined tag; include timestamps in data to prevent replays.\n\n## SHA256\n\nSHA256 is a cryptographic hash function from the SHA-2 family, producing a 256-bit digest. In GreenfieldPQC, it uses .NET's System.Security.Cryptography for compatibility, serving as a building block in hybrid post-quantum systems.\n\n### In Theory\n\nA hash function maps arbitrary input data to a fixed-size output (digest), ensuring that small changes in input produce vastly different outputs (avalanche effect). SHA256 is collision-resistant and preimage-resistant, though quantum computers reduce its effective security to about 128 bits via Grover's algorithm.\n\nIn practice, input is any byte array or stream; output is always 32 bytes. It's deterministic, so the same input always yields the same hash, enabling verification without storing originals.\n\nUse cases include integrity checks (e.g., file downloads), message digests for signing with Dilithium, or password storage (with salting), often in workflows needing faster hashing than SHA512.\n\n### In Practice\n\n**API Highlights**:\n- `CryptoFactory.CreateSHA256()`: Returns reusable SHA256 instance.\n- `CryptoFactory.ComputeSHA256(byte[] data)`: Static one-off hash.\n\n**Example**:\n```csharp\n// Instance (reusable, thread-safe for ComputeHash)\nusing var sha256 = CryptoFactory.CreateSHA256();\nbyte[] hash = sha256.ComputeHash(data);  // Or sha256.ComputeHash(stream)\n```\n\n## SHA512\n\nSHA512 is a cryptographic hash function from the SHA-2 family, producing a 512-bit digest. In GreenfieldPQC, it leverages .NET's System.Security.Cryptography, ideal for deriving longer keys in post-quantum contexts.\n\n### In Theory\n\nHash functions like SHA512 provide a one-way transformation of data into a fixed digest, supporting integrity, authentication, and key derivation. With a longer output, it offers about 256-bit effective security against quantum preimage attacks via Grover's algorithm.\n\nIn practice, input can be any data; output is 64 bytes. It's used to expand shorter secrets (e.g., Kyber's 32-byte shared secret) into symmetric keys.\n\nUse cases involve key derivation (e.g., hashing KEM outputs for Kusumi512), digital fingerprints for large files, or in HMAC for message authentication, ensuring robustness in quantum-hybrid cryptosystems.\n\n### In Practice\n\n**API Highlights**:\n- `CryptoFactory.CreateSHA512()`: Returns reusable SHA512 instance.\n- `CryptoFactory.ComputeSHA512(byte[] data)`: Static one-off hash.\n\n**Example**:\n```csharp\n// Instance (reusable, thread-safe for ComputeHash)\nusing var sha512 = CryptoFactory.CreateSHA512();\nbyte[] hash = sha512.ComputeHash(data);  // Or sha512.ComputeHash(stream)\n```\n\n## API Documentation\n\nNamespace: `GreenfieldPQC.Cryptography`\n\n### CryptoFactory\nStatic factory for keys, nonces, and instances.\n\n- **GenerateKey(CipherAlgorithm alg)**: Random key.\n  - `Kusumi512`/`Kusumi512Poly1305`: 64 bytes.\n  - `Kyber`/`Dilithium`: Algorithm-specific (use CreateKyber/CreateDilithium for instantiation).\n  - Example: `byte[] key = CryptoFactory.GenerateKey(CipherAlgorithm.Kusumi512);`\n- **GenerateNonce(CipherAlgorithm alg)**: Random nonce (12 bytes for Kusumi).\n  - Example: `byte[] nonce = CryptoFactory.GenerateNonce(CipherAlgorithm.Kusumi512);`\n- **CreateKusumi512(byte[] key, byte[] nonce)**: Kusumi512 instance.\n- **CreateKusumi512Poly1305(byte[] key, byte[] nonce)**: AEAD instance.\n- **CreateKyber(int level)**: Returns IKeyEncapsulationMechanism (level: 512, 768, 1024).\n- **CreateDilithium(int level)**: Returns ISigner (level: 2, 3, 5).\n- **CreateSHA256()**: Returns SHA256 instance.\n- **CreateSHA512()**: Returns SHA512 instance.\n- **CreateHash(HashAlgorithmType type)**: Returns IHashAlgorithm (type: SHA256, SHA512).\n- **ComputeSHA256(byte[] data)**: SHA-256 hash.\n- **ComputeSHA512(byte[] data)**: SHA-512 hash.\n  - Example: `byte[] hash = CryptoFactory.ComputeSHA512(data);`\n- **CreateJwsProvider(int dilithiumLevel = 3)**: Returns IJwsProvider for post-quantum signed JWTs (Dilithium levels: 2, 3, 5).\n- **CreateJweProvider(int kyberLevel = 3, CipherAlgorithm kusumiAlgorithm = CipherAlgorithm.Kusumi512)**: Returns IJweProvider for post-quantum encrypted JWTs (Kyber levels: 1, 3, 5; Kusumi: Kusumi512 or Kusumi512Poly1305).\n\nFor use with CryptoFactory, it is good to be aware of this enum:\n```csharp\npublic enum CipherAlgorithm\n{\n    Kusumi512,\n    Kusumi512Poly1305,\n    Kyber,\n    Dilithium,\n    SHA256,\n    SHA512\n}\n```\n\n### IKeyEncapsulationMechanism (for Kyber)\nInterface for key encapsulation operations (useful for mocking/testing).\n\n- **GenerateKeyPair()**: Returns (publicKey, privateKey) tuple.\n- **Encapsulate(byte[] publicKey)**: Returns (sharedSecret, ciphertext) tuple.\n- **Decapsulate(byte[] ciphertext, byte[] privateKey)**: Returns sharedSecret.\n\n### ISigner (for Dilithium)\nInterface for digital signing operations (useful for mocking/testing).\n\n- **GenerateKeyPair()**: Returns (publicKey, privateKey) tuple.\n- **Sign(byte[] message, byte[] privateKey)**: Returns signature.\n- **Verify(byte[] message, byte[] signature, byte[] publicKey)**: Returns bool indicating validity.\n- **GetSignatureLength()**: Returns expected signature size in bytes.\n\n### ISymmetricCipher (for Kusumi512/Kusumi512Poly1305)\nInterface for symmetric ops (useful for mocking/testing).\n\n- **AlgorithmName**: String property (e.g., \"Kusumi512\").\n- **Encrypt(byte[] plaintext)**: Returns ciphertext (with tag for AEAD).\n- **Decrypt(byte[] ciphertext)**: Returns plaintext (verifies tag for AEAD).\n- **EncryptAsync/DecryptAsync**: Task-wrapped with cancellation.\n- **EncryptInPlace(Span\u003cbyte\u003e io)**: In-place (not for AEAD).\n- **DecryptInPlace(Span\u003cbyte\u003e io)**: Symmetric to above.\n- **EncryptInPlaceAsync/DecryptInPlaceAsync**: Memory\u003cbyte\u003e versions with cancellation.\n- **EncryptStream(Stream in, Stream out, int buf=4096, Func\u003clong, byte[]\u003e? nonceGen=null)**: Stream encryption.\n- **DecryptStream**: Stream decryption.\n- **EncryptStreamAsync/DecryptStreamAsync**: With progress, cancellation, async nonceGen.\n\nFor AEAD: Ciphertext appends 128-bit tag; decryption throws on invalid.\n\n### IHashAlgorithm (for SHA256/SHA512)\nInterface for hash operations (useful for mocking/testing).\n\n- **ComputeHash(byte[] data)**: Returns hash digest for byte array input.\n- **ComputeHash(Stream stream)**: Returns hash digest for stream input.\n\n### IJwsProvider (for JWS)\nInterface for JSON Web Signature operations (useful for mocking/testing).\n\n- **CreateJws(object payload, byte[] privateKey)**: Returns compact JWS string.\n- **VerifyJws(string jwsToken, byte[] publicKey)**: Returns deserialized payload object if valid; throws otherwise.\n\n### IJweProvider (for JWE)\nInterface for JSON Web Encryption operations (useful for mocking/testing).\n\n- **CreateJwe(object payload, byte[] publicKey)**: Returns compact JWE string.\n- **DecryptJwe(string jweToken, byte[] privateKey)**: Returns raw decrypted payload string (JSON) if valid; throws otherwise.\n\n\n## Resources and Community\nFor more information, blog posts, and updates on this and other JP Kusumi creations, visit [JPKusumi.com](https://jpkusumi.com). Recent blog posts include:\n- Key and nonce management best practices.\n- Handling cryptographic metadata securely.\n- Quantum-safe JWTs with GreenfieldPQC.\n\nJPKusumi.com aims to be a resource for developers. There is also a discussion forum, open in the [GitHub repo for GreenfieldPQC](https://github.com/JPKusumi/GreenfieldPQC/discussions). Go there with questions, comments, and feedback. Happy coding!\n\n### License\nMIT License\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjpkusumi%2Fgreenfieldpqc","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjpkusumi%2Fgreenfieldpqc","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjpkusumi%2Fgreenfieldpqc/lists"}