xscriptor/xkyber_crypto

GitHub: xscriptor/xkyber_crypto

一个基于 Kyber 算法的后量子加密 Dart 库,提供密钥封装与抗量子通信能力。

Stars: 10 | Forks: 0

# XKyber_crypto 这是一个用于后量子加密的 Dart 库,提供基于 Kyber 算法的密钥封装机制(KEM)。Kyber 是 NIST 选为标准化的后量子密码方案,旨在抵御量子计算机的攻击。 ## 功能特性 - 使用 Kyber KEM 生成公钥和私钥对。 - 使用公钥封装共享密钥。 - 使用私钥解封装共享密钥。 - 共享密钥可用于对称加密算法(例如 AES-GCM)来加密或解密任意消息。 - 使用 SHAKE128,并完全遵循官方 Kyber 规范。 ## 先决条件 在使用本库之前,请确保具备以下条件: - Dart SDK:版本 2.12.0 或更高。 - Flutter(可选,若在 Flutter 项目中使用本库)。 - 编辑器(如 Visual Studio Code 或 IntelliJ),以方便开发。 ## 安装 要安装本库,请在 `pubspec.yaml` 文件中添加依赖项: ``` dependencies: xkyber_crypto: git: url: https://github.com/xscriptorcode/xkyber_crypto.git ``` 然后运行以下命令更新依赖: ``` dart pub get ``` ## 使用示例 - 以下是一个基本使用示例: ``` // example/general_example.dart // ignore_for_file: avoid_print, always_specify_types import 'dart:typed_data'; import 'package:xkyber_crypto/xkyber_crypto.dart'; Future main() async { print("=== XKyber_crypto Usage Example ==="); // 1. Key Pair Generation // Generate a Kyber key pair. KyberKeyPair keypair = KyberKeyPair.generate(); print("Public Key (${keypair.publicKey.length} bytes):"); print(keypair.publicKey); print("Secret Key (${keypair.secretKey.length} bytes):"); print(keypair.secretKey); // 2. Encapsulation // Using the public key, encapsulate a shared secret. KyberEncapsulationResult encapsulationResult = KyberKEM.encapsulate(keypair.publicKey); Uint8List ciphertext = encapsulationResult.ciphertextKEM; Uint8List sharedSecretEnc = encapsulationResult.sharedSecret; print("\nCiphertext (${ciphertext.length} bytes):"); print(ciphertext); print("\nEncapsulated Shared Secret (${sharedSecretEnc.length} bytes):"); print(sharedSecretEnc); // 3. Decapsulation // Using the secret key, decapsulate to recover the shared secret. Uint8List sharedSecretDec = KyberKEM.decapsulate(ciphertext, keypair.secretKey); print("\nDecapsulated Shared Secret (${sharedSecretDec.length} bytes):"); print(sharedSecretDec); // 4. Verify that both shared secrets match. if (sharedSecretEnc.toString() == sharedSecretDec.toString()) { print("\nShared secrets match!"); } else { print("\nShared secrets do NOT match!"); } // 5. (Optional) Symmetric Encryption using the Shared Secret // Here, we demonstrate how to generate a symmetric key, encrypt a message, // and then decrypt it using the AES-GCM implementation provided in xkyber_symmetric.dart. Uint8List symKey = await XKyberCrypto.generateSymmetricKey(); String plaintext = "This is a secret message."; String encrypted = await XKyberCrypto.symmetricEncrypt(plaintext, symKey); String decrypted = await XKyberCrypto.symmetricDecrypt(encrypted, symKey); print("\nSymmetric Encryption Example:"); print("Plaintext: $plaintext"); print("Encrypted (Base64): $encrypted"); print("Decrypted: $decrypted"); } ``` - 以下是如何测试本库: ``` // /example/main.dart == example file // ignore_for_file: avoid_print, always_specify_types // test/general_test.dart import 'dart:convert'; import 'dart:typed_data'; import 'package:test/test.dart'; import 'package:xkyber_crypto/xkyber_crypto.dart'; // Adjust the path as necessary void main() { group('Random Bytes', () { test('randombytes returns the correct number of bytes', () { final bytes = randombytes(16); expect(bytes.length, equals(16)); }); }); group('SHAKE128', () { test('Generates output of the requested length', () { final seed = Uint8List.fromList(List.generate(10, (i) => i)); final out = shake128(seed, 64); expect(out.length, equals(64)); }); }); group('Polynomial Operations', () { test('Serialization/Deserialization of a polynomial', () { final poly = Poly(); // Initialize polynomial coefficients with test values. for (int i = 0; i < KYBER_N; i++) { poly.coeffs[i] = i % KYBER_Q; } final bytes = polytobytes(poly); final poly2 = polyfrombytes(bytes); for (int i = 0; i < KYBER_N; i++) { expect(poly2.coeffs[i] % KYBER_Q, equals(poly.coeffs[i] % KYBER_Q), reason: 'Coefficient $i does not match'); } }); test('Compression/Decompression of a polynomial', () { final poly = Poly(); // Use a test polynomial; here we use (i * 7) mod KYBER_Q. for (int i = 0; i < KYBER_N; i++) { poly.coeffs[i] = (i * 7) % KYBER_Q; } final compressed = polycompress(poly); final decompressed = polydecompress(compressed); for (int i = 0; i < KYBER_N; i++) { final diff = (poly.coeffs[i] - decompressed.coeffs[i]).abs(); // Increase the tolerance to 50 due to quantization error from 3-bit compression. expect(diff, lessThan(209), reason: 'Coefficient $i: difference $diff exceeds tolerance'); } }); }); group('PolyVec Operations', () { test('Serialization/Deserialization of PolyVec', () { final polyVec = PolyVec(); // Set each polynomial in the vector with test values. for (int i = 0; i < KYBER_K; i++) { for (int j = 0; j < KYBER_N; j++) { polyVec.vec[i].coeffs[j] = (i * 123 + j) % KYBER_Q; } } final bytes = polyvectobytes(polyVec); final polyVec2 = polyvecfrombytes(bytes); for (int i = 0; i < KYBER_K; i++) { for (int j = 0; j < KYBER_N; j++) { expect(polyVec2.vec[i].coeffs[j] % KYBER_Q, equals(polyVec.vec[i].coeffs[j] % KYBER_Q), reason: 'PolyVec[$i] coefficient $j does not match'); } } }); }); group('IND-CPA and KEM', () { test('Keypair, encapsulation, and decapsulation', () { // Generate keypair. final keypair = KyberKeyPair.generate(); expect(keypair.publicKey.length, equals(KYBER_PUBLICKEYBYTES)); expect(keypair.secretKey.length, equals(KYBER_SECRETKEYBYTES)); // Encapsulate using the public key. final encapsulationResult = KyberKEM.encapsulate(keypair.publicKey); final ciphertext = encapsulationResult.ciphertextKEM; final sharedSecretEnc = encapsulationResult.sharedSecret; // Decapsulate using the secret key. final sharedSecretDec = KyberKEM.decapsulate(ciphertext, keypair.secretKey); // The shared secrets should match. expect(sharedSecretDec, equals(sharedSecretEnc)); }); }); group('Symmetric Encryption (AES-GCM)', () { test('Symmetric encryption and decryption', () async { final key = await XKyberCrypto.generateSymmetricKey(); final plaintext = "Test message for symmetric encryption."; final encrypted = await XKyberCrypto.symmetricEncrypt(plaintext, key); final decrypted = await XKyberCrypto.symmetricDecrypt(encrypted, key); expect(decrypted, equals(plaintext)); }); }); group('Constant Time Comparison', () { test('constantTimeCompare works correctly', () { final a = Uint8List.fromList([1, 2, 3, 4, 5]); final b = Uint8List.fromList([1, 2, 3, 4, 5]); final c = Uint8List.fromList([1, 2, 3, 4, 6]); expect(constantTimeCompare(a, b), isTrue); expect(constantTimeCompare(a, c), isFalse); }); }); } ``` ## 本示例演示 - 生成 Kyber 密钥对。 - 使用 cryptoKemEnc 和公钥封装共享密钥。 - 使用 cryptoKemDec 和私钥解封装共享密钥。 - 使用共享密钥(ss)进行对称加密。 # API ## 主要函数 - cryptoKemKeypair(Uint8List pk, Uint8List sk):生成 Kyber 密钥对。 - cryptoKemEnc(Uint8List c, Uint8List ss, Uint8List pk):使用公钥 pk 封装共享密钥 ss,并生成密文 c。 - cryptoKemDec(Uint8List ss, Uint8List c, Uint8List sk):使用私钥 sk 解封装密文 c,以恢复共享密钥 ss。 ## 类 - KyberKeyPair: - generate():生成 Kyber 密钥对(公钥,私钥)。 - publicKey, privateKey:表示密钥的字节数组。 ## 项目结构 - **`lib/`**: 包含库的主要实现。 - kem.dart:核心 Kyber KEM 函数(cryptoKemEnc、cryptoKemDec、cryptoKemKeypair)。 - kyber_keypair.dart:处理密钥生成及相关工具。 - poly.dart、polyvec.dart、ntt.dart、params.dart 等:核心 Kyber 实现(NTT、多项式运算、参数定义)。 - shake.dart:SHAKE128 实现。 - reduce.dart、fq.dart:模运算与域操作。 - **`example/`**: 用于理解库用法的示例代码。 - **`test/`**: 自动化测试,用于验证库功能。 ## 依赖项 本库使用以下依赖: - **`crypto: ^3.0.6`**:提供常用加密函数。 - **`pointycastle: ^3.9.1`**:Dart 的高级加密库。 - **`lints: ^5.0.0`**:建立 Dart 代码的风格规则与最佳实践。 请确保使用最新版本以保证兼容性和性能。 ## 测试与质量 ### 自动化测试 本库包含以下测试以验证功能: - 密钥生成与共享密钥:确保生成的密钥与共享密钥正确。 - 封装/解封装:验证 cryptoKemEnc 与 cryptoKemDec 生成的共享密钥匹配。 - 数学运算:检查 NTT、模运算与噪声分布。 运行方式: ``` dart test ``` ## 警告与限制 - 本库仅适用于研究、测试与教育用途。生产环境使用前建议进行彻底的安全审计。 - 性能可能因设备能力而异。 ## 感谢与参考 本项目灵感来源于 Kyber 算法,该算法已被 NIST 选为后量子密码标准的一部分。有关 Kyber 的更多信息请参考[此处](https://pq-crystals.org/kyber/)。 ## 许可证 本项目采用 MIT 许可证授权。更多细节请参考[LICENSE](LICENSE) 文件。
标签:AES-GCM, Dart, Flutter, KEM, Kyber算法, NIST标准化, post-quantum, ProjectDiscovery, SHAKE128, 公钥加密, 共享密钥, 加密库, 后量子密码, 安全通信, 密码学, 密钥协商, 密钥对生成, 密钥封装机制, 对称加密, 库, 应急响应, 开源加密, 手动系统调用, 数据保护, 移动加密, 自动化审计, 量子安全, 隐私安全