open-quantum-safe / liboqs-python

Python 3 bindings for liboqs
https://openquantumsafe.org/
MIT License
106 stars 36 forks source link

Kyber Implementation Not Working Properly #69

Closed FlareXes closed 7 months ago

FlareXes commented 8 months ago

Key Exchange Issue with Kyber-1024 in Python

I am encountering an issue while implementing the Kyber-1024 key encapsulation mechanism in my Python project. The shared secret keys between two parties do not seem to match. I have provided a simplified version of the code below:

import oqs

algo = "Kyber1024"
kyber_A = oqs.KeyEncapsulation(algo)
public_key_A, private_key_A = kyber_A.generate_keypair(), kyber_A.export_secret_key()

kyber_B = oqs.KeyEncapsulation(algo)
public_key_B, private_key_B = kyber_B.generate_keypair(), kyber_B.export_secret_key()

shared_secret_A, encapsulated_key_A = kyber_A.encap_secret(public_key_B)
shared_secret_B = kyber_B.decap_secret(encapsulated_key_A)

assert shared_secret_A == shared_secret_B

Output:

Traceback (most recent call last):
  File "/home/flarexes/Desktop/dip/Project/qcrypto.py", line 39, in <module>
    assert shared_secret_A == shared_secret_B
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError

Any help would be highly appreciated. Thank you!

vsoftco commented 7 months ago

@FlareXes The line shared_secret_A, encapsulated_key_A = kyber_A.encap_secret(public_key_B) should have its results flipped, i.e. encapsulated_key_A, shared_secret_A = kyber_A.encap_secret(public_key_B). Also, there's no need for the line public_key_A, private_key_A = kyber_A.generate_keypair(), kyber_A.export_secret_key().

Please take a look here for a full example: https://github.com/open-quantum-safe/liboqs-python/blob/main/examples/kem.py.