Possible fix for test_random_keys() failure on short keys #2173

Merged
PeterSurda merged 4 commits from gitea-68 into v0.6 2024-02-20 02:23:12 +01:00
2 changed files with 31 additions and 5 deletions

View File

@ -107,12 +107,19 @@ class ECC(object):
High level function which returns : High level function which returns :
curve(2) + len_of_pubkeyX(2) + pubkeyX + len_of_pubkeyY + pubkeyY curve(2) + len_of_pubkeyX(2) + pubkeyX + len_of_pubkeyY + pubkeyY
""" """
ctx = OpenSSL.BN_CTX_new()
n = OpenSSL.BN_new()
group = OpenSSL.EC_GROUP_new_by_curve_name(self.curve)
OpenSSL.EC_GROUP_get_order(group, n, ctx)
key_len = OpenSSL.BN_num_bytes(n)
pubkey_x = self.pubkey_x.rjust(key_len, b'\x00')
pubkey_y = self.pubkey_y.rjust(key_len, b'\x00')
return b''.join(( return b''.join((
pack('!H', self.curve), pack('!H', self.curve),
pack('!H', len(self.pubkey_x)), pack('!H', len(pubkey_x)),
self.pubkey_x, pubkey_x,
pack('!H', len(self.pubkey_y)), pack('!H', len(pubkey_y)),
self.pubkey_y, pubkey_y,
)) ))
def get_privkey(self): def get_privkey(self):

View File

@ -1,5 +1,6 @@
"""Tests for ECC object""" """Tests for ECC object"""
import os
import unittest import unittest
from hashlib import sha512 from hashlib import sha512
@ -26,10 +27,28 @@ class TestECC(unittest.TestCase):
def test_random_keys(self): def test_random_keys(self):
"""A dummy test for random keys in ECC object""" """A dummy test for random keys in ECC object"""
eccobj = pyelliptic.ECC(curve='secp256k1') eccobj = pyelliptic.ECC(curve='secp256k1')
self.assertEqual(len(eccobj.privkey), 32) self.assertTrue(len(eccobj.privkey) <= 32)
pubkey = eccobj.get_pubkey() pubkey = eccobj.get_pubkey()
self.assertEqual(pubkey[:4], b'\x02\xca\x00\x20') self.assertEqual(pubkey[:4], b'\x02\xca\x00\x20')
def test_short_keys(self):
"""Check formatting of the keys with leading zeroes"""
# pylint: disable=protected-access
def sample_key(_):
"""Fake ECC keypair"""
return os.urandom(32), os.urandom(31), os.urandom(30)
try:
gen_orig = pyelliptic.ECC._generate
pyelliptic.ECC._generate = sample_key
eccobj = pyelliptic.ECC(curve='secp256k1')
pubkey = eccobj.get_pubkey()
self.assertEqual(pubkey[:4], b'\x02\xca\x00\x20')
self.assertEqual(pubkey[36:38], b'\x00\x20')
self.assertEqual(len(pubkey[38:]), 32)
finally:
pyelliptic.ECC._generate = gen_orig
def test_decode_keys(self): def test_decode_keys(self):
"""Check keys decoding""" """Check keys decoding"""
# pylint: disable=protected-access # pylint: disable=protected-access