# ===================================================================
#
# Copyright (c) 2015, Legrandin <helderijs@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ===================================================================
import os
import errno
import warnings
import unittest
from binascii import unhexlify
from Cryptodome.SelfTest.st_common import list_test_cases
from Cryptodome.Util.py3compat import bord, tostr, FileNotFoundError
from Cryptodome.Util.asn1 import DerSequence, DerBitString
from Cryptodome.Util.number import bytes_to_long
from Cryptodome.Hash import SHAKE128
from Cryptodome.PublicKey import ECC
try:
import pycryptodome_test_vectors # type: ignore
test_vectors_available = True
except ImportError:
test_vectors_available = False
class MissingTestVectorException(ValueError):
pass
def load_file(file_name, mode="rb"):
results = None
try:
if not test_vectors_available:
raise FileNotFoundError(errno.ENOENT,
os.strerror(errno.ENOENT),
file_name)
dir_comps = ("PublicKey", "ECC")
init_dir = os.path.dirname(pycryptodome_test_vectors.__file__)
full_file_name = os.path.join(os.path.join(init_dir, *dir_comps), file_name)
with open(full_file_name, mode) as file_in:
results = file_in.read()
except FileNotFoundError:
warnings.warn("Warning: skipping extended tests for ECC",
UserWarning,
stacklevel=2)
if results is None:
raise MissingTestVectorException("Missing %s" % file_name)
return results
def compact(lines):
ext = b"".join(lines)
return unhexlify(tostr(ext).replace(" ", "").replace(":", ""))
def create_ref_keys_p192():
key_len = 24
key_lines = load_file("ecc_p192.txt").splitlines()
private_key_d = bytes_to_long(compact(key_lines[2:4]))
public_key_xy = compact(key_lines[5:9])
assert bord(public_key_xy[0]) == 4 # Uncompressed
public_key_x = bytes_to_long(public_key_xy[1:key_len+1])
public_key_y = bytes_to_long(public_key_xy[key_len+1:])
return (ECC.construct(curve="P-192", d=private_key_d),
ECC.construct(curve="P-192", point_x=public_key_x, point_y=public_key_y))
def create_ref_keys_p224():
key_len = 28
key_lines = load_file("ecc_p224.txt").splitlines()
private_key_d = bytes_to_long(compact(key_lines[2:4]))
public_key_xy = compact(key_lines[5:9])
assert bord(public_key_xy[0]) == 4 # Uncompressed
public_key_x = bytes_to_long(public_key_xy[1:key_len+1])
public_key_y = bytes_to_long(public_key_xy[key_len+1:])
return (ECC.construct(curve="P-224", d=private_key_d),
ECC.construct(curve="P-224", point_x=public_key_x, point_y=public_key_y))
def create_ref_keys_p256():
key_len = 32
key_lines = load_file("ecc_p256.txt").splitlines()
private_key_d = bytes_to_long(compact(key_lines[2:5]))
public_key_xy = compact(key_lines[6:11])
assert bord(public_key_xy[0]) == 4 # Uncompressed
public_key_x = bytes_to_long(public_key_xy[1:key_len+1])
public_key_y = bytes_to_long(public_key_xy[key_len+1:])
return (ECC.construct(curve="P-256", d=private_key_d),
ECC.construct(curve="P-256", point_x=public_key_x, point_y=public_key_y))
def create_ref_keys_p384():
key_len = 48
key_lines = load_file("ecc_p384.txt").splitlines()
private_key_d = bytes_to_long(compact(key_lines[2:6]))
public_key_xy = compact(key_lines[7:14])
assert bord(public_key_xy[0]) == 4 # Uncompressed
public_key_x = bytes_to_long(public_key_xy[1:key_len+1])
public_key_y = bytes_to_long(public_key_xy[key_len+1:])
return (ECC.construct(curve="P-384", d=private_key_d),
ECC.construct(curve="P-384", point_x=public_key_x, point_y=public_key_y))
def create_ref_keys_p521():
key_len = 66
key_lines = load_file("ecc_p521.txt").splitlines()
private_key_d = bytes_to_long(compact(key_lines[2:7]))
public_key_xy = compact(key_lines[8:17])
assert bord(public_key_xy[0]) == 4 # Uncompressed
public_key_x = bytes_to_long(public_key_xy[1:key_len+1])
public_key_y = bytes_to_long(public_key_xy[key_len+1:])
return (ECC.construct(curve="P-521", d=private_key_d),
ECC.construct(curve="P-521", point_x=public_key_x, point_y=public_key_y))
def create_ref_keys_ed25519():
key_lines = load_file("ecc_ed25519.txt").splitlines()
seed = compact(key_lines[5:8])
key = ECC.construct(curve="Ed25519", seed=seed)
return (key, key.public_key())
def create_ref_keys_ed448():
key_lines = load_file("ecc_ed448.txt").splitlines()
seed = compact(key_lines[6:10])
key = ECC.construct(curve="Ed448", seed=seed)
return (key, key.public_key())
# Create reference key pair
# ref_private, ref_public = create_ref_keys_p521()
def get_fixed_prng():
return SHAKE128.new().update(b"SEED").read
def extract_bitstring_from_spki(data):
seq = DerSequence()
seq.decode(data)
bs = DerBitString()
bs.decode(seq[1])
return bs.value
class TestImport(unittest.TestCase):
def test_empty(self):
self.assertRaises(ValueError, ECC.import_key, b"")
class TestImport_P192(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestImport_P192, self).__init__(*args, **kwargs)
self.ref_private, self.ref_public = create_ref_keys_p192()
def test_import_public_der(self):
key_file = load_file("ecc_p192_public.der")
key = ECC._import_subjectPublicKeyInfo(key_file)
self.assertEqual(self.ref_public, key)
key = ECC._import_der(key_file, None)
self.assertEqual(self.ref_public, key)
key = ECC.import_key(key_file)
self.assertEqual(self.ref_public, key)
def test_import_sec1_uncompressed(self):
key_file = load_file("ecc_p192_public.der")
value = extract_bitstring_from_spki(key_file)
key = ECC.import_key(key_file, curve_name='P192')
self.assertEqual(self.ref_public, key)
def test_import_sec1_compressed(self):
key_file = load_file("ecc_p192_public_compressed.der")
value = extract_bitstring_from_spki(key_file)
key = ECC.import_key(key_file, curve_name='P192')
self.assertEqual(self.ref_public, key)
def test_import_rfc5915_der(self):
key_file = load_file("ecc_p192_private.der")
评论0