Пример #1
0
def get_msg_with_decrypt():
    with open('wallet-5000.txt', mode='r') as f:
        keys = f.readlines()
        public_key = keys[0][:-1]
        private_key = keys[1]
    with open('blockchain-5000.txt', 'r') as f:
        file_content = f.readlines()
        blockchain = json.loads(file_content[0][:-1])
        for block in blockchain[::-1]:
            for transactions in block['transactions']:
                if transactions['recipient'] == public_key:
                    msg_encrypt = transactions['msg_to(recipient)']
                    msg_decrypt = rsa.decrypt(
                        ast.literal_eval(msg_encrypt),
                        PKCS1_v1_5.new(
                            RSA.importKey(
                                binascii.unhexlify(wallet.private_key))))
                    return msg_decrypt.decode('utf-8')
                if transactions['sender'] == public_key:
                    msg_encrypt = transactions['msg_from(sender)']
                    msg_decrypt = rsa.decrypt(
                        ast.literal_eval(msg_encrypt),
                        PKCS1_v1_5.new(
                            RSA.importKey(
                                binascii.unhexlify(wallet.private_key))))
                    return msg_decrypt.decode('utf-8')
Пример #2
0
def sign_rsa(timestamp, address, recipient, amount, operation, openfield, key,
             public_key_hashed):
    from Cryptodome.Signature import PKCS1_v1_5
    from Cryptodome.Hash import SHA

    if not key:
        raise BaseException(
            "The wallet is locked, you need to provide a decrypted key")

    transaction = (str(timestamp), str(address), str(recipient),
                   '%.8f' % float(amount), str(operation), str(openfield)
                   )  # this is signed, float kept for compatibility

    h = SHA.new(str(transaction).encode())
    signer = PKCS1_v1_5.new(key)
    signature = signer.sign(h)
    signature_enc = base64.b64encode(signature)

    verifier = PKCS1_v1_5.new(key)
    if verifier.verify(h, signature):
        return_value = str(timestamp), str(address), str(
            recipient), '%.8f' % float(amount), str(
                signature_enc.decode("utf-8")), str(
                    public_key_hashed.decode("utf-8")), str(operation), str(
                        openfield)  # float kept for compatibility
    else:
        return_value = False

    return return_value
Пример #3
0
    def runTest(self):
        key = RSA.importKey(PKCS1_15_NoParams.rsakey)
        hashed = SHA1.new(b("Test"))
        good_signature = PKCS1_v1_5.new(key).sign(hashed)
        verifier = PKCS1_v1_5.new(key.publickey())

        self.assertEqual(verifier.verify(hashed, good_signature), True)

        # Flip a few bits in the signature
        bad_signature = strxor(good_signature, bchr(1) * len(good_signature))
        self.assertEqual(verifier.verify(hashed, bad_signature), False)
    def runTest(self):
        key = RSA.importKey(PKCS1_15_NoParams.rsakey)
        hashed = SHA1.new(b("Test"))
        good_signature = PKCS1_v1_5.new(key).sign(hashed)
        verifier = PKCS1_v1_5.new(key.publickey())

        self.assertEqual(verifier.verify(hashed, good_signature), True)

        # Flip a few bits in the signature
        bad_signature = strxor(good_signature, bchr(1) * len(good_signature))
        self.assertEqual(verifier.verify(hashed, bad_signature), False)
def sign_message_with_key(message: str, key):
    # Sign with key - This is a helper function
    # Returns the b64 encoded sig as a string
    h = SHA.new(message.encode('utf-8'))
    signer = PKCS1_v1_5.new(key)
    signature = signer.sign(h)
    signature_enc = base64.b64encode(signature)
    verifier = PKCS1_v1_5.new(key)
    if verifier.verify(h, signature):
        # print("OK")
        return signature_enc.decode("utf-8")
    else:
        return False
Пример #6
0
    def send(self, wallet, recipient, amount, openfield='', operation=0):
        if (len(wallet.pub_key)) != 271 and (len(wallet.pub_key)) != 799:
            raise ValueError("Invalid public key length: {}".format(len(wallet.pub_key)))

        public_key_hashed = base64.b64encode(wallet.pub_key.encode('utf-8'))

        print("Sending from address: {}".format(wallet.address))

        # Pulled from essentials.py
        fee = Decimal("0.01") + (Decimal(len(openfield)) / Decimal("100000"))  # 0.01 dust
        print("Paying Fee: {}".format(fee))

        if float(amount) < 0:
            raise Exception("Cannot send negative amounts")

        if len(str(recipient)) != 56:
            raise Exception("Wrong address length")

        timestamp = '%.2f' % time.time()
        sig_dat = (
            str(timestamp),
            str(wallet.address),
            str(recipient),
            '%.8f' % float(amount),
            str(operation),
            str(openfield))

        sig_dat_hash = SHA.new(str(sig_dat).encode("utf-8"))
        signer = PKCS1_v1_5.new(wallet.key)
        signature = signer.sign(sig_dat_hash)
        signature_enc = base64.b64encode(signature)
        txid = signature_enc[:56]

        print("Encoded Signature: {}".format(signature_enc.decode("utf-8")))
        print("Transaction ID: {}".format(txid.decode("utf-8")))

        verifier = PKCS1_v1_5.new(wallet.key)
        if not verifier.verify(sig_dat_hash, signature):
            raise Exception("Invalid signature was generated")

        tx_submit = (
            str(timestamp),
            str(wallet.address),
            str(recipient),
            '%.8f' % float (amount),
            str(signature_enc.decode("utf-8")),
            str(public_key_hashed.decode("utf-8")),
            str(operation),
            str(openfield))
        reply = self.command("mpinsert", [tx_submit])
        print("Node responded with: {}".format(reply))
Пример #7
0
def anonymize(tx_count, per_tx, remainder, anon_recipient, identifier, anon_sender):
    # return remainder to source!
    a.execute("SELECT * FROM transactions WHERE openfield = ?", (identifier,))
    
    try:
        exists = a.fetchall()[0]
    except:#if payout didn't happen yet
        print(tx_count, per_tx, remainder, identifier)
        
        for tx in range(tx_count):
            #construct tx
            openfield = "mixer"
            operation = 0
            fee = fee_calculate(openfield)

            timestamp = '%.2f' % time.time()
            transaction = (str(timestamp),
                           str(address),
                           str(anon_recipient),
                           '%.8f' % float(per_tx - fee),
                           str(operation),
                           str(openfield))  # this is signed
           

            h = SHA.new(str(transaction).encode("utf-8"))
            signer = PKCS1_v1_5.new(key)
            signature = signer.sign(h)
            signature_enc = base64.b64encode(signature)
            print("Encoded Signature: {}".format(signature_enc.decode("utf-8")))

            verifier = PKCS1_v1_5.new(key)
            if verifier.verify(h, signature):
                print("The signature is valid, proceeding to save transaction to mempool")
                
            #construct tx
            a.execute("INSERT INTO transactions VALUES (?,?,?,?,?,?,?,?)", (str(timestamp), str(address), str(anon_recipient), '%.8f' % float(per_tx - fee), str(signature_enc.decode("utf-8")), str(public_key_hashed), str(operation), str(identifier)))
            anon.commit()
            m.execute("INSERT INTO transactions VALUES (?,?,?,?,?,?,?,?)", (str(timestamp), str(address), str(anon_recipient), '%.8f' % float(per_tx - fee), str(signature_enc.decode("utf-8")), str(public_key_hashed), str(operation), str(openfield)))
            mempool.commit()


        if (remainder - fee) > 0:
            openfield = "mixer"
            operation = 0
            fee = fee_calculate(openfield)
            timestamp = '%.2f' % time.time()
            transaction = (str(timestamp), str(address), str(anon_sender), '%.8f' % float(remainder - fee), str(operation), str(openfield))  # this is signed
            m.execute("INSERT INTO transactions VALUES (?,?,?,?,?,?,?,?)", (str(timestamp), str(address), str(anon_sender), '%.8f' % float(remainder - fee), str(signature_enc.decode("utf-8")), str(public_key_hashed), str(operation), str(openfield)))
            mempool.commit()
    return
Пример #8
0
 def _verify(self, message, signature):
     '''
     验证返回签名是否正确
     :param message:
     :param signature:
     :return:
     '''
     # 开始计算签名
     key = RSA.import_key(ALIPAY_KEY)
     h = SHA256.new(message.encode())
     try:
         PKCS1_v1_5.new(key).verify(h, signature)
         return True
     except:
         return False
Пример #9
0
 def sign(self):
     key = RSA.importKey(self.priKey)
     signer = PKCS1_v1_5.new(key)
     h = MD5.new(self.passwd)
     signature = signer.sign(h)
     code = base64.urlsafe_b64encode(signature)
     return code.decode()
Пример #10
0
def sign_request(private_key: RsaKey, body_bytes: bytes) -> str:
    signer = PKCS1_v1_5.new(private_key)
    digest = SHA256.new()
    digest.update(body_bytes)
    sign = signer.sign(digest)

    return b64encode(sign)
Пример #11
0
def proceed_signature(data, private_key):
    digest = SHA256.new()
    digest.update(data)

    signer = PKCS1_v1_5.new(private_key)
    sign = signer.sign(digest)
    return sign
Пример #12
0
    def parse(self, data: (bytes, bytearray)) -> (bytes, bytearray):
        global REQUEST_PRV_KEY

        self.enc_output = data

        iv = data[:16]

        cipher = AES.new(REQUEST_SECRET, AES.MODE_CBC, iv)
        enc_data = data[16:]  # array + signature
        dec_data = unpad(cipher.decrypt(enc_data), AES.block_size)

        body = dec_data[:
                        -REQUEST_PRV_KEY.size_in_bytes()]  # UNIQUE_MAGIC + DNA
        self.signature = dec_data[-REQUEST_PRV_KEY.size_in_bytes():]

        # verify file magic
        assert body[:4] == REQUEST_MAGIC, "Invalid update request magic"

        # verify signature
        verifier = PKCS1_v1_5.new(REQUEST_PRV_KEY)
        assert verifier.verify(SHA1.new(body),
                               self.signature), "Invalid signature"

        (magic, self.dna, self.sys_fw_ver, self.ver_code,
         self.pcba_rev) = unpack("<4s 16s 3I", body)
        self.serial = hexlify(self.dna)
Пример #13
0
 def sign_tx(self, sender, recipient, amount):
     signer = PKCS1_v1_5.new(
         RSA.importKey(binascii.unhexlify(self.private_key)))
     h = SHA256.new(
         (str(sender) + str(recipient) + str(amount)).encode('utf8'))
     signature = signer.sign(h)
     return binascii.hexlify(signature).decode('ascii')
Пример #14
0
    def signTransIN(self, transaction: Transaction, transInIndex: int,
                    aUnspentOutTrans: UnspentOutTrans, privkey):

        transIN: TransIN = transaction.transINs[transInIndex]
        dataToSign = str(transaction.transID)
        referencedUnspentOutTrans = TransMethods.findUnspentOutTrans(
            self, transIN.transOutId, transIN.transOutIndex, aUnspentOutTrans)

        if referencedUnspentOutTrans is None:
            raise ValueError("could not find referenced transOUT")

        private = RSA.importKey(privkey)
        referencedAddress = referencedUnspentOutTrans.address
        public = private.publickey().exportKey()
        if public != referencedAddress:
            raise ValueError(
                'trying to sign an input with private' +
                ' key that does not match the address that is referenced in transIN'
            )

        key_to_sign = private

        signer = PKCS1_v1_5.new(key_to_sign)
        newHash = SHA256.new()
        # It's being assumed the data is base64 encoded, so it's decoded before updating the digest
        newHash.update(dataToSign.encode("utf-8"))

        # Return singature:
        signature: str = signer.sign(newHash)

        return signature
Пример #15
0
def _sign_message(token: str, body: str) -> t.Tuple[str, str]:
    key = RSA.generate(1024, e=int("10001", 16))
    signer = PKCS1_v1_5.new(key)
    digest = SHA1.new()
    digest.update(f"X-AuthToken:{token}{body}".encode("utf-8"))
    signature = signer.sign(digest)
    return signature.hex(), f"{key.n:x}"
Пример #16
0
def jwksEmbed(headDict, paylDict):
    newHead = headDict
    pubKey, privKey = newRSAKeyPair()
    new_key = RSA.importKey(pubKey)
    n = base64.urlsafe_b64encode(new_key.n.to_bytes(256, byteorder='big'))
    e = base64.urlsafe_b64encode(new_key.e.to_bytes(3, byteorder='big'))
    jwkbuild = {}
    jwkbuild["kty"] = "RSA"
    jwkbuild["kid"] = "jwt_tool"
    jwkbuild["use"] = "sig"
    jwkbuild["e"] = str(e.decode('UTF-8'))
    jwkbuild["n"] = str(n.decode('UTF-8').rstrip("="))
    newHead["jwk"] = jwkbuild
    newHead["alg"] = "RS256"
    key = RSA.importKey(privKey)
    newContents = base64.urlsafe_b64encode(json.dumps(newHead, separators=(",", ":")).encode()).decode('UTF-8').strip(
        "=") + "." + base64.urlsafe_b64encode(json.dumps(paylDict, separators=(",", ":")).encode()).decode(
        'UTF-8').strip("=")
    newContents = newContents.encode('UTF-8')
    h = SHA256.new(newContents)
    signer = PKCS1_v1_5.new(key)
    try:
        signature = signer.sign(h)
    except:
        print("Invalid Private Key")
    newSig = base64.urlsafe_b64encode(signature).decode('UTF-8').strip("=")
    badSig = base64.b64encode(signature).decode('UTF-8').strip("=")
    print("---------------Test CVE-2018-0114  New  injected token: ------------- ")
    print(newContents + "." + newSig)
    print(newContents + "." + badSig)
Пример #17
0
 def sign_transaction(self, sender, recepient, amount):
     signer = PKCS1_v1_5.new(
         RSA.importKey(binascii.unhexlify(self.__private_key)))
     payload = SHA256.new(
         (str(sender) + str(recepient) + str(amount)).encode("utf8"))
     signature = signer.sign(payload)
     return binascii.hexlify(signature).decode("ascii")
Пример #18
0
def sign_rsa(timestamp: float, address: str, recipient: str, amount: int,
             operation: str, openfield: str, key):
    # Sign with key - This is a helper function
    # Returns the encoded sig as a string
    as_string = stringify_transaction(timestamp, address, recipient, amount,
                                      operation, openfield)
    print("As String", as_string)
    h = SHA.new(as_string)
    signer = PKCS1_v1_5.new(key)
    signature = signer.sign(h)
    signature_enc = base64.b64encode(signature)
    verifier = PKCS1_v1_5.new(key)
    if verifier.verify(h, signature):
        return signature_enc.decode("utf-8")
    else:
        return False
Пример #19
0
    def _sign(self, unsigned_string):
        """
        通过如下方法调试签名
        方法1
            key = rsa.PrivateKey.load_pkcs1(open(self._app_private_key_path).read())
            sign = rsa.sign(unsigned_string.encode("utf8"), key, "SHA-1")
            # base64 编码,转换为unicode表示并移除回车
            sign = base64.encodebytes(sign).decode("utf8").replace("\n", "")
        方法2
            key = RSA.importKey(open(self._app_private_key_path).read())
            signer = PKCS1_v1_5.new(key)
            signature = signer.sign(SHA.new(unsigned_string.encode("utf8")))
            # base64 编码,转换为unicode表示并移除回车
            sign = base64.encodebytes(signature).decode("utf8").replace("\n", "")
        方法3
            echo "abc" | openssl sha1 -sign alipay.key | openssl base64

        """
        # 开始计算签名
        key = self.app_private_key
        signer = PKCS1_v1_5.new(key)
        if self._sign_type == "RSA":
            signature = signer.sign(SHA.new(b(unsigned_string)))
        else:
            signature = signer.sign(SHA256.new(b(unsigned_string)))
        # base64 编码,转换为unicode表示并移除回车
        sign = encodebytes(signature).decode("utf8").replace("\n", "")
        return sign
Пример #20
0
def rsa_verify(sign, message, pub_Key):
    pub = RSA.importKey(pub_Key)
    cipher = SHA1.new(message)
    t = Signature_pkcs1_v1_5.new(pub).verify(cipher, base64.b64decode(sign))
    if t:
        return True
    return False
Пример #21
0
def _generate_signature(string_to_sign: str, keys: RsaKey) -> str:
    bytes_to_sign = string_to_sign.encode()
    signer = PKCS1_v1_5.new(keys)
    digest = SHA256.new()
    digest.update(bytes_to_sign)
    sign = signer.sign(digest)
    return b64encode(sign)
    def verify_signature(self, signature_algorithm, signature, cert, data):
        """
        Verifies the signature
        """
        sig = SnowflakeOCSPPyasn1.bit_string_to_bytearray(signature)
        if PY2:
            sig = str(sig)
        else:
            sig = sig.decode('latin-1').encode('latin-1')

        pubkey = SnowflakeOCSPPyasn1.bit_string_to_bytearray(
            cert.getComponentByName(
                'tbsCertificate').getComponentByName(
                'subjectPublicKeyInfo').getComponentByName('subjectPublicKey'))
        if PY2:
            pubkey = str(pubkey)
        else:
            pubkey = pubkey.decode('latin-1').encode('latin-1')

        rsakey = RSA.importKey(pubkey)
        signer = PKCS1_v1_5.new(rsakey)

        algorithm = signature_algorithm[0]
        if algorithm in SnowflakeOCSPPyasn1.SIGNATURE_HASH_ALGO_TO_DIGEST_CLASS:
            digest = SnowflakeOCSPPyasn1.SIGNATURE_HASH_ALGO_TO_DIGEST_CLASS[
                algorithm].new()
        else:
            digest = SHA1.new()

        data = der_encoder.encode(data)
        digest.update(data)
        if not signer.verify(digest, sig):
            raise RevocationCheckError(
                msg="Failed to verify the signature",
                errno=ER_INVALID_OCSP_RESPONSE)
Пример #23
0
    def _sign(self, unsigned_string):
        """
        通过如下方法调试签名
        方法1
            key = rsa.PrivateKey.load_pkcs1(open(self._app_private_key_path).read())
            sign = rsa.sign(unsigned_string.encode("utf8"), key, "SHA-1")
            # base64 编码,转换为unicode表示并移除回车
            sign = base64.encodebytes(sign).decode("utf8").replace("\n", "")
        方法2
            key = RSA.importKey(open(self._app_private_key_path).read())
            signer = PKCS1_v1_5.new(key)
            signature = signer.sign(SHA.new(unsigned_string.encode("utf8")))
            # base64 编码,转换为unicode表示并移除回车
            sign = base64.encodebytes(signature).decode("utf8").replace("\n", "")
        方法3
            echo "abc" | openssl sha1 -sign alipay.key | openssl base64

        """
        # 开始计算签名
        key = self.app_private_key
        signer = PKCS1_v1_5.new(key)
        if self._sign_type == "RSA":
            signature = signer.sign(SHA.new(b(unsigned_string)))
        else:
            signature = signer.sign(SHA256.new(b(unsigned_string)))
        # base64 编码,转换为unicode表示并移除回车
        sign = encodebytes(signature).decode("utf8").replace("\n", "")
        return sign
Пример #24
0
    def run(self):
        bufferSize = 4096
        UDPClientSocket = socket.socket(family=socket.AF_INET,
                                        type=socket.SOCK_DGRAM)

        encryptor = PKCS1_OAEP.new(self.CAPublicKey)
        encrypted = encryptor.encrypt(self.bytesToSend)
        #encrypted = encryptor.encrypt(self.bytesToSend.encode());
        #print ('Ciphertext Start');
        #print (encrypted.hex().upper());
        #print ('End');
        UDPClientSocket.sendto(encrypted, self.serverAddressPort)
        msgFromServer = UDPClientSocket.recvfrom(bufferSize)
        self.message = msgFromServer[0][:64]
        self.signature = msgFromServer[0][64:]
        #print(self.signature.hex().upper())
        self.messageString = format(msgFromServer[0][:64].decode("utf-8"))
        responseHash = SHA256.new(data=self.message)
        self.verified = False

        try:
            verified = False
            verifier = PKCS1_v1_5.new(self.CAPublicKey)
            verified = verifier.verify(responseHash, self.signature)
            self.verified = verified
        except ValueError:
            self.verified = False
Пример #25
0
def get_oauth_token(scopes):
    with open("keys.json") as f:
        keys = json.load(f)
    t = int(time.time())

    header = json.dumps({"alg": "RS256", "typ": "JWT"}).encode("utf-8")
    claim = json.dumps({
        "iss": keys["client_email"],
        "scope": " ".join(scopes),
        "aud": "https://accounts.google.com/o/oauth2/token",
        "iat": t,
        "exp": t + 60 * 60,
    }).encode("utf-8")

    data = base64_encode(header) + b'.' + base64_encode(claim)

    key = RSA.importKey(keys["private_key"])
    h = SHA256.new(data)
    signer = PKCS1_v1_5.new(key)
    signature = signer.sign(h)

    jwt = (data + b'.' + base64_encode(signature)).decode("utf-8")

    data = {
        "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
        "assertion": jwt
    }

    ret = json.loads(
        (yield from
         common.http.request_coro("https://accounts.google.com/o/oauth2/token",
                                  data, "POST")))
    if "error" in ret:
        raise Exception(ret["error"])
    return ret
Пример #26
0
 def sign_transaction(self, sender, recipient, amount):
     signer = PKCS1_v1_5.new(RSA.importKey(
         binascii.unhexlify(self.private_key)))
     h = SHA256.new((str(sender) + str(recipient) +
                     str(amount)).encode('utf8'))
     signature = signer.sign(h)
     return binascii.hexlify(signature).decode('ascii')
Пример #27
0
def verify_rs256(payload, signature, public_key):
    """
    Verifies a RS256 signature
    """
    key = RSA.importKey(public_key)
    verifier = PKCS1_v1_5.new(key)
    return verifier.verify(SHA256.new(payload), signature)
Пример #28
0
 def __init__(self,
              apibase,
              username,
              password,
              privatekey,
              publickey,
              notificationurl,
              currency='EUR',
              hold_notifications=False):
     self.apibase = apibase
     self.username = username
     self.password = password
     self.signer = PKCS1_v1_5.new(RSA.importKey(privatekey))
     self.verifier = PKCS1_v1_5.new(RSA.importKey(publickey))
     self.notificationurl = notificationurl
     self.currency = currency
     self.hold_notifications = hold_notifications
Пример #29
0
def sign_rs256(payload, private_key):
    """
    Produce a RS256 signature of the payload
    """
    key = RSA.importKey(private_key)
    signer = PKCS1_v1_5.new(key)
    signature = signer.sign(SHA256.new(payload))
    return signature
Пример #30
0
 def sign(self, unsigned_string):
     # 开始计算签名
     key = self.app_private_key
     signer = PKCS1_v1_5.new(key)
     signature = signer.sign(SHA256.new(unsigned_string))
     # base64 编码
     sign = base64.encodestring(signature).decode("utf8").replace("\n", "")
     return sign
Пример #31
0
 def verify_callback(self, body, signature):
     h = SHA256.new()
     h.update(body)
     key = Client.callback_public_key()
     verifier = PKCS1_v1_5.new(key)
     signature = bytes(signature, 'utf-8') if six.PY3 else bytes(signature)
     signature_buffer = base64.b64decode(signature)
     return verifier.verify(h, signature_buffer)
Пример #32
0
    def _sign(self, unsigned_string: AnyStr):
        """ 签名计算 """

        key = self.load_key(self.app_private_key)
        signer = PKCS1_v1_5.new(key)
        signature = signer.sign(SHA256.new(unsigned_string.encode('utf-8')))
        sign = encodebytes(signature).decode("utf-8").replace("\n", "")
        return sign
Пример #33
0
def verify_signature(data, public_key, signature):
    digest = SHA256.new()
    digest.update(data)
    signer = PKCS1_v1_5.new(public_key)

    if signer.verify(digest, signature):
        return True
    return False
Пример #34
0
 def verify(self, msg, sig, key):
     h = self.digest.new(msg)
     verifier = PKCS1_v1_5.new(key)
     try:
         if verifier.verify(h, sig):
             return True
         else:
             raise BadSignature()
     except ValueError as e:
         raise BadSignature(str(e))
Пример #35
0
 def _verify(self, raw_content, signature):
     # 开始计算签名
     key = self.alipay_public_key
     signer = PKCS1_v1_5.new(key)
     if self._sign_type == "RSA":
         digest = SHA.new()
     else:
         digest = SHA256.new()
     digest.update(raw_content.encode("utf8"))
     if signer.verify(digest, decodebytes(signature.encode("utf8"))):
         return True
     return False
Пример #36
0
def sign_string(message, pem_private, pem_passphrase="", sign_algo="SHA384"):
    """
    Generate a signature for string using the `sign_algo` and `RSA` algorithms.
    """
    from Cryptodome.PublicKey import RSA
    from Cryptodome.Signature import PKCS1_v1_5
    from binascii import b2a_hex

    if sign_algo not in ("MD5", "SHA1", "SHA256", "SHA384", "SHA512"):
        raise ValueError("Unsupported Signing algorithm")

    priv_key = RSA.import_key(pem_private, passphrase=pem_passphrase)
    signer = PKCS1_v1_5.new(priv_key)
    digest = getattr(
        __import__("Cryptodome.Hash", fromlist=[sign_algo]), sign_algo
    ).new()
    digest.update(message)
    return b2a_hex(signer.sign(digest))
Пример #37
0
 def verify_transaction(transaction):
     public_key = RSA.importKey(binascii.unhexlify(transaction.sender))
     verifier = PKCS1_v1_5.new(public_key)
     h = SHA256.new((str(transaction.sender) + str(transaction.recipient) +
                     str(transaction.amount)).encode('utf8'))
     return verifier.verify(h, binascii.unhexlify(transaction.signature))
Пример #38
0
 def sign(self, msg, key):
     h = self.digest.new(msg)
     signer = PKCS1_v1_5.new(key)
     return signer.sign(h)