{"id":22276234,"url":"https://github.com/xscriptorcode/xkyber_crypto","last_synced_at":"2025-04-11T21:43:08.320Z","repository":{"id":259950095,"uuid":"879885391","full_name":"xscriptorcode/xkyber_crypto","owner":"xscriptorcode","description":"xKyberCrypto post-quantum encryption solutions in flutter based on the Kyber algorithm.","archived":false,"fork":false,"pushed_at":"2025-02-17T19:29:10.000Z","size":1726,"stargazers_count":3,"open_issues_count":3,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-17T20:30:56.886Z","etag":null,"topics":["crypto","cryptography","cryptography-algorithms","dart-package","flutter-crypto","kyber","kyber-algorithm","library","post-quantum-cryptography","public-key-encryption","security","xkyber"],"latest_commit_sha":null,"homepage":"https://www.xscriptor.com","language":"Dart","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/xscriptorcode.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","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}},"created_at":"2024-10-28T18:06:18.000Z","updated_at":"2025-02-17T19:29:13.000Z","dependencies_parsed_at":"2025-02-08T21:34:59.159Z","dependency_job_id":null,"html_url":"https://github.com/xscriptorcode/xkyber_crypto","commit_stats":null,"previous_names":["xscriptorcode/xkyber_crypto"],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xscriptorcode%2Fxkyber_crypto","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xscriptorcode%2Fxkyber_crypto/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xscriptorcode%2Fxkyber_crypto/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xscriptorcode%2Fxkyber_crypto/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/xscriptorcode","download_url":"https://codeload.github.com/xscriptorcode/xkyber_crypto/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245509745,"owners_count":20627045,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","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":["crypto","cryptography","cryptography-algorithms","dart-package","flutter-crypto","kyber","kyber-algorithm","library","post-quantum-cryptography","public-key-encryption","security","xkyber"],"created_at":"2024-12-03T14:14:14.582Z","updated_at":"2025-03-25T17:27:21.468Z","avatar_url":"https://github.com/xscriptorcode.png","language":"Dart","funding_links":[],"categories":[],"sub_categories":[],"readme":"# XKyber_crypto\n\nIs a Dart library for post-quantum encryption, providing a Key Encapsulation Mechanism (KEM) based on the Kyber algorithm. Kyber is a post-quantum cryptographic scheme selected by NIST for standardization, designed to be secure against attacks from quantum computers.\n\n## Features\n\n- Generation of public and private key pairs using the Kyber KEM.\n- Encapsulation of a shared secret using a public key.\n- Decapsulation of the shared secret using a private key.\n- The shared secret can then be used with a symmetric cipher (e.g., AES-GCM) to encrypt or decrypt arbitrary messages.\n- Uses SHAKE128 and fully follows the official Kyber specifications.\n\n---\n\n## Prerequisites\n\nBefore using this library, ensure you have the following:\n- Dart SDK: version 2.12.0 or higher.\n- Flutter (optional, if using this library in a Flutter project).\n- An editor such as Visual Studio Code or IntelliJ to facilitate development.\n\n---\n\n## Installation\n\nTo install this library, add the dependency to your `pubspec.yaml` file:\n\n```yaml\ndependencies:\n  xkyber_crypto:\n    git:\n      url: https://github.com/xscriptorcode/xkyber_crypto.git\n```\n\nUpdate your dependencies with:\n\n```bash\ndart pub get\n```\n\n---\n\n## Usage Example\n\n- Here’s a basic example of how to use this library:\n\n```dart\n// example/general_example.dart\n// ignore_for_file: avoid_print, always_specify_types\n\nimport 'dart:typed_data';\nimport 'package:xkyber_crypto/xkyber_crypto.dart';\n\nFuture\u003cvoid\u003e main() async {\n  print(\"=== XKyber_crypto Usage Example ===\");\n\n  // 1. Key Pair Generation\n  // Generate a Kyber key pair.\n  KyberKeyPair keypair = KyberKeyPair.generate();\n  print(\"Public Key (${keypair.publicKey.length} bytes):\");\n  print(keypair.publicKey);\n  print(\"Secret Key (${keypair.secretKey.length} bytes):\");\n  print(keypair.secretKey);\n\n  // 2. Encapsulation\n  // Using the public key, encapsulate a shared secret.\n  KyberEncapsulationResult encapsulationResult = KyberKEM.encapsulate(keypair.publicKey);\n  Uint8List ciphertext = encapsulationResult.ciphertextKEM;\n  Uint8List sharedSecretEnc = encapsulationResult.sharedSecret;\n  print(\"\\nCiphertext (${ciphertext.length} bytes):\");\n  print(ciphertext);\n  print(\"\\nEncapsulated Shared Secret (${sharedSecretEnc.length} bytes):\");\n  print(sharedSecretEnc);\n\n  // 3. Decapsulation\n  // Using the secret key, decapsulate to recover the shared secret.\n  Uint8List sharedSecretDec = KyberKEM.decapsulate(ciphertext, keypair.secretKey);\n  print(\"\\nDecapsulated Shared Secret (${sharedSecretDec.length} bytes):\");\n  print(sharedSecretDec);\n\n  // 4. Verify that both shared secrets match.\n  if (sharedSecretEnc.toString() == sharedSecretDec.toString()) {\n    print(\"\\nShared secrets match!\");\n  } else {\n    print(\"\\nShared secrets do NOT match!\");\n  }\n\n  // 5. (Optional) Symmetric Encryption using the Shared Secret\n  // Here, we demonstrate how to generate a symmetric key, encrypt a message,\n  // and then decrypt it using the AES-GCM implementation provided in xkyber_symmetric.dart.\n  Uint8List symKey = await XKyberCrypto.generateSymmetricKey();\n  String plaintext = \"This is a secret message.\";\n  String encrypted = await XKyberCrypto.symmetricEncrypt(plaintext, symKey);\n  String decrypted = await XKyberCrypto.symmetricDecrypt(encrypted, symKey);\n\n  print(\"\\nSymmetric Encryption Example:\");\n  print(\"Plaintext: $plaintext\");\n  print(\"Encrypted (Base64): $encrypted\");\n  print(\"Decrypted: $decrypted\");\n}\n\n```\n- Here is how you can test the library:\n\n```dart\n// /example/main.dart == example file\n// ignore_for_file: avoid_print, always_specify_types\n\n// test/general_test.dart\n\nimport 'dart:convert';\nimport 'dart:typed_data';\n\nimport 'package:test/test.dart';\nimport 'package:xkyber_crypto/xkyber_crypto.dart'; // Adjust the path as necessary\n\nvoid main() {\n  group('Random Bytes', () {\n    test('randombytes returns the correct number of bytes', () {\n      final bytes = randombytes(16);\n      expect(bytes.length, equals(16));\n    });\n  });\n\n  group('SHAKE128', () {\n    test('Generates output of the requested length', () {\n      final seed = Uint8List.fromList(List.generate(10, (i) =\u003e i));\n      final out = shake128(seed, 64);\n      expect(out.length, equals(64));\n    });\n  });\n\n  group('Polynomial Operations', () {\n    test('Serialization/Deserialization of a polynomial', () {\n      final poly = Poly();\n      // Initialize polynomial coefficients with test values.\n      for (int i = 0; i \u003c KYBER_N; i++) {\n        poly.coeffs[i] = i % KYBER_Q;\n      }\n      final bytes = polytobytes(poly);\n      final poly2 = polyfrombytes(bytes);\n      for (int i = 0; i \u003c KYBER_N; i++) {\n        expect(poly2.coeffs[i] % KYBER_Q, equals(poly.coeffs[i] % KYBER_Q),\n            reason: 'Coefficient $i does not match');\n      }\n    });\n\n    test('Compression/Decompression of a polynomial', () {\n      final poly = Poly();\n      // Use a test polynomial; here we use (i * 7) mod KYBER_Q.\n      for (int i = 0; i \u003c KYBER_N; i++) {\n        poly.coeffs[i] = (i * 7) % KYBER_Q;\n      }\n      final compressed = polycompress(poly);\n      final decompressed = polydecompress(compressed);\n      for (int i = 0; i \u003c KYBER_N; i++) {\n        final diff = (poly.coeffs[i] - decompressed.coeffs[i]).abs();\n        // Increase the tolerance to 50 due to quantization error from 3-bit compression.\n        expect(diff, lessThan(209),\n            reason: 'Coefficient $i: difference $diff exceeds tolerance');\n      }\n    });\n  });\n\n  group('PolyVec Operations', () {\n    test('Serialization/Deserialization of PolyVec', () {\n      final polyVec = PolyVec();\n      // Set each polynomial in the vector with test values.\n      for (int i = 0; i \u003c KYBER_K; i++) {\n        for (int j = 0; j \u003c KYBER_N; j++) {\n          polyVec.vec[i].coeffs[j] = (i * 123 + j) % KYBER_Q;\n        }\n      }\n      final bytes = polyvectobytes(polyVec);\n      final polyVec2 = polyvecfrombytes(bytes);\n      for (int i = 0; i \u003c KYBER_K; i++) {\n        for (int j = 0; j \u003c KYBER_N; j++) {\n          expect(polyVec2.vec[i].coeffs[j] % KYBER_Q,\n              equals(polyVec.vec[i].coeffs[j] % KYBER_Q),\n              reason: 'PolyVec[$i] coefficient $j does not match');\n        }\n      }\n    });\n  });\n\n  group('IND-CPA and KEM', () {\n    test('Keypair, encapsulation, and decapsulation', () {\n      // Generate keypair.\n      final keypair = KyberKeyPair.generate();\n      expect(keypair.publicKey.length, equals(KYBER_PUBLICKEYBYTES));\n      expect(keypair.secretKey.length, equals(KYBER_SECRETKEYBYTES));\n\n      // Encapsulate using the public key.\n      final encapsulationResult = KyberKEM.encapsulate(keypair.publicKey);\n      final ciphertext = encapsulationResult.ciphertextKEM;\n      final sharedSecretEnc = encapsulationResult.sharedSecret;\n\n      // Decapsulate using the secret key.\n      final sharedSecretDec = KyberKEM.decapsulate(ciphertext, keypair.secretKey);\n\n      // The shared secrets should match.\n      expect(sharedSecretDec, equals(sharedSecretEnc));\n    });\n  });\n\n  group('Symmetric Encryption (AES-GCM)', () {\n    test('Symmetric encryption and decryption', () async {\n      final key = await XKyberCrypto.generateSymmetricKey();\n      final plaintext = \"Test message for symmetric encryption.\";\n      final encrypted = await XKyberCrypto.symmetricEncrypt(plaintext, key);\n      final decrypted = await XKyberCrypto.symmetricDecrypt(encrypted, key);\n      expect(decrypted, equals(plaintext));\n    });\n  });\n\n  group('Constant Time Comparison', () {\n    test('constantTimeCompare works correctly', () {\n      final a = Uint8List.fromList([1, 2, 3, 4, 5]);\n      final b = Uint8List.fromList([1, 2, 3, 4, 5]);\n      final c = Uint8List.fromList([1, 2, 3, 4, 6]);\n      expect(constantTimeCompare(a, b), isTrue);\n      expect(constantTimeCompare(a, c), isFalse);\n    });\n  });\n}\n\n\n\n```\n\n## This example demonstrates:\n\n- Generating a Kyber key pair.\n- Encapsulating a shared secret with cryptoKemEnc and pk.\n- Decapsulating the shared secret with cryptoKemDec and sk.\n- Using the shared secret (ss) for symmetric encryption.\n\n---\n\n# API\n\n\n## Main Functions\n- cryptoKemKeypair(Uint8List pk, Uint8List sk): Generates a Kyber key pair.\n- cryptoKemEnc(Uint8List c, Uint8List ss, Uint8List pk): Encapsulates a shared secret ss using pk and produces ciphertext c.\n- cryptoKemDec(Uint8List ss, Uint8List c, Uint8List sk): Decapsulates c using sk to recover ss.\n\n## Classes\n- KyberKeyPair:\n- generate(): Produces a Kyber key pair (publicKey, privateKey).\n- publicKey, privateKey: Byte arrays representing the keys.\n\n---\n\n## Project Structure\n\n- **`lib/`**:\n  Contains the main implementation of the library.\n- kem.dart: Core Kyber KEM functions (cryptoKemEnc, cryptoKemDec, cryptoKemKeypair).\n- kyber_keypair.dart: Handles key generation and utilities.\n- poly.dart, polyvec.dart, ntt.dart, params.dart, etc.: Core Kyber implementation (NTT, polynomial operations, parameter definitions).\n- shake.dart: SHAKE128 implementation.\n- reduce.dart, fq.dart: Modular arithmetic and field operations.\n\n- **`example/`**:\n  Example code for understanding the library usage.\n\n- **`test/`**:\n  Automated tests to verify library functionality.\n\n---\n\n## Dependencies\n\nThe library uses the following dependencies:\n\n- **`crypto: ^3.0.6`**: Provides common cryptographic functions.\n- **`pointycastle: ^3.9.1`**: Advanced library for cryptography in Dart.\n- **`lints: ^5.0.0`**: Establishes style rules and best practices for Dart code.\n\nEnsure you have the latest versions to guarantee compatibility and performance.\n\n---\n\n## Testing and Quality\n\n### Automated Tests\n\n### The library includes tests to verify:\n\n- Key Generation and Shared Secret: Ensures correctness of generated keys and shared secrets.\n- Encapsulation/Decapsulation: Validates that cryptoKemEnc and cryptoKemDec produce matching shared secrets.\n- Math Operations: Checks NTT, modular arithmetic, and noise distribution.\n\nRun with:\n\n```bash\ndart test\n```\n\n---\n\n## Warnings and Limitations\n\n- The library is intended for research, testing, and educational use. For production environments, a thorough security audit is recommended.\n- Performance may vary depending on device capabilities.\n\n---\n\n## Contributions\n\nContributions are welcome. To contribute:\n\n1. Fork this repository.\n2. Create a new branch (`git checkout -b feature/new-functionality`).\n3. Make your changes and commit them (`git commit -m 'Add new functionality'`).\n4. Push your branch (`git push origin feature/new-functionality`).\n5. Open a Pull Request in this repository.\n\n---\n\n## Acknowledgments and References\n\nThis project is inspired by the Kyber algorithm, selected by NIST as part of its post-quantum cryptography standards. More information about Kyber is available [here](https://pq-crystals.org/kyber/).\n\n---\n\n## License\n\nThis project is licensed under the MIT License. See the [LICENSE](LICENSE) file for more details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fxscriptorcode%2Fxkyber_crypto","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fxscriptorcode%2Fxkyber_crypto","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fxscriptorcode%2Fxkyber_crypto/lists"}