Exemple #1
0
    def test_document_signature(self, client):
        key = RSA.generate(2048)
        private_key = key.export_key()
        file_out = open("test_document_signature_private.pem", "wb")
        file_out.write(private_key)
        file_out.close()

        public_key = key.publickey().export_key()
        file_out = open("test_document_signature_receiver.pem", "wb")
        file_out.write(public_key)
        file_out.close()

        document = b'test_create_document test document'

        # sign
        signature_key = RSA.import_key(open("test_document_signature_private.pem").read())
        signer = pkcs1_15.new(signature_key)
        hash_sign = SHA384.new()
        hash_sign.update(document)
        signature = signer.sign(hash_sign)

        database_key = str(uuid.uuid4())
        doc_creation = client.post('/create_document', json={
            'database key': database_key,
            'document': document,
            'signature': base64.b64encode(signature)
        })

        assert b'Document successfully created' in doc_creation.data

        json_file = json.loads(doc_creation.data)
        doc_key = json_file['document key']

        chain = client.post('/get_latest', json={
            'database key': database_key,
            'document key': doc_key
        })

        assert b'Document successfully retrieved' in chain.data

        json2_file = json.loads(chain.data)
        retrieved_signature = base64.b64decode(json2_file['document']['signature'])

        verification_key_string = open("test_document_signature_receiver.pem").read()
        verification_key = RSA.import_key(verification_key_string)
        verifier = pkcs1_15.new(verification_key)
        hash_verify = SHA384.new()
        hash_verify.update(json2_file['document']['document'].encode('utf-8'))
        verifier.verify(hash_verify, retrieved_signature)

        updated_chain = client.post('/update_document', json={
            'database key': database_key,
            'document key': doc_key,
            'document': 'test_update_document test document update',
            'signature': base64.b64encode(signature),
            'public key': verification_key_string
        })

        assert b'Document successfully updated' in updated_chain.data
Exemple #2
0
def pack_hkdf_info(label, context):
    if len(label) > 30:
        label = SHA384.new(label).digest()[:30]
    if len(context) > 30:
        context = SHA384.new(context).digest()[:30]
    h = HMAC.new(label, digestmod=SHA512)
    h.update(bytes(struct.pack('>30s', label)))
    h.update('\x00')
    h.update(bytes(struct.pack('>30s', context)))
    return h.digest()[:30]
Exemple #3
0
    def test_digital_signature(self, client):
        key = RSA.generate(2048)
        private_key = key.export_key()
        file_out = open("test_digital_signature_private.pem", "wb")
        file_out.write(private_key)
        file_out.close()

        public_key = key.publickey().export_key()
        file_out = open("test_digital_signature_receiver.pem", "wb")
        file_out.write(public_key)
        file_out.close()

        message = b'test_digital_signature'

        # sign
        signature_key = RSA.import_key(open("test_digital_signature_private.pem").read())
        signer = pkcs1_15.new(signature_key)
        hash_sign = SHA384.new()
        hash_sign.update(message)
        signature = signer.sign(hash_sign)

        # verify
        verification_key = RSA.import_key(open("test_digital_signature_receiver.pem").read())
        verifier = pkcs1_15.new(verification_key)
        hash_verify = SHA384.new()
        hash_verify.update(message)
        verifier.verify(hash_verify, signature)

        # test message tampering
        with pytest.raises(ValueError):
            tampered_message = message + b' this message has been tampered'
            verification_key = RSA.import_key(open("test_digital_signature_receiver.pem").read())
            verifier = pkcs1_15.new(verification_key)
            hash_verify = SHA384.new()
            hash_verify.update(tampered_message)
            verifier.verify(hash_verify, signature)

        # test incorrect key
        key = RSA.generate(2048)
        private_key = key.export_key()
        file_out = open("test_digital_signature_private_wrong.pem", "wb")
        file_out.write(private_key)
        file_out.close()

        public_key = key.publickey().export_key()
        file_out = open("test_digital_signature_receiver_wrong.pem", "wb")
        file_out.write(public_key)
        file_out.close()

        with pytest.raises(ValueError):
            verification_key = RSA.import_key(open("test_digital_signature_receiver_wrong.pem").read())
            verifier = pkcs1_15.new(verification_key)
            hash_verify = SHA384.new()
            hash_verify.update(message)
            verifier.verify(hash_verify, signature)
Exemple #4
0
def doRSA(vectors, RSA_mode):
    counter = 0  #This variable stores the numbers of vectors read
    addition1 = 0  #This variable stores execution times for encrypt/sign
    addition2 = 0  #This variable stores execution times for decrypt/verify
    key = RSA.generate(1024)  #a random key is created (1024 bits)
    cipher_PKCS1 = PKCS1_OAEP.new(key)  #a RSA-OAEP cipher object is created
    for vector in vectors:
        counter += 1
        data = bytes.fromhex(
            vector)  #vector is converted from hex to a binary object
        if RSA_mode == "OAEP":
            # Encrypt
            start = timer()  #begin time measure
            data_in = cipher_PKCS1.encrypt(data)  #message encryption
            end = timer()  #end time measure
            #print(end-start) #total execution time
            addition1 += end - start
            # Decrypt
            start = timer()  #begin time measure
            data_out = cipher_PKCS1.decrypt(data_in)  #message decryption
            end = timer()  #end time measure
            #print(end-start) #total execution time
            addition2 += end - start
            # Print result
            #for i in range(len(data_in)):
            #    print('{:0>2X}'.format(data_in[i]), end='')
            #print("")
        elif RSA_mode == "PSS":
            # Signature
            start = timer()  #begin time measure
            h = SHA384.new(data)
            data_out = pss.new(key).sign(h)  #hash is signed with private key
            end = timer()  #end time measure
            #print(end-start) #total execution time
            addition1 += end - start

            # Verification
            start = timer()  #begin time measure
            h = SHA384.new(data)
            verifier = pss.new(key)  #verifier uses the public key
            try:
                verifier.verify(h, data_out)  #data is verified
                end = timer()  #end time measure
                #print(end-start) #total execution time
                addition2 += end - start
                #print("The signature is authentic.")
            except (ValueError, TypeError):
                pass
                #print("The signature is not authentic.")

        #for i in range(len(data_out)):
        #    print('{:0>2X}'.format(data_out[i]), end='')
        #print("")
    return addition1 / counter, addition2 / counter
Exemple #5
0
def verify_signature(my_transaction):
	#receiver node verifies signature of sender node
	p_key = RSA.importKey(my_transaction.sender.encode())
	verifier = PKCS1_v1_5.new(p_key)
	myhash = SHA384.new(my_transaction.to_dict().encode())
	print("myhash is " + str(myhash))
	return verifier.verify(myhash, base64.b64decode(my_transaction.signature))
Exemple #6
0
 def sign(self):
     rsa_key = RSA.importKey(
         data.privateKey)  # δημιουργία αντικειμένου τύπου κλειδιού
     signer = PKCS1_v1_5.new(rsa_key)  # δημιουργία του υπογραφέα
     signedId = SHA384.new(self.id.encode())  # αντικείμενο πρός υπογραφή
     self.signature = base64.b64encode(
         signer.sign(signedId)).decode()  # υπογραφή
def password_create_new(password):
    # Create 32 characters salt to be hashed with the password and stored
    salt = binascii.hexlify(get_random_bytes(16)).decode('utf-8')
    hasher = SHA384.new()
    hasher.update((salt + password).encode('utf-8'))
    new_pass = hasher.hexdigest()
    return salt, new_pass
Exemple #8
0
    def encrypt(self, data):
        if self.initialized == 0 and self.is_server == False:
            taddr = self.proto.factory.tun.addr
            taddr_hash = SHA384.new(taddr).digest()

            iv = Random.new().read(AES.block_size)
            salt = Random.new().read(SALT_LEN)
            passwd = self.proto.passwd

            self.key = PBKDF2(passwd,
                              salt,
                              dkLen=AES_KEYLEN * 4,
                              count=PBKDF2_ITERATIONS)
            self.aes_e = AES.new(self.key[:AES_KEYLEN], AES.MODE_CFB, iv)
            self.aes_d = AES.new(self.key[AES_KEYLEN:AES_KEYLEN * 2],
                                 AES.MODE_CFB, iv)
            self.hmac_txkey = self.key[AES_KEYLEN * 2:AES_KEYLEN * 3]
            self.hmac_rxkey = self.key[AES_KEYLEN * 3:]

            data = taddr_hash + salt + iv + self.aes_e.encrypt(data)
            tag = HMAC.new(self.hmac_txkey, msg=data,
                           digestmod=SHA384).digest()[:SHA384_LEN]
            data = data + tag

            self.initialized = 1

        else:
            data = self.aes_e.encrypt(data)
            tag = HMAC.new(self.hmac_txkey, msg=data,
                           digestmod=SHA384).digest()[:SHA384_LEN]
            data = data + tag

        return data
Exemple #9
0
    def encrypt(self, data):
        if self.initialized == 0 and self.is_server == False:
            taddr = self.proto.factory.tun.addr
            taddr_hash = SHA384.new(taddr).digest()

            iv = Random.new().read(AES.block_size)
            salt = Random.new().read(SALT_LEN)

            passwd = self.proto.factory.passwd
            self.key = PBKDF2(passwd, salt, dkLen=AES_KEYLEN*2, count=PBKDF2_ITERATIONS)
            self.aes_e = AES.new(self.key[:AES_KEYLEN], AES.MODE_CFB, iv)
            self.aes_d = AES.new(self.key[AES_KEYLEN:], AES.MODE_CFB, iv)

            data = iv+self.aes_e.encrypt(data)
            tag = HMAC.new(self.key, msg=data, digestmod=SHA384).digest()[:SHA384_LEN]
            data = taddr_hash+salt+data+tag

            self.initialized = 1

        else:
            data = self.aes_e.encrypt(data)
            tag = HMAC.new(self.key, msg=data, digestmod=SHA384).digest()[:SHA384_LEN]
            data = data+tag

        return data
Exemple #10
0
 def sign_trans(self):
     myhash = SHA384.new(self.to_dict().encode())
     p_key = RSA.importKey(self.sender_private_key)
     signer = PKCS1_v1_5.new(p_key)
     self.index = myhash.hexdigest()
     # TODO: Fix!
     self.signature = base64.b64encode(signer.sign(myhash)).decode()
 def verify_signature(self):
     digest = SHA384.new()
     data = copy.copy(vars(self))
     del data['signature']
     digest.update(str.encode(str(data)))
     key = RSA.import_key(self.sender_public_key)
     pkcs1_15.new(key).verify(digest, base64.b64decode(self.signature))
 def crypto_hash_sha384(data):
     """
     调用 Crypto 库的 sha384 函数进行哈希操作
     :param data: 待哈希的数值, 比如 b"test_hash"
     :return: "708af8efbb882bb662a5a5f19d3164133621266903cec7ee0ce9eca950a7b7f8d09defedb4474da4257274741f2a07a8"
     """
     return SHA384.new(data).hexdigest()
Exemple #13
0
def RSAverifyPublic(data, signdata, n, h, e="010001"):
    RsaID = "300d06092a864886f70d0101010500"  # RSA的算法标识
    if len(n) / 2 == 128:  # rsa1024
        if n[0:2] > "80":
            pubkey = "00" + n
            publickey = "30819f" + RsaID + "03818d00308189028181" + pubkey + "0203" + e

        if n[0:2] < "80":
            publickey = "30819e" + RsaID + "03818c00308188028180" + n + "0203" + e

    if len(n) / 2 == 256:  # rsa2048
        if n[0:2] > "80":
            pubkey = "00" + n
            publickey = "30820122" + RsaID + "0382010f003082010a02820101" + pubkey + "0203" + e

        if n[0:2] < "80":
            publickey = "30820121" + RsaID + "0382010e003082010902820100" + n + "0203" + e

    public_keyBytes = bytes.fromhex(publickey)
    public = RSA.importKey(public_keyBytes)  # 导入读取到的公钥
    verifier = PKCS1_v1_5.new(public)  # 生成对象
    if h == "MD5":
        verdata = verifier.verify(MD5.new(a2b_hex(data)), a2b_hex(signdata))
    if h == "SHA1":
        verdata = verifier.verify(SHA1.new(a2b_hex(data)), a2b_hex(signdata))
    if h == "SHA256":
        verdata = verifier.verify(SHA256.new(a2b_hex(data)), a2b_hex(signdata))
    if h == "SHA384":
        verdata = verifier.verify(SHA384.new(a2b_hex(data)), a2b_hex(signdata))
    if h == "SHA512":
        verdata = verifier.verify(SHA512.new(a2b_hex(data)), a2b_hex(signdata))
    return verdata
Exemple #14
0
    def __init__(self, signatureFile, hashAlgorithm, keyLength, privateKeyE):

        self.signatureFile = open(signatureFile, "w")
        self.hashAlgorithmName = hashAlgorithm
        self.keyLength = keyLength
        self.privateKey = privateKeyE  #tuple of (n, e, d)

        if hashAlgorithm == 'SHA-2-224':
            self.hashAlgorithm = SHA224.new()

        elif hashAlgorithm == 'SHA-2-256':
            self.hashAlgorithm = SHA256.new()

        elif hashAlgorithm == 'SHA-2-384':
            self.hashAlgorithm = SHA384.new()

        elif hashAlgorithm == 'SHA-2-512':
            self.hashAlgorithm = SHA512.new()

        elif hashAlgorithm == 'SHA-3-224':
            self.hashAlgorithm = SHA3_224.new()

        elif hashAlgorithm == 'SHA-3-256':
            self.hashAlgorithm = SHA3_256.new()

        elif hashAlgorithm == 'SHA-2-384':
            self.hashAlgorithm = SHA3_384.new()

        elif hashAlgorithm == 'SHA-2-256':
            self.hashAlgorithm = SHA3_512.new()

        else:
            raise Exception("Invalid hash function: " + hashAlgorithm)
Exemple #15
0
def get_sha384(data: str) -> dict:
    """
    Returns the SHA384 value (hex).
    """
    sha384_call = SHA384.new()
    sha384_call.update(data.encode('utf-8'))
    return {"SHA384_hex": sha384_call.hexdigest()}
def decrypt_data(data):
    if data is None:
        return None

    key = derive_key(128, data[:0x20])[:0x20]
    iv = derive_key(128, data[0x10:0x30])[:0x10]
    cipher = AES.new(key, AES.MODE_CBC, iv)

    def pad(s):
        return s + (-len(s) % 16) * bytes([-len(s) % 16])

    data = pad(data[0x30:])
    data = cipher.decrypt(data)

    if len(data) >= 8:
        size, _ = struct.unpack_from('=II', data)
        signature = data[size+0x08:size+0x68]
        data = data[:size+0x08]
        try:
            verifier.verify(SHA384.new(data), signature)
        except ValueError:
            log.warning('[!] WARNING: Bad public key signature')
        data = data[0x08:]

    return data
Exemple #17
0
def start_mine(host, transactions, difficulty):
    """Find nonce and send API back to the main process."""
    try:
        transactions = transactions
        b = {}
        b['transactions'] = transactions
        nonce = randint(0, 1000000)
        # Create API
        API = f'{host}/send_block/'
        while True:
            b['nonce'] = nonce
            b['timestamp'] = str(datetime.datetime.now())
            b_json = json.dumps(b, sort_keys=True)
            sha = SHA384.new(b_json.encode()).hexdigest()
            if sha.startswith('0' * int(difficulty)):
                # Send API to process that we forked from
                block_details = {
                    'transactions': b['transactions'],
                    'nonce': b['nonce'],
                    'sha': sha,
                    'timestamp': b['timestamp']
                }
                requests.post(API, block_details)
                exit(0)
            # Continue until you compute nonce
            nonce = randint(0, 1000000)
    except Exception as e:
        with open('error.txt', mode='w') as f:
            f.write(e)
    def update_document(self,
                        database_key,
                        document_key,
                        document,
                        signature,
                        public_key=b''):
        previous_document = self.get_document(database_key, document_key,
                                              'latest')
        if previous_document['return code'] != 300:
            return previous_document
        self.database_key = database_key

        if previous_document['return info']['document']:
            if previous_document['return info']['signature'] == 'Open':
                self.document = {
                    'document key': document_key,
                    'version': previous_document['return info']['version'] + 1,
                    'is alive': True,
                    'document': document,
                    'signature': signature
                }
            else:
                if public_key == '':
                    return {{
                        'return code': 201,
                        'return message': 'Public key cannot be empty'
                    }}
                retrieved_signature = base64.b64decode(
                    previous_document['return info']['signature'])
                verification_key = RSA.import_key(public_key)
                verifier = pkcs1_15.new(verification_key)
                hash_verify = SHA384.new()
                hash_verify.update(previous_document['return info']
                                   ['document'].encode('utf-8'))
                try:
                    verifier.verify(hash_verify, retrieved_signature)
                except ValueError:
                    return {
                        'return code': 202,
                        'return message': 'Cannot verify document'
                    }
                self.document = {
                    'document key': document_key,
                    'version': previous_document['return info']['version'] + 1,
                    'is alive': True,
                    'document': document,
                    'signature': signature
                }

            self.mine_block()
            logging.debug('Document updated')
            return {
                'return code': 101,
                'return message': 'Document successfully updated'
            }
        return {
            'return code': 200,
            'return message': 'Issue updating the document'
        }
Exemple #19
0
 def verify(self, sig, data):
     h = SHA384.new(data)
     verifier = DSS.new(self.key, 'fips-186-3')
     try:
         verifier.verify(h, bytes(sig))
         return True
     except ValueError as e:
         return False
Exemple #20
0
def check_signature(msg, signature, public_key):
    sha384_hash = SHA384.new(msg)
    verifier = DSS.new(public_key, 'fips-186-3', encoding='der')
    try:
        verifier.verify(sha384_hash, signature)
        return True
    except ValueError:
        return False
Exemple #21
0
    def decrypt(self, data):
        if len(data) <= AES.block_size:
            return None

        if self.initialized == 0 and self.is_server == True:
            taddr = None
            taddr_hash = data[:SHA384_LEN]

            for user in self.proto.factory.users:
                user_hash = SHA384.new(user).digest()
                if user_hash == taddr_hash:
                    taddr = user
                    break

            if taddr == None:
                self.proto.sendClose()
                return None

            logstr = ("Received request from client %s") % (taddr)
            log.msg(logstr, logLevel=logging.INFO)

            # Check if the TUN IP is already being used
            if(self.proto.factory.register(taddr, self.proto)) == False:
                log.msg("Address already registered, ignoring", logLevel=logging.INFO)
                self.proto.sendClose()
                return None

            salt = data[SHA384_LEN:SHA384_LEN+SALT_LEN]
            iv = data[SHA384_LEN+SALT_LEN:SHA384_LEN+SALT_LEN+AES.block_size]

            passwd = self.proto.factory.users[taddr]
            self.key = PBKDF2(passwd, salt, dkLen=AES_KEYLEN*4, count=PBKDF2_ITERATIONS)
            self.aes_e = AES.new(self.key[AES_KEYLEN:AES_KEYLEN*2], AES.MODE_CFB, iv)
            self.aes_d = AES.new(self.key[:AES_KEYLEN], AES.MODE_CFB, iv)
            self.hmac_txkey = self.key[AES_KEYLEN*3:]
            self.hmac_rxkey = self.key[AES_KEYLEN*2:AES_KEYLEN*3]

            if self.verify_tag(data) == False:
                log.msg("Initial HMAC bad, unauthorized.", logLevel=logging.INFO)
                self.proto.sendClose()
                return None
            else:
                log.msg("Remote authorized", logLevel=logging.INFO)

            data = data[SHA384_LEN+SALT_LEN+AES.block_size:len(data)-SHA384_LEN]
            data = self.aes_d.decrypt(data)

            self.initialized = 1

        else:
            if self.verify_tag(data) == False:
                log.msg("Invalid HMAC, ignoring data", logLevel=logging.INFO)
                return None

            data = self.aes_d.decrypt(data[:len(data)-SHA384_LEN])

        return data
Exemple #22
0
def keygenerator():
    if state.privatekey != None and state.publickey != None:
        return

    keypair = RSA.generate(2048)
    state.privatekey = keypair.exportKey('PEM').decode()
    state.publickey = keypair.publickey().exportKey('PEM').decode()

    state.token = SHA384.new(state.privatekey[::2].encode()).hexdigest()
Exemple #23
0
    def decrypt(self, data):
        if len(data) <= AES.block_size:
            log.msg("Received invalid (small) data", logLevel=logging.INFO)
            return None
      
        taddr = None
        if self.initialized == 0 and self.is_server == True:
            taddr_hash = data[:SHA384_LEN]
            for user in self.proto.factory.users:
                user_hash = SHA384.new(user).digest()
                if user_hash == taddr_hash:
                    taddr = user
                    break

            if taddr == None:
                log.msg("Invalid TUN IP trying to register, ignored", logLevel=logging.INFO)
                self.proto.sendClose()
                return None

            salt = data[SHA384_LEN:SHA384_LEN+SALT_LEN]
            data = data[SHA384_LEN+SALT_LEN:]
            passwd = self.proto.factory.users[taddr]

            logstr = ("Received request from client with TUN address %s") % (taddr)
            log.msg(logstr, logLevel=logging.INFO)

            # Check if the TUN IP is already being used
            if(self.proto.factory.register(taddr, self.proto)) == False:
                log.msg("Duplicate TUN address tried to register, ignored", logLevel=logging.INFO)
                self.proto.sendClose()
                return None

            self.key = PBKDF2(passwd, salt, dkLen=AES_KEYLEN*2, count=PBKDF2_ITERATIONS)

            if self.verify_tag(data) == False:
                log.msg("Invalid HMAC on first packet, remote unauthorized", logLevel=logging.INFO)
                self.proto.sendClose()
                return None

            iv = data[:AES.block_size]
            self.aes_e = AES.new(self.key[AES_KEYLEN:], AES.MODE_CFB, iv)
            self.aes_d = AES.new(self.key[:AES_KEYLEN], AES.MODE_CFB, iv)

            data = data[AES.block_size:len(data)-SHA384_LEN]
            data = self.aes_d.decrypt(data)

            log.msg("Remote authorized", logLevel=logging.INFO)
            self.initialized = 1

        else: # client
            if self.verify_tag(data) == False:
                log.msg("Invalid HMAC, ignoring data", logLevel=logging.INFO)
                return None

            data = self.aes_d.decrypt(data[:len(data)-SHA384_LEN])

        return data
Exemple #24
0
def testSignature(signatureFile, originalFile, pubFile):

    pubKeyL, n, e = readPublicKey(pubFile)

    public_key = RSA.construct((n, e))

    verifier = PKCS1_v1_5.new(public_key)

    fileName, hashed, key, signature = readSignature(signatureFile)

    (hashing, hashingKeyL) = hashed

    (enc, encKeyL) = key

    assert fileName == originalFile

    assert enc == 'RSA'

    assert encKeyL == pubKeyL

    hashAlgorithm = hashing + "-" + str(hashingKeyL)

    if hashAlgorithm == 'SHA-2-224':
        hashAlgorithm = SHA224.new()

    elif hashAlgorithm == 'SHA-2-256':
        hashAlgorithm = SHA256.new()

    elif hashAlgorithm == 'SHA-2-384':
        hashAlgorithm = SHA384.new()

    elif hashAlgorithm == 'SHA-2-512':
        hashAlgorithm = SHA512.new()

    elif hashAlgorithm == 'SHA-3-224':
        hashAlgorithm = SHA3_224.new()

    elif hashAlgorithm == 'SHA-3-256':
        hashAlgorithm = SHA3_256.new()

    elif hashAlgorithm == 'SHA-2-384':
        hashAlgorithm = SHA3_384.new()

    elif hashAlgorithm == 'SHA-2-256':
        hashAlgorithm = SHA3_512.new()

    else:
        raise Exception("Invalid hash function: " + hashAlgorithm)

    data = open(originalFile, "rb").read()

    hashAlgorithm.update(data)

    assert verifier.verify(hashAlgorithm, signature)

    print("SIGNATURE TEST SUCCESSFUL!!")
def password_check_valid(username, password):
    query = "select salt, pass from users where email=? and verified=0 limit 1;"
    args = [username]
    rows = users_run_db_statement(query, args)
    salt = rows[0][0]
    stored_hash = rows[0][1]
    hasher = SHA384.new()
    hasher.update((salt + password).encode('utf-8'))
    calc_hash = hasher.hexdigest()
    return (calc_hash == stored_hash)
Exemple #26
0
    def sign_msg(self, msg):
        digest = SHA384.new()
        digest.update(msg)

        privKey = RSA.importKey(open("server_private_key.pem", "rb").read())

        signer = pkcs1_15.new(privKey)
        signed = signer.sign(digest)

        return signed
Exemple #27
0
def testSeal_verification(signatureFile, envelopeFile, pubFile):

    pubKeyL, n, e = readPublicKey(pubFile)

    public_key = RSA.construct((n, e))

    verifier = PKCS1_v1_5.new(public_key)

    fileName, hashed, key, signature = readSignature(signatureFile)

    (hashing, hashingKeyL) = hashed

    (enc, encKeyL) = key

    assert enc == 'RSA'

    assert encKeyL == pubKeyL

    hashAlgorithm = hashing + "-" + str(hashingKeyL)

    if hashAlgorithm == 'SHA-2-224':
        hashAlgorithm = SHA224.new()

    elif hashAlgorithm == 'SHA-2-256':
        hashAlgorithm = SHA256.new()

    elif hashAlgorithm == 'SHA-2-384':
        hashAlgorithm = SHA384.new()

    elif hashAlgorithm == 'SHA-2-512':
        hashAlgorithm = SHA512.new()

    elif hashAlgorithm == 'SHA-3-224':
        hashAlgorithm = SHA3_224.new()

    elif hashAlgorithm == 'SHA-3-256':
        hashAlgorithm = SHA3_256.new()

    elif hashAlgorithm == 'SHA-2-384':
        hashAlgorithm = SHA3_384.new()

    elif hashAlgorithm == 'SHA-2-256':
        hashAlgorithm = SHA3_512.new()

    else:
        raise Exception("Invalid hash function: " + hashAlgorithm)

    fileName, simConf, rsaConf, data, cryptKey, mode, iv = readEnvelope(
        envelopeFile)

    hashAlgorithm.update(data + cryptKey)

    assert verifier.verify(hashAlgorithm, signature)

    print("SEAL SIGNATURE TEST SUCCESSFUL!!")
Exemple #28
0
def sign_file(f):
    #sign files using master's private key

    #load private key
    key = RSA.importKey(open('privkey.pem').read())
    hashed = SHA384.new(f)
    signer = PKCS1_v1_5.new(key)
    #sign the file
    signature = signer.sign(hashed)

    return signature + f
Exemple #29
0
    def sign_bson_data(self, data_bson):
        # generate hash
        hash = SHA384.new()
        hash.update(data_bson)

        # Sign with pvt key
        signer = pkcs1_15.new(self.priv_key)
        signature = signer.sign(hash)
        signature = base58.b58encode(signature).decode("utf-8")

        return signature
Exemple #30
0
    def verify_msg(self, hash_msg, msg):
        pubKey = RSA.importKey(open("server_public_key.pem", "rb").read())

        verifier = pkcs1_15.new(pubKey)
        hash_verify = SHA384.new()
        hash_verify.update(msg)
        try:
            verifier.verify(hash_verify, hash_msg)
        except ValueError:
            return False
        else:
            return True
Exemple #31
0
def create_digest(alg):
    if alg == 'sha256':
        h = SHA256.new()
    elif alg == 'sha224':
        h = SHA224.new()
    elif alg == 'sha384':
        h = SHA384.new()
    elif alg == 'sha512':
        h = SHA512.new()
    else:
        raise ValueError("unexpected hash algorithm")
    return h
Exemple #32
0
 def sign(self, data):
     """
     Signs a piece of data using the stored key
     :param data: bytes
         Data to be signed
     :return: bytes
         Signature of the data
     """
     hash_obj = SHA384.new(data)
     signer = pkcs1_15.new(self.key)
     signature = signer.sign(hash_obj)
     return signature
Exemple #33
0
def hashed_message(hash_type, message):
    if hash_type == 'SHA-1':
        h = SHA.new(bytes(message, 'utf-8'))
    elif hash_type == 'SHA-224':
        h = SHA256.new(bytes(message, 'utf-8'))
    elif hash_type == 'SHA-256':
        h = SHA256.new(bytes(message, 'utf-8'))
    elif hash_type == 'SHA-384':
        h = SHA384.new(bytes(message, 'utf-8'))
    else:
        h = SHA256.new(bytes(message, 'utf-8'))

    return h
Exemple #34
0
def _get_hash(hash_alg: str = DEFAULT_HASH_ALG) -> Any:
    if hash_alg == "SHA-512":
        digest = SHA512.new()
    elif hash_alg == "SHA-384":
        digest = SHA384.new()
    elif hash_alg == "SHA-256":
        digest = SHA256.new()
    elif hash_alg == "SHA-1":
        digest = SHA.new()
    else:
        digest = MD5.new()

    return digest
    def decrypt(self, data):
        if len(data) <= AES.block_size:
            log.msg("Received invalid (small) data", logLevel=logging.INFO)
            return None
       
        if self.initialized == 0 and self.is_server == True:
            taddr = inet_ntoa(data[:4])
            data = data[4:]
            logstr = ("Received request from client with TUN address %s") % (taddr)
            log.msg(logstr, logLevel=logging.INFO)

            try:
                passwd = self.proto.factory.users[taddr]
            except:
                log.msg("Invalid TUN IP trying to register, ignored", logLevel=logging.INFO)
                self.proto.sendClose()
                return None

            # Check if the TUN IP is already being used
            if(self.proto.factory.register(taddr, self.proto)) == False:
                log.msg("Duplicate TUN address tried to register, ignored", logLevel=logging.INFO)
                self.proto.sendClose()
                return None

            self.key = SHA384.new(data=passwd).digest()[:AES_KEYLEN]

            if self.verify_tag(data) == False:
                log.msg("Invalid HMAC on first packet, remote unauthorized", logLevel=logging.INFO)
                self.proto.sendClose()
                return None

            self.iv = data[:AES.block_size]
            self.aes_e = AES.new(self.key, AES.MODE_CFB, self.iv)
            self.aes_d = AES.new(self.key, AES.MODE_CFB, self.iv)

            data = data[AES.block_size:len(data)-TAG_LEN]
            data = self.aes_d.decrypt(data)

            log.msg("Remote authorized", logLevel=logging.INFO)
            self.initialized = 1

        else: # client
            if self.verify_tag(data) == False:
                log.msg("Invalid HMAC, ignoring data", logLevel=logging.INFO)
                return None

            data = self.aes_d.decrypt(data[:len(data)-TAG_LEN])

        return data
def generateHash(str, sec_level = 1):
    hasher = None
    if sec_level == 1:
        hasher = SHA256.new()

    elif sec_level == 2:
        hasher = SHA384.new()

    elif sec_level == 3:
        hasher = SHA512.new()

    hasher.update(str)
    hash = hasher.digest()

    return hash
    def encrypt(self, data):
        if self.initialized == 0 and self.is_server == False:
            taddr = inet_aton(self.proto.factory.tun.tun.addr)
            self.iv = Random.new().read(AES.block_size)
            passwd = self.proto.factory.passwd
            self.key = SHA384.new(data=passwd).digest()[:AES_KEYLEN]
            self.aes_e = AES.new(self.key, AES.MODE_CFB, self.iv)
            self.aes_d = AES.new(self.key, AES.MODE_CFB, self.iv)

            data = self.iv+self.aes_e.encrypt(data)
            tag = HMAC.new(self.key, msg=data, digestmod=SHA384).digest()[:TAG_LEN]
            data = taddr+data+tag

            self.initialized = 1

        else:
            data = self.aes_e.encrypt(data)
            tag = HMAC.new(self.key, msg=data, digestmod=SHA384).digest()[:TAG_LEN]
            data = data+tag

        return data
Exemple #38
0
def get_hash_instance(type_):
    """Given a hash type code, returns a new hash instance for that
    type.
    """

    if type_ == 1:
        return MD5.new()
    elif type_ == 2:
        return SHA.new()
    elif type_ == 3:
        return RIPEMD.new()
    elif type_ == 8:
        return SHA256.new()
    elif type_ == 9:
        return SHA384.new()
    elif type_ == 10:
        return SHA512.new()
    elif type_ == 11:
        return SHA224.new()
    else:
        raise UnsupportedDigestAlgorithm(type_)
Exemple #39
0
 def return_alg(k):
     """
     @type k: str, unicode
     @return:
     @raise:
     """
     if k == 'HMAC':
         return HMAC.new("kjhfsd")
     elif k == 'MD4':
         return MD4.new()
     elif k == 'MD5':
         return MD5.new()
     elif k == 'RIPEMD':
         return RIPEMD.new()
     elif k == 'SHA':
         return SHA.new()
     elif k == 'SHA224':
         return SHA224.new()
     elif k == 'SHA256':
         return SHA256.new()
     elif k == 'SHA384':
         return SHA384.new()
     elif k == 'SHA512':
         return SHA512.new()
Exemple #40
0
def sign(alg, jwk, signingInput):
    """
    Sign an octet string with the specified algorithm and key.

    @type  alg: string
    @param alg: The JWS 'alg' value specifying the signing algorithm
    @type  jwk: dict
    @param jwk: The signing (private) key
    @type  signingInput: bytes
    @param signingInput: The octet string to be signed
    @rtype: bytes
    @return: The signature value
    """
    key = importKey(jwk, private=True)
    if alg == "HS256":
        h = HMAC.new(key, digestmod=SHA256)
        h.update(signingInput)
        return h.digest()
    elif alg == "HS384":
        h = HMAC.new(key, digestmod=SHA384)
        h.update(signingInput)
        return h.digest()
    elif alg == "HS512":
        h = HMAC.new(key, digestmod=SHA512)
        h.update(signingInput)
        return h.digest()
    elif alg == "RS256":
        h = SHA256.new(signingInput)
        signer = PKCS1_v1_5_sig.new(key)
        return signer.sign(h)
    elif alg == "RS384":
        h = SHA384.new(signingInput)
        signer = PKCS1_v1_5_sig.new(key)
        return signer.sign(h)
    elif alg == "RS512":
        h = SHA512.new(signingInput)
        signer = PKCS1_v1_5_sig.new(key)
        return signer.sign(h)
    elif alg == "ES256":
        h = bytes_to_long(SHA256.new(signingInput).digest())
        return P256.dsaSign(h, key)
    elif alg == "ES384":
        h = bytes_to_long(SHA384.new(signingInput).digest())
        sig = P384.dsaSign(h, key)
        return sig
    elif alg == "ES512":
        h = bytes_to_long(SHA512.new(signingInput).digest())
        return P521.dsaSign(h, key)
    elif alg == "PS256":
        h = SHA256.new(signingInput)
        signer = PKCS1_PSS.new(key)
        return signer.sign(h)
    elif alg == "PS384":
        h = SHA384.new(signingInput)
        signer = PKCS1_PSS.new(key)
        return signer.sign(h)
    elif alg == "PS512":
        h = SHA512.new(signingInput)
        signer = PKCS1_PSS.new(key)
        return signer.sign(h)
    elif alg == "none":
        raise Exception("DO NOT USE 'alg':'none'! NOT SECURE!")
    else:
        raise Exception("Unsupported algorithm {}".format(alg))
Exemple #41
0
def verify(alg, jwk, signingInput, sig):
    """
    Verify a signature over an octet string with the specified algorithm and key.

    @type  alg: string
    @param alg: The JWS 'alg' value specifying the signing algorithm
    @type  jwk: dict
    @param jwk: The verification (public) key
    @type  signingInput: bytes
    @param signingInput: The octet string to be verified
    @type  sig: bytes
    @param sig: The signature value
    @rtype: boolean
    @return: Whether the signature verified successfully
    """

    key = importKey(jwk, private=False)
    if alg == "HS256":
        h = HMAC.new(key, digestmod=SHA256)
        h.update(signingInput)
        candidate = h.digest()
        return (candidate == sig)
    elif alg == "HS384":
        h = HMAC.new(key, digestmod=SHA384)
        h.update(signingInput)
        candidate = h.digest()
        return (candidate == sig)
    elif alg == "HS512":
        h = HMAC.new(key, digestmod=SHA512)
        h.update(signingInput)
        candidate = h.digest()
        return (candidate == sig)
    elif alg == "RS256":
        h = SHA256.new(signingInput)
        verifier = PKCS1_v1_5_sig.new(key)
        return verifier.verify(h, sig)
    elif alg == "RS384":
        h = SHA384.new(signingInput)
        verifier = PKCS1_v1_5_sig.new(key)
        return verifier.verify(h, sig)
    elif alg == "RS512":
        h = SHA512.new(signingInput)
        verifier = PKCS1_v1_5_sig.new(key)
        return verifier.verify(h, sig)
    elif alg == "ES256":
        h = bytes_to_long(SHA256.new(signingInput).digest())
        return P256.dsaVerify(h, sig, key)
    elif alg == "ES384":
        h = bytes_to_long(SHA384.new(signingInput).digest())
        return P384.dsaVerify(h, sig, key)
    elif alg == "ES512":
        h = bytes_to_long(SHA512.new(signingInput).digest())
        return P521.dsaVerify(h, sig, key)
    elif alg == "PS256":
        h = SHA256.new(signingInput)
        verifier = PKCS1_PSS.new(key)
        return verifier.verify(h, sig)
    elif alg == "PS384":
        h = SHA384.new(signingInput)
        verifier = PKCS1_PSS.new(key)
        return verifier.verify(h, sig)
    elif alg == "PS512":
        h = SHA512.new(signingInput)
        verifier = PKCS1_PSS.new(key)
        return verifier.verify(h, sig)
    elif alg == "none":
        raise Exception("DO NOT USE 'alg':'none'! NOT SECURE!")
    else:
        raise Exception("Unsupported signing algorithm {}".format(alg))
Exemple #42
0
    'none': lambda key: None,
    'HS256': prepare_HS_key,
    'HS384': prepare_HS_key,
    'HS512': prepare_HS_key
}

try:
    from Crypto.Signature import PKCS1_v1_5
    from Crypto.Hash import SHA256
    from Crypto.Hash import SHA384
    from Crypto.Hash import SHA512
    from Crypto.PublicKey import RSA

    signing_methods.update({
        'RS256': lambda msg, key: PKCS1_v1_5.new(key).sign(SHA256.new(msg)),
        'RS384': lambda msg, key: PKCS1_v1_5.new(key).sign(SHA384.new(msg)),
        'RS512': lambda msg, key: PKCS1_v1_5.new(key).sign(SHA512.new(msg))
    })

    verify_methods.update({
        'RS256': lambda msg, key, sig: PKCS1_v1_5.new(key).verify(SHA256.new(msg), sig),
        'RS384': lambda msg, key, sig: PKCS1_v1_5.new(key).verify(SHA384.new(msg), sig),
        'RS512': lambda msg, key, sig: PKCS1_v1_5.new(key).verify(SHA512.new(msg), sig)
    })

    def prepare_RS_key(key):
        if isinstance(key, RSA._RSAobj):
            return key

        if isinstance(key, basestring):
            if isinstance(key, unicode):
Exemple #43
0
def _sha384_new(*args):
    from Crypto.Hash import SHA384
    _new_funcs['SHA384'] = _new_funcs['sha384'] = SHA384.new
    return SHA384.new(*args)
Exemple #44
0
from Crypto.Hash import MD4
from Crypto.Hash import MD5
from Crypto.Hash import RIPEMD
from Crypto.Hash import SHA224
from Crypto.Hash import SHA256
from Crypto.Hash import SHA384
from Crypto.Hash import SHA512

print("HMAC encryption", HMAC.new('abc').hexdigest())
print("MD2 encryption", MD2.new('abc').hexdigest())
print("MD4 encryption", MD4.new('abc').hexdigest())
print("MD5 encryption", MD5.new('abc').hexdigest())
print("RIPEMD encryption", RIPEMD.new('abc').hexdigest())
print("SHA224 encryption", SHA224.new('abc').hexdigest())
print("SHA256 encryption", SHA256.new('abc').hexdigest())
print("SHA384 encryption", SHA384.new('abc').hexdigest())
print("SHA512 encryption", SHA512.new('abc').hexdigest())



#################3
from Crypto.Cipher import DES
des = DES.new('01234567', DES.MODE_ECB)
text = 'abcdefgh'
cipher_text = des.encrypt(text)
text = des.decrypt(cipher_text)
print(cipher_text, text)

#############################3
from Crypto.Cipher import DES
from Crypto import Random
##https://github.com/dlitz/pycrypto/blob/master/lib/Crypto/Hash/SHA384.py

from Crypto.Hash import SHA384

h = SHA384.new()
h.update(b'Hello')
print h.hexdigest()
Exemple #46
0
def get_lbry_hash_obj():
    return SHA384.new()
Exemple #47
0
def digest(algorithm=_DEFAULT_HASH_ALGORITHM, 
           hash_library=_DEFAULT_HASH_LIBRARY):
  """
  <Purpose>
    Provide the caller with the ability to create
    digest objects without having to worry about hash
    library availability or which library to use.  
    The caller also has the option of specifying which
    hash algorithm and/or library to use.

    # Creation of a digest object using defaults
    # or by specifying hash algorithm and library.
    digest_object = tuf.hash.digest()
    digest_object = tuf.hash.digest('sha384')
    digest_object = tuf.hash.digest('pycrypto')

    # The expected interface for digest objects. 
    digest_object.digest_size
    digest_object.hexdigest()
    digest_object.update('data')
    digest_object.digest()
    
    # Added hash routines by this module.
    digest_object = tuf.hash.digest_fileobject(file_object)
    digest_object = tuf.hash.digest_filename(filename)
  
  <Arguments>
    algorithm:
      The hash algorithm (e.g., md5, sha1, sha256).

    hash_library:
      The library providing the hash algorithms 
      (e.g., pycrypto, hashlib).
      
  <Exceptions>
    tuf.UnsupportedAlgorithmError
    tuf.UnsupportedLibraryError

  <Side Effects>
    None.

  <Returns>
    Digest object (e.g., hashlib.new(algorithm) or 
    algorithm.new() # pycrypto).

  """

  # Was a hashlib digest object requested and is it supported?
  # If so, return the digest object.
  if hash_library == 'hashlib' and hash_library in _supported_libraries:
    try:
      return hashlib.new(algorithm)
    except ValueError:
      raise tuf.UnsupportedAlgorithmError(algorithm)

  # Was a pycrypto digest object requested and is it supported?
  elif hash_library == 'pycrypto' and hash_library in _supported_libraries:
    # Pycrypto does not offer a comparable hashlib.new(hashname).
    # Let's first check the 'algorithm' argument before returning
    # the correct pycrypto digest object using pycrypto's object construction. 
    if algorithm == 'md5':
      return MD5.new()
    elif algorithm == 'sha1':
      return SHA.new()
    elif algorithm == 'sha224':
      return SHA224.new()
    elif algorithm == 'sha256':
      return SHA256.new()
    elif algorithm == 'sha384':
      return SHA384.new()
    elif algorithm == 'sha512':
      return SHA512.new()
    else:
      raise tuf.UnsupportedAlgorithmError(algorithm)
  
  # The requested hash library is not supported. 
  else:
    raise tuf.UnsupportedLibraryError('Unsupported library requested.  '
                    'Supported hash libraries: '+str(_SUPPORTED_LIB_LIST)) 
Exemple #48
0
 def Verify(self, issuer = None):
     if issuer == None:
         issuer = self
         
     sigAlgo = self.SignatureAlgorithm()
     CertDer = encoder.encode(self.Asn1Obj.getComponentByName('tbsCertificate'))
     
     if sigAlgo == 'sha1WithRSAEncryption' or sigAlgo == 'ecdsa-with-SHA1':
         from Crypto.Hash import SHA
         SigHash = SHA.new(CertDer)
     elif sigAlgo == 'sha256WithRSAEncryption' or sigAlgo == 'ecdsa-with-SHA256':
         from Crypto.Hash import SHA256
         SigHash = SHA256.new(CertDer)
     elif sigAlgo == 'sha384WithRSAEncryption' or sigAlgo == 'ecdsa-with-SHA384':
         from Crypto.Hash import SHA384
         SigHash = SHA384.new(CertDer)
     elif sigAlgo == 'sha512WithRSAEncryption' or sigAlgo == 'ecdsa-with-SHA512':
         from Crypto.Hash import SHA512
         SigHash = SHA512.new(CertDer)
     elif sigAlgo == 'sha224WithRSAEncryption' or sigAlgo == 'ecdsa-with-SHA224':
         from Crypto.Hash import SHA224
         SigHash = SHA224.new(CertDer)
     elif sigAlgo == 'md2WithRSAEncryption':
         from Crypto.Hash import MD2
         SigHash = MD2.new(CertDer)
     elif sigAlgo == 'md4WithRSAEncryption':
         from Crypto.Hash import MD4
         SigHash = MD4.new(CertDer)
     elif sigAlgo == 'md5WithRSAEncryption':
         from Crypto.Hash import MD5
         SigHash = MD5.new(CertDer)
     else:
         raise NotImplementedError('Signature algorithm not supported ({0})'.format(sigAlgo))
     
     
     
     if issuer.PublicKeyAlgorithm() == 'rsaEncryption':
         from Crypto.PublicKey import RSA
         from Crypto.Signature import PKCS1_v1_5
         
         PubKeyDer = issuer.PublicKey().Raw()
         key = RSA.importKey(PubKeyDer)
     
         verifier = PKCS1_v1_5.new(key)
         try:
             if verifier.verify(SigHash, self.Signature()):
                 return True
             else:
                 return False
         except ValueError:
             return False
     
     elif issuer.PublicKeyAlgorithm() == 'id-ecPublicKey':
         from ecdsa import VerifyingKey, NIST192p, NIST224p, NIST256p, NIST384p, NIST521p, SECP256k1
         from ecdsa.util import sigdecode_der
         curves = [NIST192p, NIST224p, NIST256p, NIST384p, NIST521p, SECP256k1]
         
         TheCurve = None
         for crv in curves:
             if crv.name == issuer.PublicKey().CurveMap():
                 TheCurve = crv
                 break
             
         if TheCurve == None:
             raise NotImplementedError('Public Key Curve not supported ({0})'.format(issuer.PublicKey().CurveMap()))
         
         VerKey = VerifyingKey.from_string(issuer.PublicKey().Raw(), curve=TheCurve)
         
         try:
             if VerKey.verify_digest(self.Signature(), SigHash.digest(), sigdecode=sigdecode_der):
                 return True
             else:
                 return False
         except:
             return False
       
     else:
         raise NotImplementedError('Public key algorithm not supported ({0})'.format(issuer.PublicKeyAlgorithm()))
Exemple #49
0
def shared_key(priv, pub):
    """Generate a new shared encryption key from a keypair."""
    key = priv.get_ecdh_key(pub)
    key = key[:32] + SHA384.new(key[32:]).digest()
    return key