Reputation: 1
There is the following task:
But when I run the code I get an error: ValueError: An X25519 private key is 32 bytes long
This is understandable, because sha256 returns a string equal to 64 bits. Please tell me where I'm wrong
Here's the code I'm trying:
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
from hashlib import sha256
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
#passphrase
passphrase = "asdasfsdfsjddfueirgnuengigtnsenveigvuneirvneriuvniuvnrsbng"
#hashing passphrase sha256
passphrase_sha256 = sha256(passphrase.encode('utf-8')).hexdigest()
#I pass the hash to cruve25519
private_key = X25519PrivateKey.from_private_bytes(passphrase_sha256)
peer_public_key = X25519PrivateKey.from_private_bytes(passphrase_sha256).public_key()
Upvotes: 0
Views: 141
Reputation: 345
SHA-256 produces a 64-character hexadecimal string but X25519PrivateKey expects input to be a 32-byte binary string not a hexadecimal string this is why you have to use as recommended from @Topaco bytes.fromhex()
or just changing the hexdigest()
to digest()
(although both approaches works using the digest()
is better in term readability and in bigger applications efficiency):
digest:
passphrase_sha256_hex = sha256(passphrase.encode('utf-
8')).digest()
bytes.fromhex():
passphrase_sha256_hex = sha256(passphrase.encode('utf-8')).hexdigest()
passphrase_sha256 = bytes.fromhex(passphrase_sha256_hex)
.....
Upvotes: 1