Alex
Alex

Reputation: 1

python pass the hashed sha256 phrase to curve25519

There is the following task:

The secret passphrase is hashed SHA256 to retrive the account's private key

The private key is encrypted using Curve25519 to obtain the public key of the account

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

Answers (1)

Shad0w
Shad0w

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

Related Questions