def test_loopback(self): hashed_msg = SHA512.new(b("test")) signer = DSS.new(self.key_priv, 'deterministic-rfc6979') signature = signer.sign(hashed_msg) verifier = DSS.new(self.key_pub, 'deterministic-rfc6979') verifier.verify(hashed_msg, signature)
def test_loopback(self): hashed_msg = SHA512.new(b("test")) signer = DSS.new(self.key_priv, 'fips-186-3') signature = signer.sign(hashed_msg) verifier = DSS.new(self.key_pub, 'fips-186-3') verifier.verify(hashed_msg, signature)
def test_sign_verify(self): """Verify public/private method""" self.description = "can_sign() test" signer = DSS.new(self.key_priv, 'fips-186-3') self.assertTrue(signer.can_sign()) signer = DSS.new(self.key_pub, 'fips-186-3') self.assertFalse(signer.can_sign())
def test_sign_verify(self): """Verify public/private method""" self.description = "can_sign() test" signer = DSS.new(self.key_priv, 'fips-186-3') self.failUnless(signer.can_sign()) signer = DSS.new(self.key_pub, 'fips-186-3') self.failIf(signer.can_sign())
def test_negative_unapproved_hashes(self): """Verify that unapproved hashes are rejected""" from Crypto.Hash import SHA1 self.description = "Unapproved hash (SHA-1) test" hash_obj = SHA1.new() signer = DSS.new(self.key_priv, 'fips-186-3') self.assertRaises(ValueError, signer.sign, hash_obj) self.assertRaises(ValueError, signer.verify, hash_obj, b("\x00") * 40)
def test2(self): for sig in self.signatures: tk = sig.test_key key = DSA.construct([tk.y, tk.g, tk.p, tk.q, tk.x], False) signer = DSS.new(key, 'deterministic-rfc6979') hash_obj = sig.module.new(sig.message) result = signer.sign(hash_obj) self.assertEqual(sig.result, result)
def test_verify(self, tv): self._id = "Wycheproof DSA Test #" + str(tv.id) hashed_msg = tv.hash_module.new(tv.msg) signer = DSS.new(tv.key, 'fips-186-3', encoding='der') try: signature = signer.verify(hashed_msg, tv.sig) except ValueError as e: if tv.warning: return assert not tv.valid else: assert tv.valid self.warn(tv)
def create_genesis_transaction(private_key, public_key): # TODO: I don't think the genesis transaction needs inputs. It's the genesis, where is it getting its money from? """ Create the genesis transaction. :param private_key: :param public_key: :return: """ hashed_address = SHA256.new(public_key.encode('utf-8')).hexdigest() transaction = { "input_count": 1, "inputs": [ { "transaction_id": '', "output_index": -1, "unlock": { "public_key": public_key, "signature": '', } } ], "output_count": 1, "outputs": [ { "address": hashed_address, "amount": 7000 } ] } # fill the unlock signature transaction_message = SHA256.new(( # compose transaction message str(transaction['inputs'][0]['transaction_id']) + # input id str(transaction['inputs'][0]['output_index']) + # output index str(hashed_address) + # hashed public key as address str(transaction['outputs']) # new outputs ).encode()) signer = DSS.new(private_key, 'fips-186-3') signature = signer.sign(transaction_message) # sign the message encoded = base64.b64encode(signature).decode() transaction['inputs'][0]['unlock']['signature'] = encoded transaction_id = SHA256.new( str(transaction).encode('utf-8')).hexdigest() transaction['transaction_id'] = transaction_id return Transaction(payload=transaction)
def verify(self): # TODO: Maybe rename this function to authenticate """ Verify an incoming transaction. 1) SHA256 hash the unspent transaction object's address and SHA256 hash this transaction's signature script key and see if they match. If they do, continue. Otherwise return false. 2) Compose the transaction's message consisting of: - input transaction ID - input output index - unspent transaction object's public key script (hashed pubkey) - this transaction's public key script (s)? - this transaction's output amount (s)? and check to see if this transaction's signature can be verified by the now authorized signature script key. :return: True if the transaction is valid, false otherwise """ authentic = True for tnx_input in self.inputs: # for each referenced input utxo = find_unspent_output(tnx_input['transaction_id'], tnx_input['output_index'], tnx_input['block_hash']) sig_key = SHA256.new( # get this transaction's unlock public key tnx_input['unlock']['public_key'].encode() ).hexdigest() if sig_key == utxo['address']: # if this node is the recipient of # the previous utxo transaction_message = SHA256.new(( # transaction message str(tnx_input['transaction_id']) + # input id str(tnx_input['output_index']) + # output index str(utxo['address']) + # hashed public key as address str(self.outputs) ).encode('utf-8')) ecc_key = import_public_key(tnx_input['unlock']['public_key']) signature = tnx_input['unlock']['signature'] decoded = base64.b64decode(signature.encode()) verifier = DSS.new(ecc_key, 'fips-186-3') try: verifier.verify(transaction_message, decoded) except ValueError: authentic = False break return authentic
def test_asn1_encoding(self): """Verify ASN.1 encoding""" self.description = "ASN.1 encoding test" hash_obj = SHA1.new() signer = DSS.new(self.key_priv, 'fips-186-3', 'der') signature = signer.sign(hash_obj) # Verify that output looks like a SEQUENCE self.assertEqual(bord(signature[0]), 48) signer.verify(hash_obj, signature) # Verify that ASN.1 parsing fails as expected signature = bchr(7) + signature[1:] self.assertRaises(ValueError, signer.verify, hash_obj, signature)
def test1(self): q = 0x4000000000000000000020108A2E0CC0D99F8A5EFL x = 0x09A4D6792295A7F730FC3F2B49CBC0F62E862272FL p = 2 * q + 1 y = pow(2, x, p) key = DSA.construct([pow(y, 2, p), 2L, p, q, x], False) signer = DSS.new(key, 'deterministic-rfc6979') # Test _int2octets self.assertEqual(hexlify(signer._int2octets(x)), b'009a4d6792295a7f730fc3f2b49cbc0f62e862272f') # Test _bits2octets h1 = SHA256.new(b"sample").digest() self.assertEqual(hexlify(signer._bits2octets(h1)), b'01795edf0d54db760f156d0dac04c0322b3a204224')
def verify_sig(sn, b64sig): # https://stackoverflow.com/posts/9807138/revisions missing_padding = len(b64sig) % 4 if missing_padding != 0: b64sig += '=' * (4 - missing_padding) sig = base64.urlsafe_b64decode(b64sig) h = SHA256.new(sn) verifier = DSS.new(ecc_public_key, 'fips-186-3') try: verifier.verify(h, sig) frint("The message is authentic.") return True except ValueError as e: frint("The message is not authentic: {}".format(e)) return False
def issue(self, pub_key: bytes): """ TODO: 자신의 certificate chain 과 issuer의 public key, holder의 public key와 public key의 Hash에 대한 서명을 가진 dictionary 반환 :param pub_key: :return: cert_chain: [ { issuer: pub_key0, public_key: pub_key1, sign: Signature0(Hash(pub_key1)) }, ... ] """ chain = copy.deepcopy(self.cert_chain) signer = DSS.new(self.__secret, 'fips-186-3') hash_value = SHA256.new(pub_key) sign = signer.sign(hash_value) chain.append(Cert(self.public_key(), pub_key, sign)) return chain
def test_verify(self, tv): self._id = "Wycheproof ECDSA Test #%d (%s)" % (tv.id, tv.comment) hashed_msg = tv.hash_module.new(tv.msg) signer = DSS.new(tv.key, 'fips-186-3', encoding='der') try: signature = signer.verify(hashed_msg, tv.sig) except ValueError as e: if tv.warning: return if tv.comment == "k*G has a large x-coordinate": return assert not tv.valid else: assert tv.valid self.warn(tv)
def isValid(self): global signature if isinstance(self.key, str): #系统发放的矿工奖励跳过验证 return True try: verifer = DSS.new(self.key.public_key(), 'fips-186-3') #使用公钥创建校验对象 hasher = self.calculateHash() verifer.verify(hasher, signature) self.key = str(self.key) #self.signature = str(self.signature) # The signnature is valid. return True except (ValueError, TypeError): print('The signature is not valid.') return False
def check(self, signature: int): # Convert back to bytes sig = Conversion.IP2OS(signature) # Verifier setup ecc = ECC.import_key(self.pubk) verifier = DSS.new(ecc, 'fips-186-3') new_hash = SHA256.new(bytes.fromhex(self.y)) # We need to verify the signature on the hash. The verifier throws an exception if it doesn't verify. try: verifier.verify(new_hash, sig) return True except Exception as e: print(str(e), file=sys.stderr) return False
def test1(self): q = 0x4000000000000000000020108A2E0CC0D99F8A5EF x = 0x09A4D6792295A7F730FC3F2B49CBC0F62E862272F p = 2 * q + 1 y = pow(2, x, p) key = DSA.construct([pow(y, 2, p), 2, p, q, x], False) signer = DSS.new(key, 'deterministic-rfc6979') # Test _int2octets self.assertEqual(hexlify(signer._int2octets(x)), b'009a4d6792295a7f730fc3f2b49cbc0f62e862272f') # Test _bits2octets h1 = SHA256.new(b"sample").digest() self.assertEqual(hexlify(signer._bits2octets(h1)), b'01795edf0d54db760f156d0dac04c0322b3a204224')
def test6(self): """Verify ASN.1 encoding""" self.description = "ASN.1 encoding test" key = DSA.construct((self.Y, self.G, self.P, self.Q, self.X)) hash_obj = SHA1.new() signer = DSS.new(key, 'fips-186-3', 'der') signature = signer.sign(hash_obj) # Verify that output looks like a SEQUENCE self.assertEqual(bord(signature[0]), 48) signer.verify(hash_obj, signature) # Verify that ASN.1 parsing fails as expected signature = bchr(7) + signature[1:] self.assertRaises(ValueError, signer.verify, hash_obj, signature)
def sign(message, private_key_directory): """Function that sign data with ECDSA algorithm Args: message (string): data private_key_directory (private_key): directory to PEM file Returns: Object: Signature """ private_key = ECC.import_key(open(private_key_directory).read()) h = SHA256.new(message.encode()) signer = DSS.new(private_key, 'fips-186-3') signature = signer.sign(h) return signature
def verify(self): # TODO: Maybe rename this function to authenticate """ Verify an incoming transaction. 1) SHA256 hash the unspent transaction object's address and SHA256 hash this transaction's signature script key and see if they match. If they do, continue. Otherwise return false. 2) Compose the transaction's message consisting of: - input transaction ID - input output index - unspent transaction object's public key script (hashed pubkey) - this transaction's public key script (s)? - this transaction's output amount (s)? and check to see if this transaction's signature can be verified by the now authorized signature script key. :return: True if the transaction is valid, false otherwise """ authentic = True for tnx_input in self.inputs: # for each referenced input utxo = find_unspent_output(tnx_input['transaction_id'], tnx_input['output_index'], tnx_input['block_hash']) sig_key = SHA256.new( # get this transaction's unlock public key tnx_input['unlock']['public_key'].encode()).hexdigest() if sig_key == utxo['address']: # if this node is the recipient of # the previous utxo transaction_message = SHA256.new(( # transaction message str(tnx_input['transaction_id']) + # input id str(tnx_input['output_index']) + # output index str(utxo['address']) + # hashed public key as address str(self.outputs)).encode('utf-8')) ecc_key = import_public_key(tnx_input['unlock']['public_key']) signature = tnx_input['unlock']['signature'] decoded = base64.b64decode(signature.encode()) verifier = DSS.new(ecc_key, 'fips-186-3') try: verifier.verify(transaction_message, decoded) except ValueError: authentic = False break return authentic
async def verifySignature(signature, publicKey, data): data = data.copy() data.pop("signature") data = json.dumps(data) publicKey = publicKey.split(" ") publicKey = "-----BEGIN PUBLIC KEY-----\n" + publicKey[ 0] + "\n" + publicKey[1] + "\n-----END PUBLIC KEY-----" publicKey = ECC.import_key(publicKey) signature = (int(signature, 16)).to_bytes(64, byteorder="little") data = SHA256.new(data.encode("utf-8")) verifier = DSS.new(publicKey, "fips-186-3") try: verifier.verify(data, signature) return True except ValueError: return False
def run_test_ecdsa_sign_random(): init_dmem() randkey = ECC.generate(curve='P-256') randd = int(randkey.d.to_bytes(32).hex(), 16) randk = int( Integer.random_range( min_inclusive=1, max_exclusive=P256_CURVE_ORDER).to_bytes(32).hex(), 16) rres, sres = run_sign(randd, randk, msg_digest_int) rresb = rres.to_bytes(32, byteorder='big', signed=False) sresb = sres.to_bytes(32, byteorder='big', signed=False) rsresb = b''.join([rresb, sresb]) verifier = DSS.new(randkey, 'fips-186-3') try: verifier.verify(msg_digest, rsresb) except ValueError: raise Exception('ECDSA sign (random) failed')
def is_valid(self): # The transaction is about mining. if self.from_address is None: return True # There is no signature. if self.sign_obj == None: return 'Your signature is empty.' # Regard the from address as the public key. verifer = DSS.new(self.from_address, 'fips-186-3') hasher = self.calculate_hash() # Verify the signature. try: verifer.verify(hasher, self.sign_obj) return True except: print('Someone tampers the signature.') return False
def verify(signature): file = open("public_key.pem", "r") flag = False pub_key = DSA.import_key(file.read()) verifier = DSS.new(pub_key, 'fips-186-3') for password in in_memory_password: hash_obj = SHA256.new(password.encode('utf-8')) try: verifier.verify(hash_obj, signature) flag = True break except ValueError: pass if flag: print("You are authenticated!") else: print("You are not authenticated!")
def _sign_with_dss(message: bytes, key: Union[DSA.DsaKey, ECC.EccKey]) -> dict: """Sign a bytes message with a private DSA or ECC key. We use the `fips-186-3` mode for the signer because signature is randomized, while it is not the case for the mode `deterministic-rfc6979`. :param message: the bytestring to sign :param private_key: the private key :return: signature dict with keys "digest" (bytestring) and "timestamp_utc" (integer)""" timestamp = _get_utc_timestamp() hash_payload = _compute_timestamped_hash(message=message, timestamp_utc=timestamp) signer = DSS.new(key, "fips-186-3") digest = signer.sign(hash_payload) signature = {"timestamp_utc": timestamp, "digest": digest} return signature
def ecc_sign(self, private_key: Union[ECC.EccKey, bytes], data: bytes, algorithm: str = None) -> bytes: """Sign data using (EC)DSA. :param private_key: ECC private key, either as EccKey or bytes :param data: Data to sign :param algorithm: Hash algorithm, if None the hash length is determined from ECC curve size :return: Signature, r and s coordinates as bytes """ key = private_key if isinstance( private_key, ECC.EccKey) else ECC.import_key(private_key) hash_name = algorithm or f"sha{key.pointQ.size_in_bits()}" hasher = self._get_algorithm(name=hash_name, data=data) signer = DSS.new(key, mode="deterministic-rfc6979") return signer.sign(hasher)
def DSAe(): print("Generating DSA Times") f = open("DSA.txt", "r") times = list() for x in range(10): t_start = time() tupkey = (int(f.readline(), 16), int(f.readline(), 16), int(f.readline(), 16), int(f.readline(), 16), int(f.readline(), 16)) key = DSA.construct(tupkey) h = SHA256.new(str.encode(f.readline())) signer = DSS.new(key, 'fips-186-3') a = signer.sign(h) t_final = time() total_time = t_final - t_start times.append(total_time) return times
def verify_file(input_file, size, signature_file): signature = open(signature_file, 'rb').read() hash_object = SHA1.new() with open(input_file, 'rb') as file: chunk = 0 while chunk != b'': chunk = file.read(size) hash_object.update(chunk) with open('public_key.pem', 'rb') as f: public_key = DSA.importKey(f.read()) verifier = DSS.new(public_key, 'fips-186-3') try: verifier.verify(hash_object, signature) return "Verified" except ValueError: return "Not verified"
def verify_transaction_signature(self): if self.transaction_type == 1: return wallet = BlockChain().get_output_from_input(self.inputs[0]).wallet pubkey = ECC.import_key(bytes.fromhex(wallet)) verifier = DSS.new(pubkey, "fips-186-3") signature = self.signature self.signature = 0 hash_ = SHA256.new(self.serialize()) self.signature = signature try: verifier.verify(hash_, signature.to_bytes(64, "little")) except ValueError as check_fail: raise SecretError("Invalid transaction signature")
def unlock_inputs(self, private_key, public_key): """ Unlock previous unspent transaction outputs for a new transaction. Compose a transaction message consisting of: - input transaction ID - input output index - unspent transaction object's public key script (hashed pubkey) - this transaction's public key script (s)? - this transaction's output amount (s)? and sign it with this node's private key. Place a dict consisting of {key: public_key, sig: signature} in the corresponding input at "unlock" where `public_key` is this node's full public key and `signature` is the signed transaction message. """ if self.unused_amount != 0: # use up all input amounts (change) hash_address = SHA256.new(public_key.encode('utf-8')).hexdigest() self.outputs.append({ "address": hash_address, "amount": self.unused_amount }) self.output_count += 1 self.unused_amount = 0 for tnx_input in self.inputs: # for each input utxo = find_unspent_output(tnx_input['transaction_id'], tnx_input['output_index'], tnx_input['block_hash']) if utxo: transaction_message = SHA256.new(( # compose message str(tnx_input['transaction_id']) + str(tnx_input['output_index']) + str(utxo['address']) + # hashed public key address str(self.outputs) ).encode('utf-8')) signer = DSS.new(private_key, 'fips-186-3') signature = signer.sign(transaction_message) encoded = base64.b64encode(signature).decode() unlock = { # create unlocking portion of the transaction "public_key": public_key, "signature": encoded } tnx_input['unlock'] = unlock # assign to input. else: # TODO: raise error print("Invalid input found for {}".format(tnx_input))
def verify_transaction_signature(self): # Check if the transaction signature is valid # i.e. does the signature match the Transaction object. # Note: This might not make too much sense given the way we # create transactions in this tutorial. # But in case we get transaction data # from a remote point, this is important! public_key = ECC.import_key(binascii.unhexlify(self.sender)) verifier = DSS.new(public_key, 'fips-186-3') h = SHA256.new(str(self.odict_transaction()).encode('utf8')) try: verifier.verify(h, binascii.unhexlify(self.signature)) return (True) # In case the signature is no authentic, the verifier throws a ValueError except ValueError: return (False)
def unlock_inputs(self, private_key, public_key): """ Unlock previous unspent transaction outputs for a new transaction. Compose a transaction message consisting of: - input transaction ID - input output index - unspent transaction object's public key script (hashed pubkey) - this transaction's public key script (s)? - this transaction's output amount (s)? and sign it with this node's private key. Place a dict consisting of {key: public_key, sig: signature} in the corresponding input at "unlock" where `public_key` is this node's full public key and `signature` is the signed transaction message. """ if self.unused_amount != 0: # use up all input amounts (change) hash_address = SHA256.new(public_key.encode('utf-8')).hexdigest() self.outputs.append({ "address": hash_address, "amount": self.unused_amount }) self.output_count += 1 self.unused_amount = 0 for tnx_input in self.inputs: # for each input utxo = find_unspent_output(tnx_input['transaction_id'], tnx_input['output_index'], tnx_input['block_hash']) if utxo: transaction_message = SHA256.new(( # compose message str(tnx_input['transaction_id']) + str(tnx_input['output_index']) + str(utxo['address']) + # hashed public key address str(self.outputs)).encode('utf-8')) signer = DSS.new(private_key, 'fips-186-3') signature = signer.sign(transaction_message) encoded = base64.b64encode(signature).decode() unlock = { # create unlocking portion of the transaction "public_key": public_key, "signature": encoded } tnx_input['unlock'] = unlock # assign to input. else: # TODO: raise error print("Invalid input found for {}".format(tnx_input))
def create_genesis_transaction(private_key, public_key): # TODO: I don't think the genesis transaction needs inputs. It's the genesis, where is it getting its money from? """ Create the genesis transaction. :param private_key: :param public_key: :return: """ hashed_address = SHA256.new(public_key.encode('utf-8')).hexdigest() transaction = { "input_count": 1, "inputs": [{ "transaction_id": '', "output_index": -1, "unlock": { "public_key": public_key, "signature": '', } }], "output_count": 1, "outputs": [{ "address": hashed_address, "amount": 7000 }] } # fill the unlock signature transaction_message = SHA256.new(( # compose transaction message str(transaction['inputs'][0]['transaction_id']) + # input id str(transaction['inputs'][0]['output_index']) + # output index str(hashed_address) + # hashed public key as address str(transaction['outputs']) # new outputs ).encode()) signer = DSS.new(private_key, 'fips-186-3') signature = signer.sign(transaction_message) # sign the message encoded = base64.b64encode(signature).decode() transaction['inputs'][0]['unlock']['signature'] = encoded transaction_id = SHA256.new(str(transaction).encode('utf-8')).hexdigest() transaction['transaction_id'] = transaction_id return Transaction(payload=transaction)
def _is_signed_by(account: Union[AccountId, str], message: str, signature: str) -> bool: """Check whether account has signed message with signature""" try: signature = base64.b64decode(signature) except Exception: raise ValueCommandException(signature) msg_hash = SHA3_512.new(message.strip().encode('utf-8')) for key in account.list_public_keys(): verifier = DSS.new(key, 'fips-186-3') try: verifier.verify(msg_hash, signature) return True except ValueError: pass return False
def verify(self): try: output = BlockChain().get_output_from_input(self) pubkey = ECC.import_key(bytes.fromhex(output.wallet)) except Exception as error: raise InvalidOutputReferenceError from error verifier = DSS.new(pubkey, "fips-186-3") # privkey = ECC.import_key(key) # signer = DSS.new(privkey, "fips-186-3") hash_ = SHA256.new(output.serialize()) try: verifier.verify(hash_, self.signature.to_bytes(64, "little")) except ValueError as check_fail: raise SecretError from check_fail
def validate_wallet_signature(msg, wallet_pubkey, signature): """ :param msg: :param wallet_pubkey: :param signature: :return: """ if signature is None: print( "Signature is None. probably cause something other than a string or byte being passed to signer" ) return False try: x_int = base64.b85decode(wallet_pubkey["x"].encode()) x_int = int.from_bytes(x_int, "big") y_int = base64.b85decode(wallet_pubkey["y"].encode()) y_int = int.from_bytes(y_int, "big") except KeyError: return False except Exception as e: print(f"in DigitalsignerValidator: {e}") return False signature = signature.encode() signature = base64.b85decode(signature) # if it a string try: hash_of_message = SHA256.new(msg) except TypeError: hash_of_message = SHA256.new(msg.encode()) try: wallet_pubkey = ECC.construct(point_x=x_int, point_y=y_int, curve="P-256").public_key() verifier = DSS.new(wallet_pubkey, mode="fips-186-3") verifier.verify(hash_of_message, signature=signature) except ValueError: return False else: return True
def get_signature(jws, payload): global PRIVATE_KEY if payload is not "": payload = json.dumps(payload, separators=(',', ':')) jws = json.dumps(jws, separators=(',', ':')) if PRIVATE_KEY is None: raise Exception("Private key not set") else: # RFC 7518 => signing a jws # message_to_be_signed = json_to_rfc7519(jws) + "." + json_to_rfc7519( payload) h = SHA256.new(bytes(message_to_be_signed, "ASCII")) signer = DSS.new(PRIVATE_KEY, 'fips-186-3') signature = base64.urlsafe_b64encode( signer.sign(h)).decode("ASCII").strip("=") return signature
def verify_msg(msg, sig, key_str): try: signature = bytes.fromhex(sig) except Exception as e: print("verify_msg", e) return False try: key = ECC.import_key(key_str) verifier = DSS.new(key, 'fips-186-3') h = SHA256.new(msg.encode('utf8')) print(h.hexdigest()) except Exception as e: print("verify_msg", e) return False try: verifier.verify(h, signature) return True except ValueError: return False
def validate(msg, pubkey: dict, signature): """ used to validate signature :param msg: string or byte string, message to validate signature(assignment statements, token transfers etc) :param signature: bytes string or hex string :param pubkey: {"x": base85 string, "y": base85 string} # use base64.b85decode(pubkey["x"}.encode) to get pubkey bytes :type pubkey: dict :return: """ if signature is None: print( "Signature is None. probably cause something other than a string or byte being passed to signer" ) return False try: x_int = base64.b85decode(pubkey["x"].encode()) x_int = int.from_bytes(x_int, "big") y_int = base64.b85decode(pubkey["y"].encode()) y_int = int.from_bytes(y_int, "big") except KeyError: return False signature = signature.encode() signature = base64.b85decode(signature) # if it a string try: hash_of_message = SHA256.new(msg) except TypeError: hash_of_message = SHA256.new(msg.encode()) try: pubkey = ECC.construct(point_x=x_int, point_y=y_int, curve="P-256").public_key() verifier = DSS.new(pubkey, mode="fips-186-3") verifier.verify(hash_of_message, signature=signature) except ValueError: return False else: return True
def sign(): """ (cert.json) 인증서에 공개키와 서명을 저장 Sign: sign( Hash ( student_id | is_success | week ) ) 서명은 bytes 값의 .hex()를 이용해 string으로 저장 공개키는 .export_key(format='PEM')을 이용해 PEM 형태로 저장 :return: None """ cert = load() private_key = ECC.generate(curve='P-256') public = private_key.public_key() signer = DSS.new(private_key, 'fips-186-3') hash_value = SHA256.new((cert['student_id'] + cert['is_success'] + str(cert['week'])).encode('utf-8')) cert['public_key'] = public.export_key(format='PEM') cert['sign'] = signer.sign(hash_value).hex() print(cert) save(cert)
def wallet_sign(wallet_privkey, message): """ static method used to sign with wallet privkey. used in conjunction with WalletService class :param wallet_privkey: private key of wallet, already imported key :param message: byte string,message to be signed, usually bytes of signature of client private key :return: base85 string, digital signature """ if not isinstance(message, (bytes, str)): return None elif isinstance(message, str): message = message.encode() hash_of_message = SHA256.new(message) signer = DSS.new(wallet_privkey, mode="fips-186-3") digital_signature = signer.sign(hash_of_message) digital_signature = base64.b85encode(digital_signature).decode() return digital_signature
def sign(self, message): """ signs message with private key of username :param message: bytes string or string :return: bytes; signature of message using private key """ # if not already a byte string turn it to making sure if not isinstance(message, (bytes, str)): return None elif isinstance(message, str): message = message.encode() hash_of_message = SHA256.new(message) signer = DSS.new(self.privkey, mode="fips-186-3") digital_signature = signer.sign(hash_of_message) digital_signature = base64.b85encode(digital_signature).decode() return digital_signature
"""This module helps user sign a file using DSS standard.""" from Crypto.Signature import DSS from Crypto.Hash import SHA256 from Crypto.PublicKey import DSA message = 'To be signed' key = DSA.importKey(open('dsa_key.bin').read()) h = SHA256.new(message) signer = DSS.new(key, 'fips-186-3') signature = signer.sign(h) print signature f = open("signature.bin", "wb") f.write(signature)
"""This module verifies a signature signed using DSS standard.""" from Crypto.Signature import DSS from Crypto.Hash import SHA256 from Crypto.PublicKey import DSA message = 'To be signed' key = DSA.importKey(open('pubkey.bin').read()) h = SHA256.new(message) verifier = DSS.new(key, 'fips-186-3') f = open("signature.bin", "rb") signature = f.read() try: verifier.verify(h, signature) print "The signature is authentic." except (ValueError, TypeError): print "The signature is not authentic."
if isinstance(tv, str): res = re.match("\[mod = L=([0-9]+), N=([0-9]+), ([a-zA-Z0-9-]+)\]", tv) hash_name = res.group(3).replace("-", "") hash_module = load_hash_by_name(hash_name) continue if hasattr(tv, "p"): modulus = tv.p generator = tv.g suborder = tv.q continue hash_obj = hash_module.new(tv.msg) key = DSA.construct([bytes_to_long(x) for x in (tv.y, generator, modulus, suborder)], False) verifier = DSS.new(key, 'fips-186-3') def positive_test(self, verifier=verifier, hash_obj=hash_obj, signature=tv.r+tv.s): verifier.verify(hash_obj, signature) def negative_test(self, verifier=verifier, hash_obj=hash_obj, signature=tv.r+tv.s): self.assertRaises(ValueError, verifier.verify, hash_obj, signature) if tv.result == 'p': setattr(FIPS_DSA_Tests, "test_verify_positive_%d" % idx, positive_test) else: setattr(FIPS_DSA_Tests, "test_verify_negative_%d" % idx, negative_test) test_vectors_sign = load_tests(("Crypto", "SelfTest", "Signature", "test_vectors", "DSA"), "FIPS_186_3_SigGen.txt",
def test_data_rfc6979(self): signer = DSS.new(self.key_priv, 'deterministic-rfc6979') for message, k, r, s, module in self.signatures: hash_obj = module.new(message) result = signer.sign(hash_obj) self.assertEqual(r + s, result)