コード例 #1
0
    def test_compressed_curve(self):

        # Compressed P-521 curve (Y-point is even)
        # openssl ecparam -name secp521r1 -genkey -noout -conv_form compressed -out /tmp/a.pem
        # openssl ec -in /tmp/a.pem -text -noout
        pem1 = """-----BEGIN EC PRIVATE KEY-----
MIHcAgEBBEIAnm1CEjVjvNfXEN730p+D6su5l+mOztdc5XmTEoti+s2R4GQ4mAv3
0zYLvyklvOHw0+yy8d0cyGEJGb8T3ZVKmg2gBwYFK4EEACOhgYkDgYYABAHzjTI1
ckxQ3Togi0LAxiG0PucdBBBs5oIy3df95xv6SInp70z+4qQ2EltEmdNMssH8eOrl
M5CYdZ6nbcHMVaJUvQEzTrYxvFjOgJiOd+E9eBWbLkbMNqsh1UKVO6HbMbW0ohCI
uGxO8tM6r3w89/qzpG2SvFM/fvv3mIR30wSZDD84qA==
-----END EC PRIVATE KEY-----"""

        # Compressed P-521 curve (Y-point is odd)
        pem2 = """-----BEGIN EC PRIVATE KEY-----
MIHcAgEBBEIB84OfhJluLBRLn3+cC/RQ37C2SfQVP/t0gQK2tCsTf5avRcWYRrOJ
PmX9lNnkC0Hobd75QFRmdxrB0Wd1/M4jZOWgBwYFK4EEACOhgYkDgYYABAAMZcdJ
1YLCGHt3bHCEzdidVy6+brlJIbv1aQ9fPQLF7WKNv4c8w3H8d5a2+SDZilBOsk5c
6cNJDMz2ExWQvxl4CwDJtJGt1+LHVKFGy73NANqVxMbRu+2F8lOxkNp/ziFTbVyV
vv6oYkMIIi7r5oQWAiQDrR2mlrrFDL9V7GH/r8SWQw==
-----END EC PRIVATE KEY-----"""

        key1 = ECC.import_key(pem1)
        low16 = int(key1.pointQ.y % 65536)
        self.assertEqual(low16, 0x38a8)

        key2 = ECC.import_key(pem2)
        low16 = int(key2.pointQ.y % 65536)
        self.assertEqual(low16, 0x9643)
コード例 #2
0
    def test_export_openssh_compressed(self):
        key_file = load_file("ecc_p384_public_openssh.txt", "rt")
        pub_key = ECC.import_key(key_file)

        key_file_compressed = pub_key.export_key(format="OpenSSH", compress=True)
        assert len(key_file) > len(key_file_compressed)
        self.assertEquals(pub_key, ECC.import_key(key_file_compressed))
コード例 #3
0
    def test_compressed_curve(self):

        # Compressed P-384 curve (Y-point is even)
        # openssl ecparam -name secp384p1 -genkey -noout -conv_form compressed -out /tmp/a.pem
        # openssl ec -in /tmp/a.pem -text -noout
        pem1 = """-----BEGIN EC PRIVATE KEY-----
MIGkAgEBBDAM0lEIhvXuekK2SWtdbgOcZtBaxa9TxfpO/GcDFZLCJ3JVXaTgwken
QT+C+XLtD6WgBwYFK4EEACKhZANiAATs0kZMhFDu8DoBC21jrSDPyAUn4aXZ/DM4
ylhDfWmb4LEbeszXceIzfhIUaaGs5y1xXaqf5KXTiAAYx2pKUzAAM9lcGUHCGKJG
k4AgUmVJON29XoUilcFrzjDmuye3B6Q=
-----END EC PRIVATE KEY-----"""

        # Compressed P-384 curve (Y-point is odd)
        pem2 = """-----BEGIN EC PRIVATE KEY-----
MIGkAgEBBDDHPFTslYLltE16fHdSDTtE/2HTmd3M8mqy5MttAm4wZ833KXiGS9oe
kFdx9sNV0KygBwYFK4EEACKhZANiAASLIE5RqVMtNhtBH/u/p/ifqOAlKnK/+RrQ
YC46ZRsnKNayw3wATdPjgja7L/DSII3nZK0G6KOOVwJBznT/e+zudUJYhZKaBLRx
/bgXyxUtYClOXxb1Y/5N7txLstYRyP0=
-----END EC PRIVATE KEY-----"""

        key1 = ECC.import_key(pem1)
        low16 = int(key1.pointQ.y % 65536)
        self.assertEqual(low16, 0x07a4)

        key2 = ECC.import_key(pem2)
        low16 = int(key2.pointQ.y % 65536)
        self.assertEqual(low16, 0xc8fd)
コード例 #4
0
    def test_import_private_pkcs8_clear(self):
        key_file = load_file("ecc_p521_private_p8_clear.der")

        key = ECC._import_der(key_file, None)
        self.assertEqual(self.ref_private, key)

        key = ECC.import_key(key_file)
        self.assertEqual(self.ref_private, key)
コード例 #5
0
    def test_import_private_pkcs8_encrypted_1(self):
        key_file = load_file("ecc_p521_private_p8.der")

        key = ECC._import_der(key_file, "secret")
        self.assertEqual(self.ref_private, key)

        key = ECC.import_key(key_file, "secret")
        self.assertEqual(self.ref_private, key)
コード例 #6
0
    def test_import_x509_der(self):
        key_file = load_file("ecc_p521_x509.der")

        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)
コード例 #7
0
    def test_import_openssh(self):
        key_file = load_file("ecc_p521_public_openssh.txt")

        key = ECC._import_openssh(key_file)
        self.assertEqual(self.ref_public, key)

        key = ECC.import_key(key_file)
        self.assertEqual(self.ref_public, key)
コード例 #8
0
ファイル: test_ECC.py プロジェクト: shubhanus/taiga
    def test_generate(self):

        key = ECC.generate(curve="P-256")
        self.assertTrue(key.has_private())
        self.assertEqual(key.pointQ, EccPoint(_curve.Gx, _curve.Gy) * key.d)

        # Other names
        ECC.generate(curve="secp256r1")
        ECC.generate(curve="prime256v1")
コード例 #9
0
    def test_import_private_pem_encrypted(self):
        for algo in "des3", "aes128", "aes192", "aes256", "aes256_gcm":
            key_file = load_file("ecc_p521_private_enc_%s.pem" % algo)

            key = ECC.import_key(key_file, "secret")
            self.assertEqual(self.ref_private, key)

            key = ECC.import_key(tostr(key_file), b"secret")
            self.assertEqual(self.ref_private, key)
コード例 #10
0
ファイル: test_ECC.py プロジェクト: Legrandin/pycryptodome
    def test_generate(self):

        curve = _curves['p521']
        key = ECC.generate(curve="P-521")
        self.failUnless(key.has_private())
        self.assertEqual(key.pointQ, EccPoint(curve.Gx, curve.Gy, "p521") * key.d)

        # Other names
        ECC.generate(curve="secp521r1")
        ECC.generate(curve="prime521v1")
コード例 #11
0
ファイル: test_import_ECC.py プロジェクト: shubhanus/taiga
def create_ref_keys():
    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:33])
    public_key_y = bytes_to_long(public_key_xy[33:])

    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))
コード例 #12
0
ファイル: test_ECC.py プロジェクト: Legrandin/pycryptodome
    def test_generate(self):

        key = ECC.generate(curve="P-256")
        self.failUnless(key.has_private())
        self.assertEqual(key.pointQ, EccPoint(_curves['p256'].Gx,
                                              _curves['p256'].Gy) * key.d,
                                              "p256")

        # Other names
        ECC.generate(curve="secp256r1")
        ECC.generate(curve="prime256v1")
コード例 #13
0
    def test_import_private_der(self):
        key_file = load_file("ecc_p384_private.der")

        key = ECC._import_private_der(key_file, None)
        self.assertEqual(self.ref_private, key)

        key = ECC._import_der(key_file, None)
        self.assertEqual(self.ref_private, key)

        key = ECC.import_key(key_file)
        self.assertEqual(self.ref_private, key)
コード例 #14
0
    def test_import_public_der(self):
        key_file = load_file("ecc_p521_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)
コード例 #15
0
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))
コード例 #16
0
ファイル: test_ECC.py プロジェクト: Legrandin/pycryptodome
    def test_mix(self):

        p1 = ECC.generate(curve='P-256').pointQ
        p2 = ECC.generate(curve='P-384').pointQ

        try:
            p1 + p2
            assert(False)
        except ValueError as e:
            assert "not on the same curve" in str(e)

        try:
            p1 += p2
            assert(False)
        except ValueError as e:
            assert "not on the same curve" in str(e)
コード例 #17
0
ファイル: wallet.py プロジェクト: Nurraku/ABC
def import_public_key(public_key):
    """
    Import a plain text public key and make it into an ECC object 
    :param public_key: the public key as a string
    :return: an ECC key object
    """
    return ECC.import_key(public_key)
コード例 #18
0
    def test_unsupported_curve(self):

        # openssl ecparam -name secp224r1 -genkey -noout -out strange-curve.pem -conv_form uncompressed
        curve = """-----BEGIN EC PRIVATE KEY-----
MGgCAQEEHEi7xTHW+5oT8wgpjoEKV7uwMuY8rt2YUZe4j1SgBwYFK4EEACGhPAM6
AATJgfOG+Bnki8robpNM8MtArji43GU9up4B0x9sVhqB+fZP+hXgV9ITN7YX4E/k
gVnJp9EBND/tHQ==
-----END EC PRIVATE KEY-----"""

        from Crypto.PublicKey.ECC import UnsupportedEccFeature
        try:
            ECC.import_key(curve)
        except UnsupportedEccFeature as uef:
            assert("1.3.132.0.33" in str(uef))
        else:
            assert(False)
コード例 #19
0
ファイル: wallet.py プロジェクト: Nurraku/ABC
def get_private_key():
    """
    Set the private key from a file or by creating a new one
    :return: ECC private key object
    """
    ensure_data_dir()  # ensure directory exists
    try:  # get existing private key
        key = ECC.import_key(open(_PRIVATE_KEY_PATH, 'rt').read())
    except FileNotFoundError:  # create public key
        key = ECC.generate(curve='P-256')
        # write private key to file
        file = open(_PRIVATE_KEY_PATH, 'wt')
        file.write(key.export_key(format='PEM'))
        file.close()

    return key
コード例 #20
0
    def test_export_public_der_compressed(self):
        key_file = load_file("ecc_p521_public.der")
        pub_key = ECC.import_key(key_file)
        key_file_compressed = pub_key.export_key(format="DER", compress=True)

        key_file_compressed_ref = load_file("ecc_p521_public_compressed.der")
        self.assertEqual(key_file_compressed, key_file_compressed_ref)
コード例 #21
0
ファイル: pwcryptolib.py プロジェクト: rchatterjee/pam-typopw
def decrypt_with_ecc(private_ecc_key, random_pubkey_str, nonce, ctx, tag):
    """Takes elliptic curve isntance (private_ecc_key) and a byte string
    (message), and decrypts the ciphertext (ctx) after verifying the
    tag.

    """
    assert isinstance(private_ecc_key, ECC.EccKey), \
        "private_ecc_key should be ECC key. Got {}" \
            .format(type(private_ecc_key))

    # parse the ciphertext
    random_ecc_key = ECC.import_key(random_pubkey_str)
    new_point = random_ecc_key.pointQ * private_ecc_key.d
    h = SHA256.new(str(new_point.x))
    h.update(str(new_point.y))
    key = h.digest()
    if not nonce:
        nonce = os.urandom(16)
    aes_engine = AES.new(key=key, mode=AES.MODE_EAX, nonce=nonce)
    msg = ''
    try:
        msg = aes_engine.decrypt_and_verify(ctx, tag)
    except ValueError:
        print "The tag verification failed. Means: ciphertext has been "\
            "tampered or key is incorrect" 
    return msg
コード例 #22
0
    def test_export_public_pem_compressed(self):
        key_file = load_file("ecc_p384_public.pem", "rt").strip()
        pub_key = ECC.import_key(key_file)

        key_file_compressed = pub_key.export_key(format="PEM", compress=True)
        key_file_compressed_ref = load_file("ecc_p384_public_compressed.pem", "rt").strip()

        self.assertEqual(key_file_compressed, key_file_compressed_ref)
コード例 #23
0
ファイル: test_ECC.py プロジェクト: shubhanus/taiga
    def test_equality(self):

        private_key = ECC.construct(d=3, curve="P-256")
        private_key2 = ECC.construct(d=3, curve="P-256")
        private_key3 = ECC.construct(d=4, curve="P-256")

        public_key = private_key.public_key()
        public_key2 = private_key2.public_key()
        public_key3 = private_key3.public_key()

        self.assertEqual(private_key, private_key2)
        self.assertNotEqual(private_key, private_key3)

        self.assertEqual(public_key, public_key2)
        self.assertNotEqual(public_key, public_key3)

        self.assertNotEqual(public_key, private_key)
コード例 #24
0
    def test_export_private_pkcs8_encrypted(self):
        encoded = self.ref_private._export_pkcs8(passphrase="secret",
                                            protection="PBKDF2WithHMAC-SHA1AndAES128-CBC")

        # This should prove that the output is password-protected
        self.assertRaises(ValueError, ECC._import_pkcs8, encoded, None)

        decoded = ECC._import_pkcs8(encoded, "secret")
        self.assertEqual(self.ref_private, decoded)

        # ---

        encoded = self.ref_private.export_key(format="DER",
                                         passphrase="secret",
                                         protection="PBKDF2WithHMAC-SHA1AndAES128-CBC")
        decoded = ECC.import_key(encoded, "secret")
        self.assertEqual(self.ref_private, decoded)
コード例 #25
0
def run_test_curvepoint_random():
    #rand = Integer.random_range(min_inclusive=1, max_exclusive=P256_CURVE_ORDER)
    randkey = ECC.generate(curve='P-256')
    randx = int(randkey.public_key().pointQ.x.to_bytes(32).hex(), 16)
    randy = int(randkey.public_key().pointQ.y.to_bytes(32).hex(), 16)

    res = run_isoncurve(randx, randy)
    if not res:
        raise Exception('Test point (random) should be on curve')
コード例 #26
0
 def sign(self, message):
     message = bytes(message.encode())
     key = ECC.generate(curve='P-521')
     h = SHA512.new(message)
     signer = DSS.new(key, 'fips-186-3')
     start_time = timer()
     signature = signer.sign(h)
     self.executionTime = timer() - start_time
     return signature
コード例 #27
0
    def test_export_private_pkcs8_encrypted(self):
        encoded = self.ref_private._export_pkcs8(
            passphrase="secret", protection="PBKDF2WithHMAC-SHA1AndAES128-CBC")

        # This should prove that the output is password-protected
        self.assertRaises(ValueError, ECC._import_pkcs8, encoded, None)

        decoded = ECC._import_pkcs8(encoded, "secret")
        self.assertEqual(self.ref_private, decoded)

        # ---

        encoded = self.ref_private.export_key(
            format="DER",
            passphrase="secret",
            protection="PBKDF2WithHMAC-SHA1AndAES128-CBC")
        decoded = ECC.import_key(encoded, "secret")
        self.assertEqual(self.ref_private, decoded)
コード例 #28
0
    def test_export_private_pem_encrypted(self):
        encoded = self.ref_private._export_private_pem(passphrase=b"secret")

        # This should prove that the output is password-protected
        self.assertRaises(ValueError, ECC.import_key, encoded)

        assert "EC PRIVATE KEY" in encoded

        decoded = ECC.import_key(encoded, "secret")
        self.assertEqual(self.ref_private, decoded)

        # ---

        encoded = self.ref_private.export_key(format="PEM",
                                              passphrase="secret",
                                              use_pkcs8=False)
        decoded = ECC.import_key(encoded, "secret")
        self.assertEqual(self.ref_private, decoded)
コード例 #29
0
ファイル: asymmetric.py プロジェクト: dmitriykuptsov/cutehip
    def load_from_params(curve=None, x=None, y=None):
        """
		Construct public key from the components
		"""
        if curve == ECDSALowPublicKey.SECP160R1:
            return ECDSAPublicKey(
                key=ECC.construct(curve='SECP160R1', point_x=x, point_y=y))
        else:
            raise Exception("Unsupported curve")
コード例 #30
0
ファイル: hashable.py プロジェクト: maximx1/vote_block
 def verify_ecc_sig(self, public_key, data, signature):
     key = ECC.import_key(public_key)
     hashed_message = SHA256.new(data)
     verifier = DSS.new(key, 'fips-186-3')
     try:
         verifier.verify(hashed_message, signature)
         return True
     except ValueError:
         return False
コード例 #31
0
 def construct_public_key(xy):
     """Constructs an ECC-public key starting from the bytes sequences representing the public key.
     :param xy: the bytes sequences representing the public key,
         as of the concatenation of the bytes sequences representing :param x and :param y
     :returns an EccKey object containing the public key corresponding to the couple of coordinates x and y"""
     coordinate_size = len(xy) // 2
     x = int.from_bytes(xy[:coordinate_size], 'big')
     y = int.from_bytes(xy[coordinate_size:], 'big')
     return ECC.construct(curve=STANDARD_CURVE, point_x=x, point_y=y)
コード例 #32
0
ファイル: pwcryptolib.py プロジェクト: rchatterjee/pam-typopw
 def generate_from_pw(pw, salt, curve='P-256'):
     """Generates a ECC key pair using the randomness derived from pw, salt. 
     """
     rand_seed = PBKDF2(pw, salt, dkLen=16, count=HASH_CNT)
     rand_num_generator = RandomWSeed(rand_seed, 1024)
     return ECC.generate(
         curve=curve, 
         randfunc=rand_num_generator.get_random_bytes
     )
コード例 #33
0
    def test_export_public_pem_compressed(self):
        key_file = load_file("ecc_p256_public.pem", "rt").strip()
        pub_key = ECC.import_key(key_file)

        key_file_compressed = pub_key.export_key(format="PEM", compress=True)
        key_file_compressed_ref = load_file("ecc_p256_public_compressed.pem",
                                            "rt").strip()

        self.assertEqual(key_file_compressed, key_file_compressed_ref)
コード例 #34
0
ファイル: tests.py プロジェクト: elon0823/amo-storage
def generate_new_identity():
    key_obj = ECC.generate(curve='P-256')
    x, y = key_obj.pointQ.xy
    xb = int.to_bytes(int(x), 32, byteorder='big')
    yb = int.to_bytes(int(y), 32, byteorder='big')

    public_key = b'\x04' + xb + yb

    return key_obj, public_key, SHA256.new(public_key).digest()[:20].hex().upper()
コード例 #35
0
ファイル: server.py プロジェクト: Bart94/DQV
def verify(message, ac):
    key = ECC.import_key(open('DQV_certs/lab_pk.pem').read())
    h = SHA256.new(message.encode('utf-8'))
    verifier = DSS.new(key, 'fips-186-3')
    try:
        verifier.verify(h, ac)
        return True
    except ValueError:
        return False
def verify_vote(private_key, public_key, ballot):

    try:
        signer = DSS.new(ECC.import_key(private_key), 'fips-186-3')
        verifier = DSS.new(ECC.import_key(public_key), 'fips-186-3')

        ballot_hash = SHA3_256.new(ballot.encode())

        ballot_signature = signer.sign(ballot_hash)

        verifier.verify(ballot_hash, ballot_signature)
        return [
            True, 'Your vote verfied and Ballot is signed successfully.',
            ballot_hash.hexdigest(),
            ballot_signature.hex()
        ]
    except Exception as e:
        return [False, str(e), 'N/A', 'N/A']
コード例 #37
0
ファイル: FEDCoin.py プロジェクト: relotonp/blockchain
    def generate_keypair(self,private_key_str):
        # If this is a 'new' wallet, i.e. no private_key_str has been given to the constructor
        # --> Create a private key
        if private_key_str is None:
            # Generate the private key (in here the randomness takes place)
            private_key = ECC.generate(curve='P-256')
        else:
            # In case this is a wallet for a specific private_key
            # read the private key in string format.
            # binascii.unhexlify(x) converts x which is in hexadecimal format into a binary format
            private_key = ECC.import_key(binascii.unhexlify(private_key_str))

        # Returns a dictionary with private and public key
        keypair = {
        'private_key': binascii.hexlify(private_key.export_key(format='DER')).decode('utf8'),
        'public_key': binascii.hexlify(private_key.public_key().export_key(format='DER')).decode('utf8')
        }
        return keypair
コード例 #38
0
ファイル: helper.py プロジェクト: AdnanSlef/DACC-ECTF-2021
def create_secrets_before():
    # Generate private keys
    privkeys = [ecc.generate(curve='secp256r1') for _ in range(DEPL_COUNT)]

    # Calculate public key points
    pubkeys = [ecc.construct(curve='secp256r1',d=privkey.d).public_key()._point for privkey in privkeys]

    # Generate broadcast keys
    brdcst_privkey = ecc.generate(curve='secp256r1')
    brdcst_public = ecc.construct(curve='secp256r1',d=brdcst_privkey.d).public_key()._point
    brdcst_keys = [brdcst_privkey,brdcst_public]

    # Uniquely identify this deployment
    depl_nonce = get_random_bytes(16)

    # Generate secrets for each depl_id
    for depl_id in range(DEPL_COUNT):
        make_a_secret(depl_id, depl_nonce, privkeys[depl_id], pubkeys, brdcst_keys)
コード例 #39
0
    def test_export_private_pem_encrypted(self):
        encoded = self.ref_private._export_private_pem(passphrase=b"secret")

        # This should prove that the output is password-protected
        self.assertRaises(ValueError, ECC.import_key, encoded)

        assert "EC PRIVATE KEY" in encoded

        decoded = ECC.import_key(encoded, "secret")
        self.assertEqual(self.ref_private, decoded)

        # ---

        encoded = self.ref_private.export_key(format="PEM",
                                         passphrase="secret",
                                         use_pkcs8=False)
        decoded = ECC.import_key(encoded, "secret")
        self.assertEqual(self.ref_private, decoded)
コード例 #40
0
def test_functionality():
    # generate a set of pk,sk pairs
    list_keys = {i: ECC.generate(curve='P-256') for i in xrange(10)}
    pk_dict = {k: v.public_key() for k, v in list_keys.items()}
    msg = 'HI Multiuser! in (test_functionality)'
    ctx = encrypt(pk_dict, msg)
    while list_keys:
        sk_dict = dict([list_keys.popitem()])
        _msg = decrypt(sk_dict, ctx)
        assert msg == _msg, "\n_msg={}\n msg={}\n".format(_msg, msg)
コード例 #41
0
def load_ECC_key(keyfile):
    f = open(keyfile, 'rb')
    keystr = f.read()
    f.close()

    try:
        return ECC.import_key(keystr)
    except ValueError:
        print('ValueError: Cannot import ECC key from file ' + keyfile)
        sys.exit(1)
コード例 #42
0
def test_compute_id_w_saltctx():
    pwtypo = 'asdfadsfadf'
    list_keys = {i: ECC.generate(curve='P-256') for i in xrange(10)}
    pk_dict = {k: v.public_key() for k, v in list_keys.items()}
    salt = os.urandom(32)
    saltctx = encrypt(pk_dict, salt)
    id1 = compute_id_w_saltctx(pwtypo, dict([list_keys.popitem()]), saltctx)
    id2 = compute_id_w_saltctx(pwtypo, dict([list_keys.popitem()]), saltctx)
    assert isinstance(id1, int)
    assert id1 == id2
コード例 #43
0
def ecVerifySignatureFromBase64(publicKeyPem, message, signatureBase64):
    ecPublicKey = ECC.import_key(publicKeyPem)
    signatureBytes = base64Decoding(signatureBase64)
    hashMessage = SHA256.new(message.encode("ascii"))
    verifier = DSS.new(ecPublicKey, 'fips-186-3', 'der')
    try:
        verifier.verify(hashMessage, signatureBytes)
        return True
    except ValueError:
        return False
コード例 #44
0
def create(request):
    if request.method == 'POST':
        voter_id = request.POST.get('voter-id-input')
        vote = request.POST.get('vote-input')
        private_key = request.POST.get('private-key-input')

        # Create ballot as string vector
        timestamp = datetime.datetime.now().timestamp()
        ballot = "{}|{}|{}".format(voter_id, vote, timestamp)
        print('\ncasted ballot: {}\n'.format(ballot))
        signature = ''
        try:
            # Create signature
            priv_key = ECC.import_key(private_key)
            print(priv_key)
            h = SHA3_256.new(ballot.encode('utf-8'))
            signature = DSS.new(priv_key, 'fips-186-3').sign(h)
            print('\nsignature: {}\n'.format(signature.hex()))

            # Verify the signature using registered public key
            pub_key = ECC.import_key(settings.PUBLIC_KEY)
            print(pub_key)
            verifier = DSS.new(pub_key, 'fips-186-3')

            verifier.verify(h, signature)
            status = 'The ballot is signed successfully.'
            error = False
        except (ValueError, TypeError):
            status = 'The key is not registered.'
            error = True

        context = {
            'ballot': ballot,
            'signature': signature,
            'status': status,
            'error': error,
        }
        return render(request, 'ballot/status.html', context)

    context = {
        'voter_id': uuid.uuid4(),
    }
    return render(request, 'ballot/create.html', context)
コード例 #45
0
 def _load_private_key(self):
     """Load the private key used to sign HTTP requests.
         The private key is used to sign HTTP requests as defined in
         https://datatracker.ietf.org/doc/draft-cavage-http-signatures/.
     """
     if self.private_key is not None:
         return
     with open(self.private_key_path, 'r') as f:
         pem_data = f.read()
         # Verify PEM Pre-Encapsulation Boundary
         r = re.compile(r"\s*-----BEGIN (.*)-----\s+")
         m = r.match(pem_data)
         if not m:
             raise ValueError("Not a valid PEM pre boundary")
         pem_header = m.group(1)
         if pem_header == 'RSA PRIVATE KEY':
             self.private_key = RSA.importKey(pem_data, self.private_key_passphrase)
         elif pem_header == 'EC PRIVATE KEY':
             self.private_key = ECC.import_key(pem_data, self.private_key_passphrase)
         elif pem_header in {'PRIVATE KEY', 'ENCRYPTED PRIVATE KEY'}:
             # Key is in PKCS8 format, which is capable of holding many different
             # types of private keys, not just EC keys.
             (key_binary, pem_header, is_encrypted) = \
                 PEM.decode(pem_data, self.private_key_passphrase)
             (oid, privkey, params) = \
                 PKCS8.unwrap(key_binary, passphrase=self.private_key_passphrase)
             if oid == '1.2.840.10045.2.1':
                 self.private_key = ECC.import_key(pem_data, self.private_key_passphrase)
             else:
                 raise Exception("Unsupported key: {0}. OID: {1}".format(pem_header, oid))
         else:
             raise Exception("Unsupported key: {0}".format(pem_header))
         # Validate the specified signature algorithm is compatible with the private key.
         if self.signing_algorithm is not None:
             supported_algs = None
             if isinstance(self.private_key, RSA.RsaKey):
                 supported_algs = {ALGORITHM_RSASSA_PSS, ALGORITHM_RSASSA_PKCS1v15}
             elif isinstance(self.private_key, ECC.EccKey):
                 supported_algs = ALGORITHM_ECDSA_KEY_SIGNING_ALGORITHMS
             if supported_algs is not None and self.signing_algorithm not in supported_algs:
                 raise Exception(
                     "Signing algorithm {0} is not compatible with private key".format(
                         self.signing_algorithm))
コード例 #46
0
def verify_message(message):
    eccpubkey = ECC.import_key(message["eccpubkey"])
    h = SHA256.new(message["aeskey"] + message["nonce"] + message["message"])
    verifier = DSS.new(eccpubkey, 'fips-186-3')

    try:
        verifier.verify(h, message["signature"])
        return True
    except ValueError:
        return False
コード例 #47
0
def createPEM_ECDSA():
    key = ECC.generate(
        curve='P-256'
    )  # private key is generated by using the Elliptic curve cipher
    with open('privkey_ecdsa.pem', 'w') as h:
        h.write(key.export_key(format='PEM'))

    key = key.public_key()
    with open('pubkey_ecdsa.pem', 'w') as h:
        h.write(key.export_key(format='PEM'))
コード例 #48
0
    def sign_transaction(self, private_key):
        # Sign a transaction using the private_key

        private_key = ECC.import_key(binascii.unhexlify(private_key))
        signer = DSS.new(private_key, 'fips-186-3')
        #h = hashlib.sha256.new(str(self.odict_transaction()).encode('utf8'))
        h = SHA256.new(str(self.odict_transaction()).encode('utf8'))
        self.signature = binascii.hexlify(signer.sign(h)).decode('utf8')
        # When the signature is created the id can be set
        self.id = self.hash_transaction()
 def verify_transaction_signature(self, sender_address, signature,
                                  transaction):
     public_key = ECC.import_key(binascii.unhexlify(sender_address))
     verifier = DSS.new(public_key, 'fips-186-3')
     h = SHA512.new(str(transaction).encode('utf-8'))
     try:
         verifier.verify(h, binascii.unhexlify(signature))
         return True
     except ValueError:
         return False
コード例 #50
0
ファイル: wallet.py プロジェクト: felipemfp/pythonchain
    def new_keys(self):
        private_key = ECC.generate(curve="P-256")
        public_key = private_key.public_key()

        response = {
            'private_key': private_key.export_key(format='DER').hex(),
            'public_key': public_key.export_key(format='DER').hex()
        }

        return response
コード例 #51
0
ファイル: test_transform_ecc.py プロジェクト: wech71/benji
 def test_pubkey_only_decryption(self):
     curve = 'NIST P-384'
     ecc_transform = self._get_transform_args(
         ECC.generate(curve=curve).public_key())
     data = b'THIS IS A TEST'
     enc_data, materials = ecc_transform.encapsulate(data=data)
     self.assertRaises(ValueError,
                       ecc_transform.decapsulate,
                       data=enc_data,
                       materials=materials)
コード例 #52
0
ファイル: elftosb.py プロジェクト: saper/spsdk
def generate_master_boot_image(image_conf: click.File) -> None:
    """Generate MasterBootImage from json configuration file."""
    config_data = json.load(image_conf)
    config = elftosb_helper.MasterBootImageConfig(config_data)
    app = load_binary(config.input_image_file)
    load_addr = config.output_image_exec_address
    trustzone = _get_trustzone(config)
    image_type = _get_master_boot_image_type(config)
    dual_boot_version = config.dual_boot_version
    firmware_version = config.firmware_version

    cert_block = None
    signature_provider = None
    if MasterBootImageType.is_signed(image_type):
        cert_config = elftosb_helper.CertificateBlockConfig(config_data)
        root_certs = [
            load_binary(cert_file) for cert_file in cert_config.root_certs  # type: ignore
        ]
        user_data = None
        if cert_config.isk_sign_data_path:
            user_data = load_binary(cert_config.isk_sign_data_path)
        isk_private_key = None
        if cert_config.isk_private_key_file:
            isk_private_key = load_private_key(cert_config.isk_private_key_file)
            assert isinstance(isk_private_key, EllipticCurvePrivateKeyWithSerialization)

        isk_cert = None
        if cert_config.isk_certificate:
            cert_data = load_binary(cert_config.isk_certificate)
            isk_cert = ECC.import_key(cert_data)

        ca_flag = not cert_config.use_isk
        cert_block = CertBlockV3(
            root_certs=root_certs, ca_flag=ca_flag,
            used_root_cert=cert_config.main_root_cert_id, constraints=cert_config.isk_constraint,
            isk_private_key=isk_private_key, isk_cert=isk_cert,  # type: ignore
            user_data=user_data
        )
        if cert_config.use_isk:
            signing_private_key_path = cert_config.isk_private_key_file
        else:
            signing_private_key_path = cert_config.main_root_private_key_file
        signature_provider = SignatureProvider.create(f'type=file;file_path={signing_private_key_path}')

    assert config.master_boot_output_file
    mbi = MasterBootImageN4Analog(
        app=app, load_addr=load_addr, image_type=image_type,
        trust_zone=trustzone, dual_boot_version=dual_boot_version,
        firmware_version=firmware_version,
        cert_block=cert_block,
        signature_provider=signature_provider
    )
    mbi_data = mbi.export()

    write_file(mbi_data, config.master_boot_output_file, mode='wb')
コード例 #53
0
    def verify(self, cert_chain: List[Cert], pub_key: bytes, nonce: bytes,
               sign: bytes):
        """
        TODO:

        cert_chain을 검증하고 pub_key의 서명을 확인함

        root issuer는 저장된 root ca에 대한 정보를 이용하여 확인

        cert chain 검증 결과 root ca로부터 연결된 신뢰 관계를 갖고 있을 경우 True 반환

        :param cert_chain:
        :param pub_key:
        :param nonce:
        :param sign:
        :return:
        """
        # public key 체인 확인
        pub = {self.root: True}
        for cert in cert_chain:
            if not pub.get(cert.issuer):
                return False
            public_key = ECC.import_key(cert.issuer)
            hash_value = SHA256.new(cert.public)
            verifier = DSS.new(public_key, 'fips-186-3')
            try:
                verifier.verify(hash_value, cert.sign)
                pub[cert.public] = True
            except:
                pass
        if not pub.get(pub_key):
            return False

        # sign 확인
        public_key = ECC.import_key(pub_key)
        hash_value = SHA256.new(nonce)
        verifier = DSS.new(public_key, 'fips-186-3')
        try:
            verifier.verify(hash_value, sign)
            return True
        except:
            return False
コード例 #54
0
def test_verify():
    key = ECC.generate(curve='P-256')
    admin = Address(bytes(key.export_key(format='DER')))
    block_header = BlockHeader(0,
                               SHA256.new(b'0').digest(),
                               SHA256.new(b'').digest(),
                               SHA256.new(b'').digest(), 1, 0)
    chain = BlockChain(
        Block(block_header, MerkleTree([]), {admin: 10000000}, {admin: -1}))
    chain.mining(new_transaction_list(chain, admin, key))
    assert chain.verify()
コード例 #55
0
def generate_keys():
    """Function that generate private and public keys using ECDSA algorithm
    """
    key = ECC.generate(curve='P-256')
    f = open('privatekey.pem', 'wt')
    f.write(key.export_key(format='PEM'))
    f.close()

    f = open('publickey.pem', 'wt')
    f.write(key.public_key().export_key(format='PEM'))
    f.close()
コード例 #56
0
    def test_export_private_pkcs8_and_pem_2(self):
        # PKCS8 inside PEM with PKCS8 encryption
        encoded = self.ref_private._export_private_encrypted_pkcs8_in_clear_pem("secret",
                              protection="PBKDF2WithHMAC-SHA1AndAES128-CBC")

        # This should prove that the output is password-protected
        self.assertRaises(ValueError, ECC.import_key, encoded)

        assert "ENCRYPTED PRIVATE KEY" in encoded

        decoded = ECC.import_key(encoded, "secret")
        self.assertEqual(self.ref_private, decoded)

        # ---

        encoded = self.ref_private.export_key(format="PEM",
                                         passphrase="secret",
                                         protection="PBKDF2WithHMAC-SHA1AndAES128-CBC")
        decoded = ECC.import_key(encoded, "secret")
        self.assertEqual(self.ref_private, decoded)
コード例 #57
0
    def test_export_private_pkcs8_and_pem_2(self):
        # PKCS8 inside PEM with PKCS8 encryption
        encoded = ref_private._export_private_encrypted_pkcs8_in_clear_pem("secret",
                              protection="PBKDF2WithHMAC-SHA1AndAES128-CBC")

        # This should prove that the output is password-protected
        self.assertRaises(ValueError, ECC.import_key, encoded)

        assert "ENCRYPTED PRIVATE KEY" in encoded

        decoded = ECC.import_key(encoded, "secret")
        self.assertEqual(ref_private, decoded)

        # ---

        encoded = ref_private.export_key(format="PEM",
                                         passphrase="secret",
                                         protection="PBKDF2WithHMAC-SHA1AndAES128-CBC")
        decoded = ECC.import_key(encoded, "secret")
        self.assertEqual(ref_private, decoded)
コード例 #58
0
    def test_compressed_curve(self):

        # Compressed P-256 curve (Y-point is even)
        pem1 = """-----BEGIN EC PRIVATE KEY-----
        MFcCAQEEIHTuc09jC51xXomV6MVCDN+DpAAvSmaJWZPTEHM6D5H1oAoGCCqGSM49
        AwEHoSQDIgACWFuGbHe8yJ43rir7PMTE9w8vHz0BSpXHq90Xi7/s+a0=
        -----END EC PRIVATE KEY-----"""

        # Compressed P-256 curve (Y-point is odd)
        pem2 = """-----BEGIN EC PRIVATE KEY-----
        MFcCAQEEIFggiPN9SQP+FAPTCPp08fRUz7rHp2qNBRcBJ1DXhb3ZoAoGCCqGSM49
        AwEHoSQDIgADLpph1trTIlVfa8NJvlMUPyWvL+wP+pW3BJITUL/wj9A=
        -----END EC PRIVATE KEY-----"""

        key1 = ECC.import_key(pem1)
        low16 = int(key1.pointQ.y % 65536)
        self.assertEqual(low16, 0xA6FC)

        key2 = ECC.import_key(pem2)
        low16 = int(key2.pointQ.y % 65536)
        self.assertEqual(low16, 0x6E57)
コード例 #59
0
def test_functionality():
    # generate a set of pk,sk pairs
    list_keys = {
        i: ECC.generate(curve='P-256')
        for i in xrange(10)
    }
    pk_dict = {k: v.public_key() for k,v in list_keys.items()}
    msg = 'HI Multiuser! in (test_functionality)'
    ctx = encrypt(pk_dict, msg)
    while list_keys:
        sk_dict = dict([list_keys.popitem()])
        _msg = decrypt(sk_dict, ctx)
        assert msg == _msg, "\n_msg={}\n msg={}\n".format(_msg, msg)
コード例 #60
0
def test_compute_id_w_saltctx():
    pwtypo = 'asdfadsfadf'
    list_keys = {
        i: ECC.generate(curve='P-256')
        for i in xrange(10)
    }
    pk_dict = {k: v.public_key() for k,v in list_keys.items()}
    salt = os.urandom(32)
    saltctx = encrypt(pk_dict, salt)
    id1 = compute_id_w_saltctx(pwtypo, dict([list_keys.popitem()]), saltctx)
    id2 = compute_id_w_saltctx(pwtypo, dict([list_keys.popitem()]), saltctx)
    assert isinstance(id1, int)
    assert id1 == id2