Example #1
0
 def __generate(self, keydata):
     '''
     Generate the pycrypto rsa object
     '''
     if keydata:
         if 'components' not in keydata:
             raise ValueError('Invalid keydata, no components')
         key = RSA.construct(keydata['components'])
         if key.has_private():
             self.priv = key
             self.pub = key.publickey()
             self.sign_key = PKCS1_PSS.new(self.priv)
             self.verify_key = PKCS1_PSS.new(self.pub)
             self.decrypter = PKCS1_OAEP.new(self.priv)
         else:
             self.pub = key
             self.verify_key = PKCS1_PSS.new(self.pub)
         self.keydata = keydata
     else:
         self.priv = self._gen_key()
         self.pub = self.priv.publickey()
         self.sign_key = PKCS1_PSS.new(self.priv)
         self.verify_key = PKCS1_PSS.new(self.pub)
         self.keydata = self._gen_keydata(self.priv)
         self.decrypter = PKCS1_OAEP.new(self.priv)
     self.encrypter = PKCS1_OAEP.new(self.pub)
     self.max_msg_size = self.get_max_msg_size()
     self.enc_chunk_size = self.get_enc_chunk_size()
Example #2
0
        def testSignVerify(self):
                        h = SHA1.new()
                        h.update(b('blah blah blah'))

                        class RNG(object):
                            def __init__(self):
                                self.asked = 0
                            def __call__(self, N):
                                self.asked += N
                                return Random.get_random_bytes(N)

                        key = RSA.generate(1024)

                        # Helper function to monitor what's request from MGF
                        global mgfcalls
                        def newMGF(seed,maskLen):
                            global mgfcalls
                            mgfcalls += 1
                            return bchr(0x00)*maskLen

                        # Verify that PSS is friendly to all ciphers
                        for hashmod in (MD2,MD5,SHA1,SHA224,SHA256,SHA384,RIPEMD160):
                            h = hashmod.new()
                            h.update(b('blah blah blah'))

                            # Verify that sign() asks for as many random bytes
                            # as the hash output size
                            rng = RNG()
                            signer = PKCS.new(key, randfunc=rng)
                            s = signer.sign(h)
                            signer.verify(h, s)
                            self.assertEqual(rng.asked, h.digest_size)

                        h = SHA1.new()
                        h.update(b('blah blah blah'))

                        # Verify that sign() uses a different salt length
                        for sLen in (0,3,21):
                            rng = RNG()
                            signer = PKCS.new(key, saltLen=sLen, randfunc=rng)
                            s = signer.sign(h)
                            self.assertEqual(rng.asked, sLen)
                            signer.verify(h, s)

                        # Verify that sign() uses the custom MGF
                        mgfcalls = 0
                        signer = PKCS.new(key, newMGF)
                        s = signer.sign(h)
                        self.assertEqual(mgfcalls, 1)
                        signer.verify(h, s)

                        # Verify that sign() does not call the RNG
                        # when salt length is 0, even when a new MGF is provided
                        key.asked = 0
                        mgfcalls = 0
                        signer = PKCS.new(key, newMGF, 0)
                        s = signer.sign(h)
                        self.assertEqual(key.asked,0)
                        self.assertEqual(mgfcalls, 1)
                        signer.verify(h, s)
Example #3
0
def verify_signature(message, signature, key):
    h = SHA256.new(message)
    print(message, key)
    try:
        PKCS1_PSS.new(key).verify(h, signature)
        return True
    except SyntaxError:
        return False
Example #4
0
def verifySignature(message, signature, key):
	h = SHA256.new(message)
	try:
	    PKCS1_PSS.new(key).verify(h, signature)
	    #print "The signature is valid."
	    return True
	except (ValueError, TypeError):
	 	#print "The signature is not valid."
	 	return False
Example #5
0
    def testSignVerify(self):
        h = SHA.new()
        h.update(b('blah blah blah'))

        rng = Random.new().read
        key = MyKey(RSA.generate(1024, rng))

        # Helper function to monitor what's request from MGF
        global mgfcalls

        def newMGF(seed, maskLen):
            global mgfcalls
            mgfcalls += 1
            return bchr(0x00) * maskLen

        # Verify that PSS is friendly to all ciphers
        for hashmod in (MD2, MD5, SHA, SHA224, SHA256, SHA384, RIPEMD):
            h = hashmod.new()
            h.update(b('blah blah blah'))

            # Verify that sign() asks for as many random bytes
            # as the hash output size
            key.asked = 0
            signer = PKCS.new(key)
            s = signer.sign(h)
            self.failUnless(signer.verify(h, s))
            self.assertEqual(key.asked, h.digest_size)

        h = SHA.new()
        h.update(b('blah blah blah'))

        # Verify that sign() uses a different salt length
        for sLen in (0, 3, 21):
            key.asked = 0
            signer = PKCS.new(key, saltLen=sLen)
            s = signer.sign(h)
            self.assertEqual(key.asked, sLen)
            self.failUnless(signer.verify(h, s))

        # Verify that sign() uses the custom MGF
        mgfcalls = 0
        signer = PKCS.new(key, newMGF)
        s = signer.sign(h)
        self.assertEqual(mgfcalls, 1)
        self.failUnless(signer.verify(h, s))

        # Verify that sign() does not call the RNG
        # when salt length is 0, even when a new MGF is provided
        key.asked = 0
        mgfcalls = 0
        signer = PKCS.new(key, newMGF, 0)
        s = signer.sign(h)
        self.assertEqual(key.asked, 0)
        self.assertEqual(mgfcalls, 1)
        self.failUnless(signer.verify(h, s))
Example #6
0
    def testSignVerify(self):
        h = SHA.new()
        h.update(b('blah blah blah'))

        rng = Random.new().read
        key = MyKey(RSA.generate(1024, rng))

        # Helper function to monitor what's request from MGF
        global mgfcalls

        def newMGF(seed, maskLen):
            global mgfcalls
            mgfcalls += 1
            return bchr(0x00) * maskLen

        # Verify that PSS is friendly to all ciphers
        for hashmod in (MD2, MD5, SHA, SHA224, SHA256, SHA384, RIPEMD):
            h = hashmod.new()
            h.update(b('blah blah blah'))

            # Verify that sign() asks for as many random bytes
            # as the hash output size
            key.asked = 0
            signer = PKCS.new(key)
            s = signer.sign(h)
            self.failUnless(signer.verify(h, s))
            self.assertEqual(key.asked, h.digest_size)

        h = SHA.new()
        h.update(b('blah blah blah'))

        # Verify that sign() uses a different salt length
        for sLen in (0, 3, 21):
            key.asked = 0
            signer = PKCS.new(key, saltLen=sLen)
            s = signer.sign(h)
            self.assertEqual(key.asked, sLen)
            self.failUnless(signer.verify(h, s))

        # Verify that sign() uses the custom MGF
        mgfcalls = 0
        signer = PKCS.new(key, newMGF)
        s = signer.sign(h)
        self.assertEqual(mgfcalls, 1)
        self.failUnless(signer.verify(h, s))

        # Verify that sign() does not call the RNG
        # when salt length is 0, even when a new MGF is provided
        key.asked = 0
        mgfcalls = 0
        signer = PKCS.new(key, newMGF, 0)
        s = signer.sign(h)
        self.assertEqual(key.asked, 0)
        self.assertEqual(mgfcalls, 1)
        self.failUnless(signer.verify(h, s))
Example #7
0
    def runTest(self):
        key = RSA.generate(1024)
        hashed = SHA1.new(b("Test"))
        good_signature = PKCS1_PSS.new(key).sign(hashed)
        verifier = PKCS1_PSS.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.generate(1024)
        hashed = SHA1.new(b("Test"))
        good_signature = PKCS1_PSS.new(key).sign(hashed)
        verifier = PKCS1_PSS.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)
Example #9
0
 def initActive(self, self_prv_key, peer_pub_key):
     self.active = True
     
     self.self_prv_key = self_prv_key
     self.peer_pub_key = peer_pub_key
     
     self.self_asym_decrypter = PKCS1_OAEP.new(self.self_prv_key)
     self.peer_asym_encrypter = PKCS1_OAEP.new(self.peer_pub_key)
     
     self.self_signer = PKCS1_PSS.new(self.self_prv_key)
     self.peer_verifier = PKCS1_PSS.new(self.peer_pub_key)             
     return self
Example #10
0
    def inicijaliziraj(self, velicina_kljuca, naziv):
        self.velicina_kljuca = self.velicine_kljuca[
            velicina_kljuca]  # duljina broja n
        self.privatni_kljuc = RSA.generate(self.velicina_kljuca)
        self.javni_kljuc = self.privatni_kljuc.publickey()
        rsa_kljuc_u_dat(naziv + '_privatni_rsa.key', self.privatni_kljuc,
                        self.velicina_kljuca, False)
        rsa_kljuc_u_dat(naziv + '_javni_rsa.key', self.javni_kljuc,
                        self.velicina_kljuca, True)

        self.kljuc_za_potpis = PKCS1_PSS.new(self.privatni_kljuc)
        self.kljuc_za_verifikaciju = PKCS1_PSS.new(self.javni_kljuc)
        self.privatni_kljuc = PKCS1_OAEP.new(self.privatni_kljuc)
        self.javni_kljuc = PKCS1_OAEP.new(self.javni_kljuc)
Example #11
0
        def test_wrong_signature(self):
            key = RSA.generate(1024)
            msg_hash = SHA1.new(b("Message"))

            signer = PKCS.new(key)
            s = signer.sign(msg_hash)

            verifier = PKCS.new(key.publickey())

            # The signature s should be OK
            verifier.verify(msg_hash, s)

            # Construct an incorrect signature and ensure that the check fails
            wrong_s = s[:-1] + bchr(bord(s[-1]) ^ 0xFF)
            self.assertRaises(ValueError, verifier.verify, msg_hash, wrong_s)
Example #12
0
    def test_wrong_signature(self):
        key = RSA.generate(1024)
        msg_hash = SHA1.new(b("Message"))

        signer = PKCS.new(key)
        s = signer.sign(msg_hash)

        verifier = PKCS.new(key.publickey())

        # The signature s should be OK
        verifier.verify(msg_hash, s)

        # Construct an incorrect signature and ensure that the check fails
        wrong_s = s[:-1] + bchr(bord(s[-1]) ^ 0xFF)
        self.assertRaises(ValueError, verifier.verify, msg_hash, wrong_s)
Example #13
0
    def asymmetric_sign(self, message, private_key):
        """Produce the PKCS#1 PSS RSA signature of the message.

        See the PyCrypto `PKCS1_PSS module
        <https://pythonhosted.org/pycrypto/Crypto.Signature.PKCS1_PSS-module.html>`_
        for more information about the underlying implementation.
        PKCS#1 PSS is a secure signature scheme.

        :param str message: The message to sign.
        :param private_key: The private key to sign with.
        :type private_key: An RSA key object

        :returns: The signature.
        :rtype: str

        :raises CryptoError: If message is not a string, or if private_key
            is not an RSA key object.
        :raises ValueError: If the RSA key length is not sufficiently long to
            deal with the given hash algorithm (SHA256).
        :raises TypeError: If the RSA key has no private half.
        """
        if not isinstance(message, str):
            raise CryptoError("Message must be a string")

        if not isinstance(private_key, RSA._RSAobj):
            raise CryptoError("private_key is not an RSA key")

        h = SHA256.new()
        h.update(_string_to_bytes(message))
        signer = PKCS1_PSS.new(private_key)
        signature = signer.sign(h)
        return _bytes_to_hex(signature)
Example #14
0
 def set_priv_key(self, priv_key):
     self.signer = PKCS1_PSS.new(priv_key)
     pub_key = priv_key.publickey()
     self.dbc.execute("INSERT INTO _singletons (key, data) VALUES ('priv_key', ?)",
         (buffer(priv_key.exportKey('PEM')),))
     (hid, summary, body) = record.make_pubkey_record(pub_key)
     self.on_record(record.RT_PUBKEY, hid, summary, body)
Example #15
0
def check_signature(path, public_key):

    hash_value = compute_hash(path + "/signed_data")
    with open(path + "/" + signature_filename, "rb") as f:
        signature = f.read()
    verifier = PKCS1_PSS.new(public_key)
    return verifier.verify(Crypto.Hash.SHA256.new(hash_value), signature)
Example #16
0
def sign_data(priv_sign_rsa_key, data):
    key = open(priv_sign_rsa_key, "r").read()
    rsakey = RSA.importKey(key)
    signer = PKCS1_PSS.new(rsakey)
    digest = SHA256.new()
    digest.update(data)
    return signer.sign(digest)
Example #17
0
    def asymmetric_verify(self, message, signature, public_key):
        """Verify that a PKCS#1 PSS RSA signature is authentic.

        See the PyCrypto `PKCS1_PSS module
        <https://pythonhosted.org/pycrypto/Crypto.Signature.PKCS1_PSS-module.html>`_
        for more information about the underlying implementation.

        :param str message: The original message.
        :param str signature: The signature to be verified.
        :param public_key: The public key of the signer.
        :type public_key: An RSA key object

        :returns: True if verification is correct. False otherwise.
        :rtype: bool

        :raises CryptoError: If message or signature are not strings, or
            if public_key is not an RSA public key.
        """
        if not isinstance(message, str):
            raise CryptoError("Message must be a string")
        if not isinstance(signature, str):
            raise CryptoError("Signature must be a string")
        if not isinstance(public_key, RSA._RSAobj):
            raise CryptoError("public_key must be an RSA public key")

        try:
            h = SHA256.new()
            h.update(_string_to_bytes(message))
            verifier = PKCS1_PSS.new(public_key)
            status = verifier.verify(h, _hex_to_bytes(signature))
            return status
        except:
            return False
Example #18
0
def _create_signature(message):
    key = RSA.importKey(CLIENT_PRIV_KEY)
    h = SHA.new()
    h.update(message)
    signer = PKCS1_PSS.new(key)

    return signer.sign(h)
def digital_signature():
    try:
        file = open("private_key.txt", "r")
        private_key_text = file.read()
        file.close()
    except:
        print("Private key hasn't been created yet.")
        return

    filename = input("Filename: ")

    try:
        file = open(filename, "r")
        data = file.read()
        file.close()
    except:
        print("File not found.")
        return

    private_key = RSA.importKey(private_key_text)
    digital_signer = PKCS1_PSS.new(private_key)
    digital_signature_data = digital_signer.sign(MD5.new(data.encode()))
    print("Digital signature successfully created.")

    digital_signature_text = base64.b64encode(digital_signature_data).decode()
    save_file("digital_signature.txt", digital_signature_text)
    print("File has been saved as digital_signature.txt.")
Example #20
0
def get_balance(private_key):
    encoded_public_key = private_key.publickey().exportKey()
    timestamp = time.time()
    h = SHA.new()
    h.update(encoded_public_key)
    h.update(str(timestamp))
    signer = PKCS1_PSS.new(private_key)
    signature = binascii.hexlify(signer.sign(h))

    data = {}
    data['pub_key'] = encoded_public_key
    data['timestamp'] = timestamp
    data['signature'] = signature

    def get_balance_from_body(body):
        r = json.loads(body)
        if not 'balance' in r:
            raise ValueError("Invalid response: no 'balance' field")
        else:
            return float(r['balance'])

    d = get_body_from_request('/get-balance/', data)

    d.addCallback(get_balance_from_body)

    return d
Example #21
0
def get_recent_transactions(private_key):
    encoded_public_key = private_key.publickey().exportKey()
    timestamp = time.time()
    h = SHA.new()
    h.update(encoded_public_key)
    h.update(str(timestamp))
    signer = PKCS1_PSS.new(private_key)
    signature = binascii.hexlify(signer.sign(h))

    data = {}
    data['pub_key'] = encoded_public_key
    data['timestamp'] = timestamp
    data['signature'] = signature
    data['end_time'] = 0
    data['start_time'] = 120

    def get_transactions_from_body(body):
        r = json.loads(body)
        if "transactions" not in r:
            raise ValueError("Invalid response: no 'transactions' field")
        else:
            return r['transactions']

    d = get_body_from_request('/get-transactions/', data)

    d.addCallback(get_transactions_from_body)

    return d
Example #22
0
def send_points(private_key, recipient_public_key, amount):
    encoded_public_key = private_key.publickey().exportKey()
    timestamp = time.time()
    h = SHA.new()
    h.update(encoded_public_key)
    h.update(recipient_public_key)
    h.update(str(amount))
    h.update(str(timestamp))
    signer = PKCS1_PSS.new(private_key)
    signature = binascii.hexlify(signer.sign(h))

    data = {}
    data['sender_pub_key'] = encoded_public_key
    data['recipient_pub_key'] = recipient_public_key
    data['amount'] = amount
    data['timestamp'] = timestamp
    data['signature'] = signature

    def get_success_from_body(body):
        r = json.loads(body)
        if not 'success' in r or r['success'] is False:
            return False
        return True

    d = get_body_from_request('/send-points/', data)

    d.addCallback(get_success_from_body)

    return d
Example #23
0
File: safe.py Project: adoll/dms
def read_board():
    r = tor_connection.get(message_board)
    j = json.loads(r)
    for i in j:
        if (i["to"] == own_id):
            ciphertext = i["message"].decode("base64")
            cipher = PKCS1_OAEP.new(key)
            message = cipher.decrypt(ciphertext)
            mj = json.loads(message)
            their_key = RSA.importKey(directory[mj["from"]])
            
            h = SHA.new()
            h.update(ciphertext)
            verifier = PKCS1_PSS.new(their_key)
            if verifier.verify(h, i["signature"].decode("base64")):
                if mj["command"] == check_in_command:
                    from_id = str(mj["from"])
                    ts = mj["timestamp"]

                    if from_id in checkins:
                        lts = checkins[from_id]
                        if ts > lts:
                            checkins[from_id] = ts
                    else:
                        checkins[from_id] = ts
                elif mj["command"] == add_command:
                    from_id = str(mj["from"])
                    period = str(mj["period"])
                    share = str(mj["share"])
                    shares[from_id] = (share, period)
            else:
                print "FAIL"
Example #24
0
    def _rsassa_pss_verifier(self):
        verifier = self.__rsassa_pss_verifier

        if not verifier:
            verifier = self.__rsassa_pss_verifier = PKCS1_PSS.new(self._public_key())

        return verifier
Example #25
0
 def sign(self, msg):
     h = SHA.new()
     h.update(msg)
     keystr = self.manager.key_object.exportKey('PEM')
     # signer object constructed with RSA object chat manager
     signer = PKCS1_PSS.new(RSA.importKey(keystr))
     return base64.encodestring(signer.sign(h))
Example #26
0
    def _rsassa_pss_signer(self):
        signer = self.__rsassa_pss_signer

        if not signer:
            signer = self.__rsassa_pss_signer = PKCS1_PSS.new(self._private_key())

        return signer
Example #27
0
def receive():
    global PublicKeys
    global client_socket
    """Handles receiving of messages."""
    while True:
        msg = client_socket.recv(BUFSIZ)
        if not msg:
            break
        if bytes("{PUBLICKEY}", "utf8") in msg:
            msg = msg[11:]
            PublicKeys = pickle.loads(msg)
        else:
            message = msg[:384]
            signature = msg[384:768]
            sender = msg[768:]
            """ decrypt message """
            decryptor = PKCS1_OAEP.new(keyPair)
            decryptedMessage = decryptor.decrypt(message)
            """ decrypt signature """
            h = SHA.new()
            h.update(decryptedMessage)
            for ip in PublicKeys:
                if ip == sender.decode("utf8"):
                    verifier = PKCS1_PSS.new(RSA.import_key(PublicKeys[ip]))
            if verifier.verify(h, signature):
                print(decryptedMessage.decode("utf8"))
            else:
                print("Not Verified")
Example #28
0
def _verify_signature(message, signature):
    key = RSA.importKey(SRV_PUB_KEY)
    h = SHA.new()
    h.update(message)
    verifier = PKCS1_PSS.new(key)

    return verifier.verify(h, signature)
Example #29
0
def get_signature(username):
    global private_key
    msg = SHA.new()
    msg.update(username)
    signer = PKCS1_PSS.new(private_key)
    signature = signer.sign(msg)
    return urllib.quote(signature)
Example #30
0
def asymmetricSign(message, key):
	"""Returns a signature of inpString signed with 'key'."""
	key = RSA.importKey(key)
	h = SHA.new()
	h.update(message)
	signer = PKCS1_PSS.new(key)
	return binascii.b2a_base64(signer.sign(h))
Example #31
0
def asymmetricSign(message, key):
    """Returns a signature of inpString signed with 'key'."""
    key = RSA.importKey(key)
    h = SHA.new()
    h.update(message)
    signer = PKCS1_PSS.new(key)
    return binascii.b2a_base64(signer.sign(h))
Example #32
0
def verify(path):
    """
    Verify the file `path`, with signature `path`.sig, against the key
    found under ~/.conda/keys/<key_name>.pub.  This function returns:
      - True, if the signature is valid
      - False, if the signature is invalid
    It raises SignatureError when the signature file, or the public key
    does not exist.
    """
    log = logging.getLogger(__name__)
    sig_path = path + '.sig'
    if not isfile(sig_path):
        log.error("signature does not exist: %s", sig_path)
        return False
    with open(sig_path) as fi:
        key_name, sig = fi.read().split()
    if key_name not in KEYS:
        key_path = join(KEYS_DIR, '%s.pub' % key_name)
        if not isfile(key_path):
            log.error("public key does not exist: %s", key_path)
            return False
        KEYS[key_name] = RSA.importKey(open(key_path).read())
    key = KEYS[key_name]
    verifier = PKCS1_PSS.new(key)
    return verifier.verify(hash_file(path), base64.b64decode(sig))
Example #33
0
def verify(path):
    """
    Verify the file `path`, with signature `path`.sig, against the key
    found under ~/.conda/keys/<key_name>.pub.  This function returns:
      - True, if the signature is valid
      - False, if the signature is invalid
    It raises SignatureError when the signature file, or the public key
    does not exist.
    """
    log = logging.getLogger(__name__)
    sig_path = path + '.sig'
    if not isfile(sig_path):
        log.error("signature does not exist: %s", sig_path)
        return False
    with open(sig_path) as fi:
        key_name, sig = fi.read().split()
    if key_name not in KEYS:
        key_path = join(KEYS_DIR, '%s.pub' % key_name)
        if not isfile(key_path):
            log.error("public key does not exist: %s", key_path)
            return False
        KEYS[key_name] = RSA.importKey(open(key_path).read())
    key = KEYS[key_name]
    verifier = PKCS1_PSS.new(key)
    return verifier.verify(hash_file(path), base64.b64decode(sig))
Example #34
0
def signImage(privkey, infile, offset, outfile):
    hash = SHA256.new()
    keyFileh = open(privkey, "rb")
    key = RSA.importKey(keyFileh.read())
    keyFileh.close()
    signer = PKCS1_PSS.new(key)
    infileh = open(infile, "rb")
    message = ''
    if offset > 0:
        message = infileh.seek(offset)
        print "signImage: ignored: %d" % offset

    message = infileh.read()
    while message != '':
        hash.update(message)
        message = infileh.read()
    signature = signer.sign(hash)
    infileh.close()

    infileh = open(infile, "rb")
    outfileh = open(outfile, 'wb')
    outfileh.write(signature)
    if offset > 0:
        message = infileh.seek(offset)

    message = infileh.read()
    while message != '':
        outfileh.write(message)
        message = infileh.read()
    infileh.close()
    outfileh.close()
Example #35
0
def encrypt(v, encrypt_rsapubkey=None, sign_rsaprivkey=None):
	from Crypto.PublicKey import RSA
	from Crypto.Cipher import PKCS1_OAEP
	from Crypto.Cipher import AES
	from Crypto.Signature import PKCS1_PSS
	from Crypto.Hash import SHA512
	out = {}
	if encrypt_rsapubkey:
		encrypt_rsapubkey = RSA.importKey(encrypt_rsapubkey)
		rsa = PKCS1_OAEP.new(encrypt_rsapubkey)
		aeskey = randomString(32)
		iv = randomString(16)
		aes = AES.new(aeskey, AES.MODE_CBC, iv)
		data = varEncode(v).tostring()
		data += "\x00" * (-len(data) % 16)
		out["aesInfo"] = rsa.encrypt(aeskey + iv)
		out["data"] = aes.encrypt(data)
		out["encrypted"] = True
	else:
		out["data"] = varEncode(v).tostring()
		out["encrypted"] = False
	if sign_rsaprivkey:
		sign_rsaprivkey = RSA.importKey(sign_rsaprivkey)
		pss = PKCS1_PSS.new(sign_rsaprivkey)
		h = SHA512.new()
		h.update(out["data"])
		sign = pss.sign(h)
		out["signature"] = sign
	else:
		out["signature"] = None
	return out
def digital_signature_verification():
    try:
        file = open("public_key.txt", "r")
        public_key_text = file.read()
        file.close()
    except:
        print("Public key hasn't been created yet.")
        return

    filename = input("Filename: ")
    try:
        file = open(filename, "r")
        data = file.read()
        file.close()
    except:
        print("File not found.")
        return

    try:
        file = open("digital_signature.txt", "r")
        digital_signature_text = file.read()
        file.close()
    except:
        print("Digital signature hasn't been created yet.")
        return

    public_key = RSA.importKey(public_key_text)
    digital_signature_data = base64.b64decode(digital_signature_text)
    digital_signer = PKCS1_PSS.new(public_key)

    if digital_signer.verify(MD5.new(data.encode()), digital_signature_data):
        print("Digital signature is valid.")
    else:
        print("Digital signature is invalid.")
Example #37
0
def verifyTransactionInput(referencedTransaction: Transaction,
                           transaction: Transaction,
                           inputIndex: int) -> Tuple[bool, str]:
    """
    Verifies that a transaction input referencs a valid transaction output
    with corresponding index. Also checks if the transaction input is properly
    signed.

    This method is to verify that a person using a transaction input
    is the same person who recieved it as an output.
    """
    newInput = transaction.inputs[inputIndex]
    serializedOutputs = \
        TransactionOutput.serializeMultiple(transaction.outputs)

    # Check if referenced index is out of bounds
    index = newInput.referencedOutputIndex
    if index >= len(referencedTransaction.outputs) or index < 0:
        return False, "Referenced output index is out of bound"

    if referencedTransaction.hash != newInput.referencedHash:
        return False, "Referenced transaction hash does not match."

    referencedOutput = referencedTransaction.outputs[index]
    publicKey = RSA.importKey(bytes.fromhex(referencedOutput.address))
    verifier = PKCS1_PSS.new(publicKey)
    hash = TransactionInput.createSignatureHash(newInput.referencedHash,
                                                newInput.referencedOutputIndex,
                                                serializedOutputs)
    signature = bytes.fromhex(newInput.signature)

    if not verifier.verify(hash, signature):
        return False, "Signature not valid"

    return True, ""
Example #38
0
def send_points(private_key, recipient_public_key, amount):
    encoded_public_key = private_key.publickey().exportKey()
    timestamp = time.time()
    h = SHA.new()
    h.update(encoded_public_key)
    h.update(recipient_public_key)
    h.update(str(amount))
    h.update(str(timestamp))
    signer = PKCS1_PSS.new(private_key)
    signature = binascii.hexlify(signer.sign(h))

    data = {}
    data['sender_pub_key'] = encoded_public_key
    data['recipient_pub_key'] = recipient_public_key
    data['amount'] = amount
    data['timestamp'] = timestamp
    data['signature'] = signature

    def get_success_from_body(body):
        r = json.loads(body)
        if not 'success' in r or r['success'] is False:
            return False
        return True

    d = get_body_from_request('/send-points/', data)

    d.addCallback(get_success_from_body)

    return d
Example #39
0
def get_recent_transactions(private_key):
    encoded_public_key = private_key.publickey().exportKey()
    timestamp = time.time()
    h = SHA.new()
    h.update(encoded_public_key)
    h.update(str(timestamp))
    signer = PKCS1_PSS.new(private_key)
    signature = binascii.hexlify(signer.sign(h))

    data = {}
    data['pub_key'] = encoded_public_key
    data['timestamp'] = timestamp
    data['signature'] = signature
    data['end_time'] = 0
    data['start_time'] = 120

    def get_transactions_from_body(body):
        r = json.loads(body)
        if "transactions" not in r:
            raise ValueError("Invalid response: no 'transactions' field")
        else:
            return r['transactions']

    d = get_body_from_request('/get-transactions/', data)

    d.addCallback(get_transactions_from_body)

    return d
Example #40
0
 def sign(cls, data):
     if not cls.private_key:
         return
     key = cls.Import_Key(cls.private_key)
     _hash = SHA256.new(data)
     signature = PKCS1_PSS.new(key).sign(_hash)
     return b64encode(signature)
    def sign(self, message, private_keypath=None):
        if private_keypath == None:
            private_keypath = self.PRIVATE_KEY_FILE

        private_key = RSA.importKey(self.__read_file(private_keypath))
        signature = PKCS1_PSS.new(private_key)
        return signature.sign(self.__sha256(message))
Example #42
0
 def verify(cls, data, signature):
     if not cls.public_key:
         return
     key = cls.Import_Key(cls.public_key)
     _hash = SHA256.new(data)
     signature = b64decode(signature)
     return PKCS1_PSS.new(key).verify(_hash, signature)
Example #43
0
def getSignature(bstring):
    privateKey = RSA.importKey(open(DIR_IN + PRI_KEY_FILE).read())
    hash = SHA256.new()
    hash.update(bstring)
    signer = PKCS1_PSS.new(privateKey)
    signature = signer.sign(hash)
    return signature
Example #44
0
def api_call_verifier(config, pubkey, method_name, data, syndicate_data,
                      rpc_result):
    """
    Verify an RPC call.
    """
    # sanity check
    if not 'signature' in syndicate_data:
        log.error("No signature in server reply")
        return False

    sig = syndicate_data['signature']

    # verify object ID and type
    ret = False

    if pubkey is not None:
        # verify this data
        h = HashAlg.new(data)
        verifier = CryptoSigner.new(pubkey)
        ret = verifier.verify(h, sig)

        if not ret:
            # verification key has changed on the MS
            print warn_key_change(config)
            return False

        else:
            return True

    else:
        raise Exception("No public key given.  Unable to verify result.")
Example #45
0
def rsa_sign(priv_key, payload):
    """Sign the payload.

    This function sign the payload using RSA-PSS algorithm and private key
    of the source.

    :parameter:
     priv_key : RSA key object
        The rsa private key use to sign the payload.
     payload : string
        The payload to sign.

    :return: A string, the RSA-PSS signature of the payload.
    """

    # prepare the SHA256 hash
    h = SHA256.new()
    # create the SHA256 hash of the payload
    h.update(payload)
    # prepare the PKCS1-PSS signature with the private key
    signer = PKCS1_PSS.new(priv_key)
    # sign the hash
    thesignature = signer.sign(h)

    return thesignature
Example #46
0
    def sign(self, sk_priv):
        """
        Sign the BuildList using the RSA private key.

        sk_priv is the RSA private key used for siging the BuildList.
        """

        if self._dig_sig is not None:
            raise BLError("buildlist has already been signed")

        # Verify that the public key (sk) is the public part of sk_priv,
        # the private RSA key.
        # pylint: disable=protected-access
        if (not sk_priv) or (not isinstance(sk_priv, RSA._RSAobj)):
            raise BLError("sk_priv is nil or not a valid RSA key")
        if sk_priv.publickey() != self._public_key:
            raise BLError("sk_priv does not match BuildList's public key")

        # the time is part of what is signed, so we need to set it now
        # XXX truncating loses microseconds
        now = int(time.time())      # seconds from Epoch
        self._when = now

        sha = self._get_build_list_sha1()

        # Sign the list using SHA1 and RSA.  What we are signing is the
        # in-memory binary data structure.
        signer = PKCS1_PSS.new(sk_priv)
        self._dig_sig = signer.sign(sha)
Example #47
0
def get_balance(private_key):
    encoded_public_key = private_key.publickey().exportKey()
    timestamp = time.time()
    h = SHA.new()
    h.update(encoded_public_key)
    h.update(str(timestamp))
    signer = PKCS1_PSS.new(private_key)
    signature = binascii.hexlify(signer.sign(h))

    data = {}
    data['pub_key'] = encoded_public_key
    data['timestamp'] = timestamp
    data['signature'] = signature

    def get_balance_from_body(body):
        r = json.loads(body)
        if not 'balance' in r:
            raise ValueError("Invalid response: no 'balance' field")
        else:
            return float(r['balance'])

    d = get_body_from_request('/get-balance/', data)

    d.addCallback(get_balance_from_body)

    return d
Example #48
0
def api_call_verifier( config, pubkey, method_name, data, syndicate_data, rpc_result ):
   """
   Verify an RPC call.
   """
   
   # sanity check
   if not 'signature' in syndicate_data:
      log.error("No signature in server reply")
      return False 
   
   sig = syndicate_data['signature']
   
   # verify object ID and type
   ret = False
   
   if pubkey is not None:
      
      # verify this data
      h = HashAlg.new( data )
      verifier = CryptoSigner.new(pubkey)
      ret = verifier.verify( h, sig )
   
      if not ret:
         # verification key has changed on the MS
         warn_key_change( config )
         return False
   
      else:
         return True
   
   else:
      raise Exception("No public key given.  Unable to verify result.")
Example #49
0
File: Keys.py Project: stungkit/nut
def pssVerify(buffer, signature, modulus):
    p = PKCS1_PSS.new(RSA.RsaKey(n=modulus, e=65537))

    try:
        return p.verify(SHA256.new(buffer), signature)
    except BaseException:
        return False
Example #50
0
 def sign_transaction(self, sender, recipient, amount):
     signer = PKCS1_PSS.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')
Example #51
0
    def sign(self, sig_directives, signed) -> list:
        data = self.cjson(signed).encode('utf-8')

        sigs = []
        for (priv, pub), bad_sig in sig_directives:
            if self.signature_scheme == 'ed25519':
                priv = ed25519.SigningKey(binascii.unhexlify(priv))
                sig = priv.sign(data)
            elif self.signature_scheme.startswith('rsa'):
                if self.signature_scheme == 'rsassa-pss-sha256':
                    h = SHA256.new(data)
                elif self.signature_scheme == 'rsassa-pss-sha512':
                    h = SHA512.new(data)
                else:
                    raise Exception('Unknown signature scheme: {}'.format(
                        self.signature_scheme))

                rsa = RSA.importKey(priv)
                signer = PKCS1_PSS.new(rsa)
                sig = signer.sign(h)
            else:
                raise Exception('Unknow signature scheme: {}'.format(
                    self.signature_scheme))

            if bad_sig:
                sig[0] ^= 0x01

            sig_data = {
                'keyid': self.key_id(pub, bad_id=False),
                'method': self.signature_scheme,
                'sig': self.encode_signature(sig),
            }
            sigs.append(sig_data)

        return sigs
Example #52
0
def rsa_verify_sign(pub_key, rsa_signature, payload):
    """Verify the signature of the payload.

    This function control if the signature is valid for the payload provided
    using using RSA-PSS algorithm and public key of the source.

    :parameter:
     pub_key : RSA key object
        The rsa public key use to verify the signature.
     rsa_signature : string
        The signature of the payload.
     payload : string
        The payload to verify.

    :return: A boolean, true if the signature is verified for the payload or
    false if not.
    """

    # prepare the SHA256 hash
    h = SHA256.new()
    # create the SHA256 hash of the payload
    h.update(payload)
    # prepare the PKCS1-PSS signature with the public key
    verifier = PKCS1_PSS.new(pub_key)

    if verifier.verify(h, rsa_signature):
        sign_ok = True
    else:
        sign_ok = False

    return sign_ok
Example #53
0
 def verify(self, msg, sig, key):
     h = self.digest.new(msg)
     verifier = PKCS1_PSS.new(key)
     res = verifier.verify(h, sig)
     if not res:
         raise BadSignature()
     else:
         return True
Example #54
0
def create_dig_sig(message):
    f = open("./keys/rsa", "r") # get private key
    key = RSA.importKey(f.read())
    h = SHA.new()
    h.update(message)
    signer = PKCS.new(key)
    signature = signer.sign(h)
    return b64encode(signature)
Example #55
0
def asymmetricVerify(message, signature, key):
	"""Verifies the signature using 'key' and 'message'"""
	key = RSA.importKey(key)
	h = SHA.new()
	h.update(message)
	verifier = PKCS1_PSS.new(key)
	signature = binascii.a2b_base64(signature)
	return verifier.verify(h, signature)
Example #56
0
 def sign(self, private_key, plaintext):
   """
   Sign plaintext with private key.
   """
   msg_hash = SHA256.new(plaintext)
   signer = PKCS1_PSS.new(private_key)
   signature = signer.sign(msg_hash)
   return signature.encode('base64')
Example #57
0
 def _verify(self, message, signature):
     key = RSA.importKey(self._pub_key)
     h = SHA256.new()
     h.update(message)
     verifier = PKCS1_PSS.new(key)
     if verifier.verify(h, signature.decode('base64')):
         return json.loads(message.decode('base64'))
     raise ValueError("Invalid file signature!")
Example #58
0
    def cmdloop(self):
        while not self.flag:
            try:
                sys.stdout.write(self.prompt)
                sys.stdout.flush()

                # Wait for input from stdin & socket
                inputready, outputready, exceptrdy = select.select([0, self.sock], [], [])

                for i in inputready:
                    if i == 0:
                        # grab message
                        data = sys.stdin.readline().strip()

                        try:
                            # encrypt
                            data = self.encryptionKey.encrypt(data, 0)
                            data = data[0]

                            # append signature
                            signkey = self.decryptor
                            message_hash = SHA512.new()
                            message_hash.update(data)

                            signer = PKCS1_PSS.new(signkey)
                            signature = signer.sign(message_hash)
                            data = '%s#^[[%s' % (data, signature)

                        except ValueError:
                            print 'Too large text, cannot encrypt, not sending.'
                            data = None

                        if data:
                            send(self.ssl_sock, data)

                    elif i == self.sock:
                        data = receive(self.ssl_sock)

                        if not data:
                            print 'Shutting down.'
                            self.flag = True
                            break

                        else:
                            if 'PLAIN:' in data:
                                data = data.strip('PLAIN:').strip()
                            else:
                                #data = str(data)
                                data = self.decryptor.decrypt(data)


                            sys.stdout.write(data + '\n')
                            sys.stdout.flush()

            except KeyboardInterrupt:
                print 'Interrupted.'
                self.sock.close()
                break
Example #59
0
    def __init__(self, key):
        if type(key) in [str, bytes]:
            key = _RSA.importKey(key)
        self.rsa = key

        Key.__init__(self, 'RSA', nbits=self.rsa.size())

        self.oaep = PKCS1_OAEP.new(self.rsa, hashAlgo=SHA256)
        self.pss = PKCS1_PSS.new(self.rsa)