Beispiel #1
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
 def crypto_hash_sha384(data):
     """
     调用 Crypto 库的 sha384 函数进行哈希操作
     :param data: 待哈希的数值, 比如 b"test_hash"
     :return: "708af8efbb882bb662a5a5f19d3164133621266903cec7ee0ce9eca950a7b7f8d09defedb4474da4257274741f2a07a8"
     """
     return SHA384.new(data).hexdigest()
Beispiel #3
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
Beispiel #4
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
    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
Beispiel #7
0
def sign(message, priv_key, hashAlg="SHA-256"):
    global hash
    hash = hashAlg
    signer = PKCS1_v1_5.new(priv_key)
    if (hash == "SHA-512"):
        digest = SHA512.new()
    elif (hash == "SHA-384"):
        digest = SHA384.new()
    elif (hash == "SHA-256"):
        digest = SHA256.new()
    elif (hash == "SHA-1"):
        digest = SHA.new()
    else:
        digest = MD5.new()
    digest.update(message)
    return signer.sign(digest)
Beispiel #8
0
    def test_1_auth_create_db(self):
        # deploy app
        index.server.start()

        schema_def = {
            "description": "this is my database",
            "unique": "r8and0mseEd905",
            "encoder": "example.com/autoencoder/API",
            "codelen": 30,
            "metadata": {
                "name": "string",
                "age": "number"
            }
        }
        data_ = {"schema": schema_def}
        data_bson = bson.dumps(data_)
        # generate hash
        hash = SHA384.new()
        hash.update(data_bson)

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

        url = "http://127.0.0.1:5001/db/create"

        headers = CaseInsensitiveDict()
        headers["Content-Type"] = "application/json"

        data = {"data": data_, "signature": signature}

        data = json.dumps(data)

        resp = requests.post(url, headers=headers, data=data)

        database_name_ = resp.json()["database_name"]

        schema_def = schema.generate_schema(schema_def)
        database_name = CID.doc2CID(schema_def)

        index.server.terminate()
        index.server.join()

        self.assertEqual(database_name, database_name_,
                         "DB name doesn't match")
Beispiel #9
0
 def verify(self, data, sig):
     """
     Verifies the signature against the provided piece of data
     :param data: bytes
         The data that was signed
     :param sig: bytes
         The signature associated with the data
     :return: bool
         Whether verification passed or not
     """
     hash_obj = SHA384.new(data)
     verifier = pkcs1_15.new(self.pubkey)
     try:
         verifier.verify(hash_obj, sig)
         return True
     except Exception:
         return False
def verify(message, signature, pub_key):
    signer = PKCS1_v1_5.new(pub_key)
    if (hash == "SHA-512"):
        digest = SHA512.new()
    elif (hash == "SHA-384"):
        digest = SHA384.new()
    elif (hash == "SHA-256"):
        digest = SHA256.new()
    elif (hash == "SHA-1"):
        digest = SHA.new()
    else:
        digest = MD5.new()
    digest.update(message)
    #return signer.verify(digest, signature)
    if signer.verify(digest,b64decode(signature)):
        return True
    return False
def generate_hash(string, type):
    if type not in ['SHA1', 'SHA224', 'SHA256', 'SHA384', 'SHA512']:
        print("unknown type of hash")
        return
    if type == 'SHA1':
        obj = SHA1.new()
    if type == 'SHA224':
        obj = SHA224.new()
    if type == 'SHA256':
        obj = SHA256.new()
    if type == 'SHA384':
        obj = SHA384.new()
    if type == 'SHA512':
        obj = SHA512.new()

    obj.update(string.encode())
    return obj.hexdigest()
    def delete_document(self, database_key, document_key, public_key=b''):
        previous_document = self.get_document(database_key, document_key,
                                              'latest')
        if previous_document['return code'] != 300:
            return previous_document

        if not previous_document['return info']['is alive']:
            return {
                'return code': 203,
                'return message': 'Document is already dead'
            }

        if previous_document['return info']['signature'] != 'Open':
            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.database_key = database_key
        self.document = {
            'document key': document_key,
            'version': previous_document['return info']['version'] + 1,
            'is alive': False,
            'document': previous_document['return info']['document'],
            'signature': previous_document['return info']['signature']
        }
        self.mine_block()
        return {
            'return code': 102,
            'return message': 'Document successfully deleted'
        }
Beispiel #13
0
def sign(message, priv_key, hash_alg="SHA-256"):
    global m_hash
    m_hash = hash_alg
    signer = PKCS1_v1_5.new(priv_key)
    if m_hash == "SHA-512":
        digest = SHA512.new()
    elif m_hash == "SHA-384":
        digest = SHA384.new()
    elif m_hash == "SHA-256":
        digest = SHA256.new()
    elif m_hash == "SHA-1":
        digest = SHA.new()
    else:
        digest = MD5.new()
    digest.update(message)
    print("esse eh o hash: " + str(digest.hexdigest()))
    return signer.sign(digest)
Beispiel #14
0
def md_sha_hash(flag, text):
    hash_text = None
    if flag == 'MD2':
        h = MD2.new()
        h.update(text)
        hash_text = h.hexdigest()
    elif flag == 'MD4':
        h = MD4.new()
        h.update(text)
        hash_text = h.hexdigest()
    elif flag == 'MD5':
        h = MD5.new()
        h.update(text)
        hash_text = h.hexdigest()
    elif flag == 'SHA1':
        h = SHA1.new()
        h.update(text)
        hash_text = h.hexdigest()
    elif flag == 'SHA224':
        h = SHA224.new()
        h.update(text)
        hash_text = h.hexdigest()
    elif flag == 'SHA256':
        h = SHA256.new()
        h.update(text)
        hash_text = h.hexdigest()
    elif flag == 'SHA384':
        h = SHA384.new()
        h.update(text)
        hash_text = h.hexdigest()
    elif flag == 'SHA512':
        h = SHA512.new()
        h.update(text)
        hash_text = h.hexdigest()
    elif flag == 'RIPEMD':
        h = RIPEMD.new()
        h.update(text)
        hash_text = h.hexdigest()
    elif flag == 'RIPEMD160':
        h = RIPEMD160.new()
        h.update(text)
        hash_text = h.hexdigest()
    else:
        return {'error': False, 'msg': u'未知hash算法!'}
    return {'error': True, 'msg': hash_text}
Beispiel #15
0
    def sign(self, message, hash_alg="SHA-256"):
        """ Sign a message with the private key """

        signer = PKCS1_v1_5.new(self.private_key)

        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()

        digest.update(message)
        return signer.sign(digest)
Beispiel #16
0
def digest(message):
    global hash
    #hash = hashAlg
    #signer = PKCS1_v1_5.new(priv_key)

    if (hash == "SHA-512"):
        digest = SHA512.new()
    elif (hash == "SHA-384"):
        digest = SHA384.new()
    elif (hash == "SHA-256"):
        digest = SHA256.new()
    elif (hash == "SHA-1"):
        digest = SHA.new()
    else:
        digest = MD5.new()
    digest.update(message)
    #return signer.sign(digest)
    return str(digest.digest())
Beispiel #17
0
def hashing(func, str):
    if func == 0:
        result = MD5.new(str)
        return result.hexdigest()
    if func == 1:
        result = SHA1.new(str)
        return result.hexdigest()
    if func == 2:
        return SHA256.new(str).hexdigest()
    if func == 3:
        result = SHA224.new(str)
        return result.hexdigest()
    if func == 4:
        result = SHA384.new(str)
        return result.hexdigest()
    if func == 5:
        result = SHA512.new(str)
        return result.hexdigest()
Beispiel #18
0
    def verify(self, message, signature, hash_alg="SHA-256"):
        """ Verify the signature of a message using public key """

        signer = PKCS1_v1_5.new(self.public_key)

        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()

        digest.update(message)
        return signer.verify(digest, signature)
Beispiel #19
0
    def function(self):
        if (self.hash == 'keccak'):
            self.digest = keccak.new(digest_bits=512)
            self.digest.update(self.text)
        elif (self.hash == 'SHA224'):
            self.digest = SHA224.new()
            self.digest.update(self.text)
        elif (self.hash == 'SHA256'):
            self.digest = SHA256.new()
            self.digest.update(self.text)
        elif (self.hash == 'SHA384'):
            self.digest = SHA384.new()
            self.digest.update(self.text)
        elif (self.hash == 'SHA512'):
            self.digest = SHA512.new()
            self.digest.update(self.text)

        return self.digest.hexdigest()
Beispiel #20
0
def do_verifier_login(credential,proof,nonce,tokenPrivateKey):
    session = requests.Session()

    req1 = session.get("http://127.0.0.1:5000/ver_opps/login")
    if req1.status_code != 200:
        raise ConnectionError
    
    challenge = bytes.fromhex(req1.json())
    signer = pkcs1_15.new(RSA.import_key(tokenPrivateKey))
    h = SHA384.new(challenge)
    challengeResponse = signer.sign(h).hex()

    req2 = session.post("http://127.0.0.1:5000/ver_opps/login",
                              data=json.dumps({'credential':credential,'proof':proof,'nonce':nonce,'challengeResponse':challengeResponse},
                              cls=CredentialEncoder),
                              headers={'content-type':'application/json'})
    if req2.status_code == 200:
        return session
def CreateMessageDigest(message, digest_method):
    if digest_method == "SHA-1":
        digest = SHA.new()
    elif digest_method == "SHA-2-224":
        digest = SHA224.new()
    elif digest_method == "SHA-2-256":
        digest = SHA256.new()
    elif digest_method == "SHA-2-384":
        digest = SHA384.new()
    elif digest_method == "SHA-2-512":
        digest = SHA512.new()

    message = str(message)

    print "Message to digest: " + message
    digest.update(message)
    print "Digested message: " + digest.hexdigest()

    print ""
    return digest.hexdigest()
Beispiel #22
0
def sign(msg):
    if type(msg) is not bytes:
        msg = bytes(msg, 'utf8')
    keyPair = RSA.RsaKey(
        n=
        122929120347181180506630461162876206124588624246894159983930957362668455150316050033925361228333120570604695808166534050128069551994951866012400864449036793525176147906281580860150210721340627722872013368881325479371258844614688187593034753782177752358596565495566940343979199266441125486268112082163527793027,
        e=65537,
        d=
        51635782679667624816161506479122291839735385241628788060448957989505448336137988973540355929843726591511533462854760404030556214994476897684092607183504108409464544455089663435500260307179424851133578373222765508826806957647307627850137062790848710572525309996924372417099296184433521789646380579144711982601,
        p=
        9501029443969091845314200516854049131202897408079558348265027433645537138436529678958686186818098288199208700604454521018557526124774944873478107311624843,
        q=
        12938505355881421667086993319210059247524615565536125368076469169929690129440969655350679337213760041688434152508579599794889156578802099893924345843674089,
        u=3286573208962127166795043977112753146960511781843430267174815026644571470787675370042644248296438692308614275464993081581475202509588447127488505764805156
    )
    signer = pkcs1_15.new(keyPair)
    hsh = SHA384.new()
    hsh.update(msg)
    signature = signer.sign(hsh)

    return signature
    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
Beispiel #24
0
def submit_post(post_payload, signature):
    # validate the post_payload data
    validate_post_payload(post_payload, signature)
    # create the bytes representation of the data
    post_payload_bytes = pickle.dumps(post_payload)
    # create a sha384 hasher
    hasher = SHA384.new()
    # process the post_payload data
    hasher.update(post_payload_bytes)
    # retrieve the public key from the signer
    poster_pk = post_payload.poster_public_register['pk']
    poster_pk = RSA.import_key(poster_pk)
    # create a signer object
    validator = pkcs1_15.new(poster_pk)
    # call verify with hasher and signature to validate. No errors = valid
    validator.verify(hasher, signature)

    # create a new _Post object
    new_post = _Post(post_payload, signature)
    # add the post to pending posts
    add_post_to_pending_posts(new_post)
Beispiel #25
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_)
Beispiel #26
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_)
Beispiel #27
0
    def startRC4(self, plaintext,
                 outputfilename):  #possibly input a filestream
        #print("PLAINTEXT OF STREAM: {0}".format(plaintext))
        if self.communicate_flag:
            rc_cipher = RC4(self.symmetricKey)
            x = 0  #chunk number
            out_file = open(outputfilename, "wb")
            hasher = SHA384.new()
            while (x + 1) * BLOCK_SIZE < len(plaintext):

                ciphertext = rc_cipher.run(plaintext[x * BLOCK_SIZE:(x + 1) *
                                                     BLOCK_SIZE])
                ciphertext = array.array(
                    'B', ciphertext).tobytes()  #last 6 bytes will be new key
                hasher.update(ciphertext)
                self.symmetricKey = ciphertext[len(ciphertext) -
                                               SYMMETRIC_KEY_SIZE:]
                #print("Bob {0}: {1}".format(x,self.symmetricKey))
                x = x + 1
                #print("CIPHERTEXT OF STREAM: {0}".format(ciphertext))
                out_file.write(ciphertext)
                rc_cipher.changeKey(self.symmetricKey)
                #hash ciphertext?
                #change key?

            ciphertext = rc_cipher.run(
                plaintext[x * BLOCK_SIZE:len(plaintext) -
                          SHA384_SIZE])  #is -1 correct?
            ciphertext = array.array('B', ciphertext).tobytes()
            hasher.update(ciphertext)
            endhash = plaintext[len(plaintext) - SHA384_SIZE:]
            #print("THIS HASHES DIGEST {0}".format(hasher.digest()))
            #print("DIGEST OF ALICE'S HASH {0}".format(endhash))

            #print("RC4 CIPHERTEXT: {0}".format(ciphertext))
            out_file.write(ciphertext)
            out_file.close()
            self.validateDigest(endhash, hasher.digest())
        else:
            print("Unable to communicate")
Beispiel #28
0
def doSHA(vectors, length, version):
    counter = 0
    addition = 0
    for vector in vectors:
        counter += 1
        data = bytes.fromhex(
            vector)  #vector is converted from hex to a binary object
        if version == 2:
            if length == 384:
                start = timer()  #begin time measure
                h = SHA384.new()
                h.update(data)  #message is hashed
                end = timer()  #end time measure
                #print(end-start) #total execution time
                addition += end - start
            elif length == 512:
                start = timer()  #begin time measure
                h = SHA512.new()
                h.update(data)  #message is hashed
                end = timer()  #end time measure
                #print(end-start) #total execution time
                addition += end - start
            #print(h.hexdigest())
        elif version == 3:
            if length == 384:
                start = timer()  #begin time measure
                h = SHA3_384.new()
                h.update(data)  #message is hashed
                end = timer()  #end time measure
                #print(end-start) #total execution time
                addition += end - start
            elif length == 512:
                start = timer()  #begin time measure
                h = SHA3_512.new()
                h.update(data)  #message is hashed
                end = timer()  #end time measure
                #print(end-start) #total execution time
                addition += end - start
            #print(h.hexdigest())
    return addition / counter
Beispiel #29
0
    def identify_hash(self, hash2use):
        """ Identify type of cryptographic hashing to use for processing.

        :param hash2use: Value indicating type of hashing desired based upon user's input
        :return: No explicit value returned. Variables set for further processing.

        """
        if hash2use == 1:
            self.h = RIPEMD.new()
            self.hstr = 'ripemd160'
        elif hash2use == 2:
            self.h = SHA224.new()
            self.hstr = 'sha224'
        elif hash2use == 3:
            self.h = SHA256.new()
            self.hstr = 'sha256'
        elif hash2use == 4:
            self.h = SHA384.new()
            self.hstr = 'sha384'
        elif hash2use == 5:
            self.h = SHA512.new()
            self.hstr = 'sha512'
Beispiel #30
0
def verify_signature (json_data, pub_key, signature):
    
    ret = True

    binary_data = bson.dumps(json_data)

    # generate hash
    hash = SHA384.new()
    hash.update(binary_data)
    
    signature = base58.b58decode(signature)

    # Verify with pub key
    verifier = pkcs1_15.new(pub_key)
    
    try:
        verifier.verify(hash, signature)
    except Exception as e:
        logging.debug(e)
        ret = False

    return ret
Beispiel #31
0
def getHashValue(toHash: str, hashSize: int) -> str:
    if hashSize == 256:
        newHash = SHA256.new()
        newHash.update(toHash.encode('utf-8'))
        return newHash.hexdigest()
    elif hashSize == 224:
        newHash = SHA224.new()
        newHash.update(toHash.encode('utf-8'))
        return newHash.hexdigest()
    elif hashSize == 384:
        newHash = SHA384.new()
        newHash.update(toHash.encode('utf-8'))
        return newHash.hexdigest()
    elif hashSize == 512:
        newHash = SHA512.new()
        newHash.update(toHash.encode('utf-8'))
        return newHash.hexdigest()
    elif hashSize == 160:
        newHash = sha1(toHash.encode('utf-8'))
        return newHash.hexdigest()
    else:
        raise TypeError("Invalid Hash Size")
Beispiel #32
0
    def startRC4(self, plaintext,
                 outputfilename):  #possibly input a filestream
        if self.communicate_flag:
            rc_cipher = RC4(self.symmetricKey)
            x = 0  #chunk number
            out_file = open(outputfilename, "wb")
            hasher = SHA384.new()
            while (x + 1) * (BLOCK_SIZE - SYMMETRIC_KEY_SIZE) < len(plaintext):
                self.symmetricKey = get_random_bytes(
                    SYMMETRIC_KEY_SIZE
                )  # New key to be used, should this be done?

                message = plaintext[x *
                                    (BLOCK_SIZE - SYMMETRIC_KEY_SIZE):(x + 1) *
                                    (BLOCK_SIZE -
                                     SYMMETRIC_KEY_SIZE)] + self.symmetricKey
                hasher.update(message)
                ciphertext = rc_cipher.run(message)
                ciphertext = array.array('B', ciphertext).tobytes()
                #print("Alice {0}: {1}".format(x,self.symmetricKey))
                x = x + 1

                out_file.write(ciphertext)

                rc_cipher.changeKey(self.symmetricKey)

            #self.symmetricKey = get_random_bytes(SYMMETRIC_KEY_SIZE)  #!! Don't need to have a new key at the end of the message
            message = plaintext[x * (BLOCK_SIZE - SYMMETRIC_KEY_SIZE):]
            hasher.update(message)
            ciphertext = rc_cipher.run(message)
            ciphertext = array.array('B', ciphertext).tobytes()

            out_file.write(ciphertext)
            out_file.write(hasher.digest())
            out_file.close()
        else:
            print("Unable to communicate")
Beispiel #33
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()
Beispiel #34
0
def get_lbry_hash_obj():
    return SHA384.new()
Beispiel #35
0
    u'none': lambda key: None,
    u'HS256': prepare_HS_key,
    u'HS384': prepare_HS_key,
    u'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({
        u'RS256':
        lambda msg, key: PKCS1_v1_5.new(key).sign(SHA256.new(msg)),
        u'RS384':
        lambda msg, key: PKCS1_v1_5.new(key).sign(SHA384.new(msg)),
        u'RS512':
        lambda msg, key: PKCS1_v1_5.new(key).sign(SHA512.new(msg))
    })
    verify_methods.update({
        u'RS256':
        lambda msg, key, sig: PKCS1_v1_5.new(key).verify(SHA256.new(msg), sig),
        u'RS384':
        lambda msg, key, sig: PKCS1_v1_5.new(key).verify(SHA384.new(msg), sig),
        u'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
import string
import time


#checks if the files have the correct extensions
def fileExt():
    if (sys.argv[1][-4:] == ".txt"):
        print "Hashing ", (sys.argv[1])
        return 1
    else:
        return -1


validFile = fileExt()

if (validFile == -1):
    print "incorrect file type"
    sys.exit()

h = SHA384.new()

#for each .txt file in command line arguments generate a message digest (hash) and print the time taken in seconds for each file
for i in range(1, len(sys.argv)):
    fin = open(sys.argv[i], "r", 0)
    start = time.time()
    for readBlock in iter(lambda: fin.read(1), ""):
        h.update(readBlock)
    print h.hexdigest()
    end = time.time()
    print "Time taken:", end - start, "seconds"
Beispiel #37
0
def hashof(data: bytes) -> SHA384.SHA384Hash:
    'Computes the SHA384 digest of the message.'
    return SHA384.new(data)
Beispiel #38
0
def _sha384_new(*args):
    from Crypto.Hash import SHA384
    _new_funcs['SHA384'] = _new_funcs['sha384'] = SHA384.new
    return SHA384.new(*args)
Beispiel #39
0
##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()
Beispiel #40
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)) 
Beispiel #41
0
def get_lbry_hash_obj():
    return SHA384.new()
from Crypto.Signature import PKCS1_v1_5
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA384

message = b'123456'

# ===== Creating a signature =====
key = RSA.generate(2048)
private_key = key


signer = PKCS1_v1_5.new(private_key)
hash_object = SHA384.new(message)

signature = signer.sign(hash_object)

# ===== Verifying a signature =====

public_key = key.publickey()
verifier = PKCS1_v1_5.new(public_key)

hash_object = SHA384.new()
hash_object.update(message)
if verifier.verify(hash_object, signature):
    print('The signature is authentic.')
else:
    print('The signature is not authentic.')
Beispiel #43
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):
Beispiel #44
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()))
Beispiel #45
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
Beispiel #46
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))
Beispiel #47
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))
Beispiel #48
0
import getpass
import socket, string, random, subprocess, os
from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA384
import utils

key = utils.get_private_key('update')

host, port = "127.0.0.1", 2356  #int(input('port :'))

mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

mySocket.connect((host, port))
while True:

    # Step 1 : Receive session_key
    while True:
        session_key = mySocket.recv(1024)
        if (session_key):
            print(session_key)
            break

    # Step 2 : encrypt session_key and send it
    signer = pkcs1_15.new(key)
    signature = SHA384.new()
    signature.update(session_key)
    mySocket.send(signer.sign(signature))

    # break
Beispiel #49
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