def DecryptECIES(curve_name, R, enc, t, pwd):
    '''Performs ECIES decryption.'''
    # Setup for Decryption
    E = PredefinedCurves(curve_name)

    # Get secret key s
    hashpwd = SHA512.new(pwd).hexdigest() + RIPEMD.new(pwd).hexdigest()
    s = int(str(int(hashpwd,16))[0: len(str(E.N))]) % E.N
    if s < 2:
        s = E.N/2

    # Begin Decryption
    Z = E.multPoint(s,R)
    RZ = str(R)+str(Z)
    H1 = SHA512.new(RZ).hexdigest()
    k1 = H1[0:32]
    k2 = H1[32:128]
    H2 = RIPEMD.new(enc+k2).digest()

    # If the hashes don't match, stop
    if base64.b64decode(t) != H2:
        return "Error: Hashes don't match! Your public key password is most likely incorrect.  It is also possible, though improbable, that you selected the wrong encrypted image."

    cipher = AES.new(k1)
    message = cipher.decrypt(base64.b64decode(enc))

    return message
Example #2
0
def sha2_hmac(key, message):
	"""
	This is the PRF used in the RFC; an implementation of HMAC using SHA512
	"""
	hashfunc = SHA512.new()
	opad = bytearray([0x5c]*blocksize)
	ipad = bytearray([0x36]*blocksize)

	key = bytearray(key)
	if len(key) > blocksize:
		hashfunc.update(bytearray(key))				#truncate key to blocksize if required
		key = bytearray(hashfunc.digest())
	if len(key) < blocksize:
		key = key + bytearray([0x00]*(blocksize - len(key)))	#pad right with 0s if needed

	o_key_pad = bytearray([a^b for a,b in zip(key, opad)])		#compute key XORs
	i_key_pad = bytearray([a^b for a,b in zip(key, ipad)])

	hashfunc.update(i_key_pad + bytearray(message))	#internal hash
	ihash = bytearray(hashfunc.digest())

	hashfunc = SHA512.new()				#reset hash function for outer hash
	hashfunc.update(o_key_pad + ihash)
	ohash = hashfunc.digest()			#inner hash result

	return bytearray(ohash)				#return in byte array format
Example #3
0
def _get_hash(obj):
    """
    Returns a SHA512 object for the given object. Works in a similar fashion
    to a Merkle tree (see https://en.wikipedia.org/wiki/Merkle_tree) should
    the object be tree like in structure - but only returns the "root" hash.
    """
    obj_type = type(obj)
    if obj_type is dict:
        hash_list = []
        for k in sorted(obj):
            hash_list.append(_get_hash(k).hexdigest())
            hash_list.append(_get_hash(obj[k]).hexdigest())
        seed = ''.join(hash_list)
        return SHA512.new(seed)
    elif obj_type is list:
        hash_list = []
        for item in obj:
            hash_list.append(_get_hash(item).hexdigest())
        seed = ''.join(hash_list)
        return SHA512.new(seed)
    elif obj_type is NoneType:
        return SHA512.new('null')
    elif obj_type is bool:
        return SHA512.new(str(obj).lower())
    else:
        return SHA512.new(str(obj))
Example #4
0
def otp():
	if not request.json:
		abort(400)

	i9 = request.json['iv1']
	i10 = request.json['iv2']
	k9 =  request.json['k9']
	k10 = merchant.decrypt(request.json['k10'])
	block1 = request.json['block1']
	block2 = request.json['block2']

	aes10 = AES.new(k10, AES.MODE_CFB, iv2)

	decrypt_block2 = aes10.decrypt(block2)
	authdata = decrypt_block2[:-128]
	hash_authdata = decrypt_block1[-128:]

	if SHA512.new(authdata).hexdigest() != hash_authdata:
		return 'hash of auth doesnt match'


	authdata = 'the customer is trying to send his otp, take it'
	k11 = Random.get_random_bytes(16)
	i11 = Random.get_random_bytes(16)
	aes = AES.new(k11, AES.MODE_CFB, i11)

	encrypted_authdata = aes.encrypt(authdata)
	signed_auth_data = merchant.sign(encrypted_authdata)
	encrypted_k11 = paymentgateway_publickey.encrypt(k11)

	data = {'k11': k11, 'i7': i11, 'authdata': encrypted_authdata, 'hash_authdata': signed_auth_data,
	'eotp': block1, 'k9': k9, 'i9': i9}

	response = requests.post('http://loclahost:8002/otp', data=data)

	data = response.json()
	encrypt_auth_data = data['authdata']
	signed_auth_data = data['signature']
	auth_data_iv = data['iv']
	kx = merchant.decrypt(data['kx'])

	aes = AES.new(kx, AES.MODE_CFB, auth_data_iv)
	auth_data = aes.decrypt(encrypt_auth_data)

	if paymentgateway_publickey.verify(SHA512.new(auth_data).hexdigest(), signed_auth_data) == False:
		return {'status': "couldnt verify paymentgateway response"}

	if auth_data != 'everything is good':
		return {'status': 'something went wrong while starting transaction'}

	auth_data = 'everything is good'
	iv = Random.get_random_bytes(16)
	aes = AES.new(k10, AES.MODE_CFB, iv)
	encrypted_authdata = aes.encrypt(auth_data)
	signature = merchant.sign(SHA512.new(signature).hexdigest())

	return {'iv': iv, 'authdata': encrypted_authdata, 'signature': signature}
Example #5
0
def remunge(params, raw_uid):
    """Creates a new PGPv3 key and PGPv4 signature.
    """
    n, e, d, p, q = params = [long(param) for param in params]

    pubkey = v3pubkey(n, e)
    restamped_pub = dumpbuffer(str(pubkey))[0]

    raw_uid = (raw_uid.encode('utf-8')
               if isinstance(raw_uid, unicode)
               else raw_uid)

    uid = (bytearray([0xb4]) +
           bytearray(four_octet(len(raw_uid))) +
           bytearray(raw_uid))

    sigtohash = bytearray(
        [0x04,   # version
         0x13,   # type
         0x01,   # pub_algo
         0x0a,   # hash_algo == SHA512
         0x00,   # first octet of length
         len(_HASHED_SUBPACKETS)]) + _HASHED_SUBPACKETS

    sigtrailer = bytearray([0x04, 0xff, 0x00, 0x00, 0x00,
                            len(sigtohash)])

    # (n, e, d, p, q)
    #params = (sk.modulus, long(sk.exponent), sk.exponent_d,
    #          sk.prime_p, sk.prime_q)
    rsa_key = RSA.construct(params)

    signer = PKCS1_v1_5.new(rsa_key)
    message = restamped_pub.raw_data + uid + sigtohash + sigtrailer
    h = SHA512.new(bytes(message))
    signature = signer.sign(h)

    digest = h.digest()

    new_sig = (sigtohash
               + chr(0)
               + chr(10)
               + chr(9)  # Length of issuer subpacket; always 8 + 1
               + '\x10'  # Issuer subpacket marker
               + long_to_bytes(long(restamped_pub.key_id, base=16))
               + digest[:2]
               + to_mpi(bytes_to_long(signature)))

    new_sig = '\x89' + pack('>H', len(new_sig)) + new_sig
    complete = bytes(bytearray().join([restamped_pub.raw_data,
                                       b"\xb4" + chr(len(raw_uid)),
                                       raw_uid, new_sig]))

    with open(urlsafe_b64encode(SHA512.new(complete).digest()), 'w') as f:
        f.write(complete)

    return complete
Example #6
0
def password():
	if not request.json:
		abort(400)

	k5 = request.json['k5']
	k6 = merchant.decrypt(request.json['k6'])
	i5 = request.json['iv1']
	i6 = request.json['i5']
	block1 = request.json['block1']
	block2 = request.json['block2']

	aes6 = AES.new(k6, AES.MODE_CFB, i6)

	decrypt_block2 = aes6.decrypt(block2)
	authdata = decrypt_block2[:-128]
	hash_authdata = decrypt_block1[-128:]

	if SHA512.new(authdata).hexdigest() != hash_authdata:
		return 'hash of auth doesnt match'

	authdata = 'the customer is trying to send his pass, take it'
	k7 = Random.get_random_bytes(16)
	i7 = Random.get_random_bytes(16)
	aes = AES.new(k7, AES.MODE_CFB, i7)

	encrypted_authdata = aes.encrypt(authdata)
	signed_auth_data = merchant.sign(SHA512.new(encrypted_authdata).hexdigest())
	encrypted_k7 = paymentgateway_publickey.encrypt(k7)

	data = {'k7': encrypted_k7, 'i7': i7, 'authdata': encrypted_authdata, 'hash_authdata': hash_authdata,
	'epassword': block1, 'k5': k5, 'i5': i5}

	response = requests.post('http://loclahost:8002/password', data=data)

	data = response.json()
	encrypt_auth_data = data['authdata']
	signed_auth_data = data['signature']
	auth_data_iv = data['iv']
	k4 = merchant.decrypt(data['k4'])

	aes = AES.new(k4, AES.MODE_CFB, auth_data_iv)
	auth_data = aes.decrypt(encrypt_auth_data)

	if paymentgateway_publickey.verify(SHA512.new(auth_data).hexdigest(), signed_auth_data) == False:
		return {'status': "couldnt verify paymentgateway response"}

	if auth_data != 'everything is good':
		return {'status': 'something went wrong while starting transaction'}

	auth_data = 'everything is good'
	iv = Random.get_random_bytes(16)
	aes = AES.new(k6, AES.MODE_CFB, iv)
	encrypted_authdata = aes.encrypt(auth_data)
	signature = merchant.sign(SHA512.new(signature).hexdigest())

	return {'iv': iv, 'authdata': encrypted_authdata, 'signature': signature}
Example #7
0
 def random32(self):
     """ Generate a random 32-bit integer. """
     fmt = '<L'
     N = struct.calcsize(fmt)
     if len(self.bits) < N:
         self.bits += _hash.new(self.hash).digest()
         self.hash = _hash.new(self.hash).digest()
     val = struct.unpack('<L', self.bits[:N])[0]
     self.bits = self.bits[N:]
     self.bits_used += 32
     return val
Example #8
0
def make_hash(data):
    """ make hash
    @param data:
    @type data:
    """
    sha = SHA512.new(data)
    return sha.hexdigest()
Example #9
0
 def check_sign(self, data, signature, key):
     """验证签名"""
     verifier = PKCS1_v1_5.new(key)
     if verifier.verify(SHA512.new(data), signature):
         print "the signature is authentic"
     else:
         print "the signature is not authentic"
Example #10
0
def sha512(pw):
    """hash the password once; expands shorter passwords"""
    h  = SHA512.new()
    lb = pack("> I", len(pw))
    h.update(lb)
    h.update(pw)
    return h.digest()
Example #11
0
    def test_loopback(self):
        hashed_msg = SHA512.new(b("test"))
        signer = DSS.new(self.key_priv, 'fips-186-3')
        signature = signer.sign(hashed_msg)

        verifier = DSS.new(self.key_pub, 'fips-186-3')
        verifier.verify(hashed_msg, signature)
    def get_challenge(self):
        '''
        Generate a QR2Auth challenge.
        A QR2Auth challenge consists of 128 random bits generated by PyCrypto
        with StrongRandom.
        These random bits are hashed with SHA512. This hash value represents
        the challenge.

        :return: A tuple containing the QR2Auth challenge as well as the range
                 of the OTP in the response hash value.
        :rtype: tuple
        '''
        random_pool = StrongRandom()
        nonce = random_pool.getrandbits(128)
        nonce_hash = SHA512.new(str(nonce)).hexdigest()
        self.__start = int(random_pool.randint(0, 128))
        '''
        Start and end of the range must be between 0 and the length of the hash
        We use Sha512, so in this case start and end must be between
        0 and 128
        '''
        self.__end = self.__start + self.__otp_length
        if self.__end > len(nonce_hash):
            self.__end = self.__end - len(nonce_hash)
        self.__challenge = nonce_hash
        return self.__challenge, self.__start, self.__end
Example #13
0
	def load_table_index(self,key):
		#FIXME no overlap check currently 
		hash = SHA512.new(key);
		self.blockdevice.seek(0);
		self.blockdevice.seek(self._hash_to_location(hash.hexdigest()));
		hextowrite = ord(self.blockdevice.read(1));
		self.indexlocation = hextowrite * (512 * 1024) + 2;
Example #14
0
def TransactionInitialise(request):
    # if request.user.is_authenticated():
    id = request.POST.get('uid')
    fee = request.POST.get('fees')
    college_id = request.POST.get('college_id')
    signature = request.POST.get('hash')
    m = SHA512.new()
    m.update(str(id).encode('utf-8'))
    m.update(str(fee).encode('utf-8'))
    m.update(str(college_id).encode('utf-8'))
    # print(hush + str(type(hush))+'         '+ m.hexdigest() + str(type(m.hexdigest())))
    hash=m.hexdigest()
    #print(m.hexdigest())
    if clg_public_key.verify(hash,signature):
        print(college_id)
        college_id=key.decrypt(college_id)
        acct = account_inst_map.objects.filter(institute_id=college_id)[0].account_no
        # acct = account.objects.get(pk=acc_no)
        # user=uuid.uuid()
        id=key.decrypt(id)
        fee=key.decrypt(fee)
        print(id)
        temp = temporary(uuid=id, account_no=acct, fees=fee)
        # temp=temporary(uuid=a,accnt_num=b,fees=c,user=user)
        temp.save()
        context = {
            'id': id,
            'form': LoginForm()
        }
        return render_to_response('vasubank/payment_login.html', context, context_instance=RequestContext(request))

    context = {
        'message': 'DATA has been Tempered.',
    }
    return render_to_response('vasubank/invalid_trans.html', context, context_instance=RequestContext(request))
Example #15
0
    def test_loopback(self):
        hashed_msg = SHA512.new(b("test"))
        signer = DSS.new(self.key_priv, 'deterministic-rfc6979')
        signature = signer.sign(hashed_msg)

        verifier = DSS.new(self.key_pub, 'deterministic-rfc6979')
        verifier.verify(hashed_msg, signature)
Example #16
0
def convert(args: object) -> int:
    """ Convert from sha256 hashed key to using a master key and encrypting the
    master key with a password based key.

    """

    filename = args.filename
    password = get_pass("password", verify=False)

    # Read the accounts dictionary into accounts_dict.
    accounts_dict, encrypted_key, master_key = read_file(filename, password)

    # Try to convert from old sha256 format to the new format.
    print("Converting...", end="")
    tmp_accounts_dict = {}
    for account_hash, account_data in accounts_dict.items():
        account_dict = crypt_to_dict_sha256(account_data, password=password, skip_invalid=True)
        if account_dict:
            new_account_data = dict_to_crypt(account_dict, master_key)
        else:
            raise (Exception("Invalid password.  Can't convert."))
        account_name = account_dict.get("Account Name", "")
        new_account_hash = SHA512.new(account_name.encode()).hexdigest()
        tmp_accounts_dict[new_account_hash] = new_account_data
    write_file(filename, tmp_accounts_dict, encrypted_key)
    print("Done.")
    return 0
Example #17
0
def compare_password(password, hash):
    split = hash.split(':')
    salt = base64.b64decode(split[0])
    new_hash = SHA512.new()
    new_hash.update(salt)
    new_hash.update(password.encode('utf8'))
    return is_equal(new_hash.digest(), base64.b64decode(split[1]))
Example #18
0
    def get_hash(
            cls,
            version: str,
            frequency: int,
            timestamp: int,
            seed_value: str,
            prev_output: str,
            status_code: str,
    ) -> SHA512Hash:
        """
        Given required properties from a NistBeaconValue,
        compute the SHA512Hash object.

        :param version: NistBeaconValue.version
        :param frequency: NistBeaconValue.frequency
        :param timestamp: NistBeaconValue.timestamp
        :param seed_value: NistBeaconValue.seed_value
        :param prev_output: NistBeaconValue.previous_output_value
        :param status_code: NistBeaconValue.status_code

        :return: SHA512 Hash for NistBeaconValue signature verification
        """
        return SHA512.new(
            version.encode() +
            struct.pack(
                '>1I1Q64s64s1I',
                frequency,
                timestamp,
                binascii.a2b_hex(seed_value),
                binascii.a2b_hex(prev_output),
                int(status_code),
            )
        )
Example #19
0
def construct_hash(value, timestamp, expires, name, meta):
    """
    The hash is a SHA512 hash of the concatenated SHA512 hashes of the
    msgpack encoded 'value', 'timetamp, 'expires', 'name' and 'meta'
    fields (in that order).

    It ensures that the 'value', 'timestamp', 'expires', 'name' and 'meta'
    fields have not been tampered with.
    """
    hashes = []
    for item in (value, timestamp, expires, name, meta):
        packed = msgpack.packb(item)
        hashed = SHA512.new(packed).digest()
        hashes.append(hashed)
    compound_hashes = ''.join(hashes)
    return SHA512.new(compound_hashes)
    def sendfile(self, dst_link, filepath):
        def _callback(err):
            if self._ret_sendfile(filekey, err) and err != None:
                with Auth.change_current_iden(self._idendesc, self._auth):
                    self.call(dst_link + "imc/", "abort_sendfile", 65536, filekey, err)

        filekey = SHA512.new(uuid.uuid1().bytes + ssl.RAND_bytes(64)).hexdigest()
        filesize = os.stat(filepath).st_size

        fileresult = FileResult(filekey)

        self._info_filekeymap[filekey] = {
            "filesize": filesize,
            "filepath": filepath,
            "fileresult": fileresult,
            "timer": self._ioloop.add_timeout(
                datetime.timedelta(days=1), lambda: self._ret_sendfile(filekey, "Etimeout")
            ),
            "callback": tornado.stack_context.wrap(_callback),
        }

        with Auth.change_current_iden(self._idendesc, self._auth):
            stat, ret = self.call(dst_link + "imc/", "pend_recvfile", 65536, self._link, filekey, filesize)

        if stat == False:
            self._ret_sendfile(filekey, "Enoexist")

        return fileresult
 def addUser(self, user):
     keygen = MD5.new()
     passgen = SHA512.new()
     keygen.update(user.getPassword().encode("UTF-8"))
     passgen.update(user.getPassword().encode("UTF-8"))
     key = keygen.hexdigest()
     pWord = passgen.hexdigest()
     uName = self.CIPHER.encrypt(user.getUsername(), key)
     query = """
             SELECT {0}, {1}, {2}, {3}, {4}
             FROM {5}
             WHERE
                 Username = '******' AND
                 Password = '******';
     """.format(Con.DB_USERS_ID, Con.DB_USERS_FIRSTNAME, Con.DB_USERS_LASTNAME, Con.DB_USERS_USERNAME, Con.DB_USERS_PASSWORD, Con.DB_USERS, uName, pWord)
     for row in self.CURSOR.execute(query):
         raise DatabaseError(Con.ERROR_DATABASE_USER_ALREADY_REGISTRATED)
         return
     
     fName = self.CIPHER.encrypt(user.getFirstName(), key)
     lName = self.CIPHER.encrypt(user.getLastName(), key)
     query = """
             INSERT INTO {0}
             ({1}, {2}, {3}, {4})
             VALUES
             ("{5}", "{6}", "{7}", "{8}");
             """.format(Con.DB_USERS, Con.DB_USERS_FIRSTNAME, Con.DB_USERS_LASTNAME, Con.DB_USERS_USERNAME, Con.DB_USERS_PASSWORD, fName, lName, uName, pWord)
     self.CONN.execute(query)
     self.CONN.commit()
     return self.login(user)
Example #22
0
def encrypt(v, encrypt_rsapubkey=None, sign_rsaprivkey=None):
	from Crypto.PublicKey import RSA
	from Crypto.Cipher import PKCS1_OAEP
	from Crypto.Cipher import AES
	from Crypto.Signature import PKCS1_PSS
	from Crypto.Hash import SHA512
	out = {}
	if encrypt_rsapubkey:
		encrypt_rsapubkey = RSA.importKey(encrypt_rsapubkey)
		rsa = PKCS1_OAEP.new(encrypt_rsapubkey)
		aeskey = randomString(32)
		iv = randomString(16)
		aes = AES.new(aeskey, AES.MODE_CBC, iv)
		data = varEncode(v).tostring()
		data += "\x00" * (-len(data) % 16)
		out["aesInfo"] = rsa.encrypt(aeskey + iv)
		out["data"] = aes.encrypt(data)
		out["encrypted"] = True
	else:
		out["data"] = varEncode(v).tostring()
		out["encrypted"] = False
	if sign_rsaprivkey:
		sign_rsaprivkey = RSA.importKey(sign_rsaprivkey)
		pss = PKCS1_PSS.new(sign_rsaprivkey)
		h = SHA512.new()
		h.update(out["data"])
		sign = pss.sign(h)
		out["signature"] = sign
	else:
		out["signature"] = None
	return out
 def crypto_hash_sha512(data):
     """
     调用 Crypto 库的 sha512 函数进行哈希操作
     :param data: 待哈希的数值, 比如 b"test_hash"
     :return: "5a32f0967623012cdd4c29257f808f3f209184e992c39dc6d931f89831e7b1eb9379f9e3a20da09eb06d0ca53bd9c0845dda91baed17a713c0cac8a24259c0b9"
     """
     return SHA512.new(data).hexdigest()
Example #24
0
    def send(self, obj, commit = False):

        msg = {'msg' : obj}
        if not commit:
            logger.info('[+] Sending: {0}'.format(msg['msg']))
        else:
            msg['COMMIT'] = obj

        # serialize input
        data = pickle.dumps(obj)

        # padding
        pad = AES.block_size - len(data) % AES.block_size

        # create an header [pck length (4 bytes), pad length (1 byte), random (3 bytes))]
        plaintext = pack('>IB', len(data) + pad + SHA512.digest_size, pad)
        plaintext += Random.new().read(AES.block_size - len(plaintext))
        # add payload plus padding
        plaintext += data
        plaintext += Random.new().read(pad)

        # encryption
        ciphertext = self.cipher_out.encrypt(plaintext)

        # integrity
        hsha = HMAC.new(self.key_hmac_out, digestmod=SHA512.new())
        hsha.update(plaintext)
        hsha.update(pack('>I', self.seq_out))
        self.seq_out = (self.seq_out + 1) & 0xFFFFFFFF
        ciphertext += hsha.digest()

        self.socket.sendall(ciphertext)
Example #25
0
def insert_encrypted_file(file, master_password):
    filename = file.path
    obj = SHA256.new()
    obj.update(file.author)
    obj.update(filename)
    obj.update(file.title)
    title = obj.hexdigest()

    obj_pass = SHA512.new()
    obj_pass.update(file.author)
    obj_pass.update(master_password)
    obj_pass.update(file.title)
    encfs_password = obj_pass.hexdigest()

    mount_f = media_dir + os.path.sep + mount_dir + os.path.sep + title
    store_f = media_dir + os.path.sep + store_dir + os.path.sep + title

    print store_f
    if os.path.exists(store_f):
        return

    if not os.path.exists(mount_f):
        os.makedirs(mount_f)
    if not os.path.exists(store_f):
        os.makedirs(store_f)

    subprocess.call(["expect", "encfs.exp", encfs_password, os.path.abspath(mount_f), os.path.abspath(store_f)],
                    stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    subprocess.call(["fusermount","-z","-u", os.path.abspath(mount_f)])
    subprocess.call(["/bin/sh", "-c", 'echo '+encfs_password+' | encfs -S -o allow_root --idle=1 '+os.path.abspath(store_f)+' '+os.path.abspath(mount_f)])
    shutil.copyfile("../media/" + filename, mount_f + os.path.sep + filename)
Example #26
0
def hash(*args):
	"""
	Update a new SHA512 hash with one argument at a time, and return that hash.
	"""
	h = SHA512.new()
	for arg in args:
		h.update(arg)
	return h.digest()
Example #27
0
	def create_table_index(self,key):
		#FIXME no overlap check currently 
		hash = SHA512.new(key);
		self.blockdevice.seek(0);
		self.blockdevice.seek(self._hash_to_location(hash.hexdigest()));
		hextowrite = random.randint(2,255);
		self.blockdevice.write('%c' % hextowrite);
		self.indexlocation = hextowrite * (512 * 1024) + 2;
Example #28
0
    def test_verify_true(self):
        decryption = Decryption(self.recipient_key, self.sender_key)
        message = 'ERROR=aA321\nTOKEN=e975ffc4f0605ddf3afc299eee6aeffb59efba24769548acf58e34a89ae4e228\n'
        hash = SHA512.new(message)
        signer = PKCS1_v1_5.new(self.sender_key_private)
        signature = signer.sign(hash)

        self.assertTrue(decryption.verify(signature, message))
	def __init__( self, key ):
		self.BS = 16
		self.pad = lambda s: s + (self.BS - len(s) % self.BS) * chr(self.BS - len(s) % self.BS) 
		self.unpad = lambda s : s[0:-ord(s[-1])]

		h = SHA512.new()
		h.update(str(key))
		self.key = h.hexdigest()[:16]
Example #30
0
 def prompt(self):
   username = raw_input("username: ")
   password = getpass('password: ')
   # generate key from username/password
   key = PBKDF2(password, SHA512.new(username).hexdigest(), dkLen=32, count=20000)
   # hmac
   hmac = HMAC.new(key, msg=username, digestmod=SHA512).hexdigest()
   return (key, hmac)
Example #31
0
def digSig(sigKey, string):

    # TODO: return the signature of the file

    # First, lets compute the SHA-512 hash of the data
    dataHash = SHA512.new(string).digest()

    # Lets generate the signature by encrypting our hash with the private key
    dataSig = sigKey.sign(dataHash, '')

    # Return the signature of the file
    return dataSig
Example #32
0
def verify_signature(key, text):
    msg = text[:32]

    h = SHA512.new(msg)

    signature = text[32:]

    try:
        PKCS1_v1_5.new(key).verify(h, signature)
        return True
    except (ValueError, TypeError):
        return False
Example #33
0
def get_retid():
    global gr_idmap
    global ret_idmap

    gr = greenlet.getcurrent()
    grid = id(gr)
    retid = SHA512.new(uuid.uuid1().bytes + ssl.RAND_bytes(64)).hexdigest()

    gr_idmap[grid].add(retid)
    ret_idmap[retid] = gr

    return retid
Example #34
0
 def __extend_key(self):
     key = ''
     h = SHA512.new()
     h.update(self.key)
     key += h.digest()
     h.update(self.key)
     key += h.digest()
     h.update(self.key)
     key += h.digest()
     h.update(self.key)
     key += h.digest()
     self.key = key
Example #35
0
def verify(data, sign):
    if not (os.path.isfile("public.key") and os.path.isfile("private.key")):
        print "[!] Key has not generated"
        generateKey()

    f = open("public.key", 'rb')
    key = RSA.importKey(f.read())
    signer = PKCS1_v1_5.new(key)
    hash = SHA512.new(data)
    f.close()

    return signer.verify(hash, sign)
Example #36
0
	def generate_master_key(self):

		# Get hex code
		self.digest = SHA512.new(Random.get_random_bytes(1024)).hexdigest();
		prefix = '04358394' if self.testnet == True else '0488ade4'
		hex = prefix + '00' + '00000000' + '00000000' + self.digest[:64] + '00' + self.digest[64:]

		# BASE58 encode + checksum
		master_key = b58encode_checksum(unhexlify(hex));

		# Generate child key
		return self.derive_child(master_key, '0', True)
 def _sign(self, body, algo="SHA-1"):
     signer = PKCS1_v1_5.new(self._private_key)
     if algo == "SHA-1":
         digest = SHA.new()
     else:
         digest = SHA512.new()
     digest.update(body)
     try:
         signature = signer.sign(digest)
     except Exception as err:
         raise Exception("Could not make sign. " + str(err))
     return signature
Example #38
0
    def build_authorization_header(self):
        """Build authorization headers."""
        if len(self.required_authorization_headers) > 0:
            self.authorization_parameters['headers'] = '{}'.format(' '.join([
                header.lower()
                for header in self.required_authorization_headers
            ]))
        self.build_signing_string()
        signing_bytestring = self.signing_string.encode(self.encoding)
        if self.signing_algorithm == 'RSA':
            signer = RSA.import_key(self.private_key_string)
            if self.hashing_algorithm == 'SHA256':
                hash_obj = SHA256.new(signing_bytestring)
            elif self.hashing_algorithm == 'SHA512':
                hash_obj = SHA512.new(signing_bytestring)
            else:
                raise Exception("Invalid key type")
            signature = pkcs1_15.new(signer).sign(hash_obj)
        else:
            private_key, public_key = PEMEncoder.decode_private_key(
                self.private_key_string)
            if self.hashing_algorithm == 'SHA256':
                hash_function = hashlib.sha256
            elif self.hashing_algorithm == 'SHA512':
                hash_function = hashlib.sha512
            else:
                raise Exception("Invalid key type")

            if self.signing_algorithm.lower() == 'p256':
                r, s = ecdsa.sign(signing_bytestring,
                                  private_key,
                                  curve=curve.P256,
                                  hashfunc=hash_function)
            else:
                raise Exception("Invalid key type")
            signature = DEREncoder.encode_signature(r, s)
        base64_signature = base64.b64encode(signature).decode(self.encoding)
        self.authorization_parameters['signature'] = '{}'.format(
            base64_signature)
        authorization_rows = []
        for key, value in self.authorization_parameters.items():
            if isinstance(value, str):
                authorization_rows.append('{}="{}"'.format(key, value))
            elif isinstance(value, int) or isinstance(value, float):
                authorization_rows.append('{}={}'.format(key, value))
            elif isinstance(value, bool):
                if value is True:
                    authorization_rows.append('{}=true')
                else:
                    authorization_rows.append('{}=false')
        authorization_header = 'Signature {}'.format(
            ','.join(authorization_rows))
        self.headers['Authorization'] = authorization_header
Example #39
0
def encrypt_textfile(file, key, pvt_key):

    # AES_encrypt part
    print("\nencrypt_textfile_function")

    # open file txt
    with open(file, 'r') as f:
        fp = f.read()
        print("text: ", fp)

    # open file AES key
    with open(key, 'rb') as f:
        k = f.read()

    # get AES key to encrypt text
    cipher = AES.new(k, AES.MODE_EAX)
    iv = cipher.nonce
    ciphertext, tag = cipher.encrypt_and_digest(fp.encode('UTF-8'))

    print("iv : ", iv)
    print("ciphertext : ", ciphertext)

    # len iv = 16 | tag = 16
    ciphertext = iv + tag + ciphertext
    print("ciphertext_encrypt : ", ciphertext)

    # save file text encrypt
    with open('AES_encrypt.txt', 'wb') as f:
        f.write(ciphertext)

    # Digital_Signal Part
    print("\nencrypt_signature_function")

    #get private Key from file
    private_key = RSA.import_key(open(pvt_key).read())

    # hash 512
    digest = SHA512.new()
    digest.update(ciphertext)

    with open('hash', 'wb') as f:
        f.write(digest.digest())

    # sign with private key
    signer = PKCS1_v1_5.new(private_key)
    sig = signer.sign(digest)

    print("Signature : ", sig)

    with open('digital_signature', 'wb') as f:
        f.write(sig)
        f.close
Example #40
0
    def do_creater(self, inp: str):
        '''    Create a Repo. \n    Usage: creater <repo name>'''
        parsed_prompt = IGCMD.prompt.split()
        if len(inp) > 0 and len(parsed_prompt) > 1:

            #admin
            admin = parsed_prompt[1]
            l_inp = len(admin)
            admin = str(admin[:l_inp - 1])

            #create client random
            cr_b = get_random_bytes(64)
            cr = SHA512.new(cr_b).hexdigest()
            try:
                res = requests.post('https://localhost:5683/create_repo',
                                    json={
                                        'repo_name': inp,
                                        'cr': cr,
                                        'admin': admin
                                    },
                                    verify=certpath + 'ca-public-key.pem')
            except ConnectionError:
                print(
                    ' Connection Error: Please check validity of the repo...')
            json_data: dict = json.loads(res.text)
            # print(json_data)
            repo_name = json_data.get('repo_name', None)
            status = json_data.get('status', None)

            if status == 'OK' and repo_name is not None:
                print(f'Repo Created : {repo_name}')

                #create a local repo
                c_path = os.path.join('src', 'dbctest', repo_name)
                os.mkdir(c_path)
                c_repo = Repo.init(c_path)

                with open(c_path + "/README.md", 'x') as readme:
                    readme.write('#' + repo_name)
                c_repo.index.add("README.md")
                c_repo.index.commit("Initial commit")

                self.do_pushr(repo_name)

            elif status != 'OK':
                print(f'{status}')
            else:
                print(f'{res.text}')
        elif len(inp) > 0 and len(parsed_prompt) == 1:
            print('*** Login to create a repo')
        else:
            print('*** Too Less Arguments')
Example #41
0
 def verifyresponse(self, message):
  idx = message.find('|')
  if idx == -1:
    return True
 
  signed_message = message[:idx]
  original_message = message[idx+1:]
  key = RSA.importKey(self.serverkey)
  signer = PKCS1_v1_5.new(key)
  digest = SHA512.new()
  digest.update(original_message)
  if signer.verify(digest, base64.b64decode(signed_message + "=" * ((4 - len(signed_message) % 4) % 4))):
    return True
    def _verify(self, data, sig):
        h = SHA512.new(data)
        hs = h.hexdigest()
        if hs in self._cache_hashmap:
            return True

        if self._verifier.verify(h, sig) == True:
            self._cache_hashmap.add(hs)

            return True

        else:
            return False
Example #43
0
def getFileSig(fileName, privKey, algorithm):
    # 1. Open the file
    # 2. Read the contents
    # 3. Compute the SHA-512 hash of the contents
    # 4. Sign the hash computed in using the digSig() function you implemented.
    # 5. Return the signed hash; this is your digital signature
    with open(fileName) as f:
        content = f.read()
    # Compute the SHA-512 hash of the contents
    content_hash = SHA512.new(content)
    # Sign the computed hash
    signed_hash = digSig(privKey, content_hash, algorithm)
    return signed_hash,
Example #44
0
def generateHashUsingSHA512(fileName):
    print("SHA_512")
    data = getData(fileName)
    data = bytes(data, "utf-8")
    start = timer()
    h = SHA512.new()
    h.update(data)
    #Because this looks better when viewed instead of h.digest()
    digest = h.hexdigest()
    end = timer()
    #print(digest)
    print("Time Taken to generate Hash is ", (end - start))
    print("Time Taken to Hash per byte is ", (end - start) / len(data))
Example #45
0
File: lib.py Project: ace0/xcheck
def protectEntry(name1, name2, birthdate, debug=False):
    """
    Protects a single record of demographic info by applying SHA512.
    """
    assert (type(birthdate) is date)
    name = "".join([x for x in [name1, name2] if x is not None])
    sha = SHA512.new(data=name)
    sha.update(birthdate.isoformat())

    if debug:
        print name + birthdate.isoformat()

    return b64enc(sha.digest())
Example #46
0
def verify_rsa_sha512_checksum(pubkey: str, data: bytes, checksum: str):
    """Verify your data and the callback checksum from SBER.

    Using asymmetric method: RSA SHA512 to encrypt the data
    https://securepayments.sberbank.ru/wiki/doku.php/integration:api:callback:start
    Returns:
        bool: verified or not

    """
    key = RSA.import_key(pubkey)
    signer = PKCS1_v1_5.new(key)
    digest = SHA512.new(data=data)
    return signer.verify(digest, unhexlify(checksum.lower()))
Example #47
0
    def sign(self, message):
        signer = PKCS1_v1_5.new(self.private_key)
        if (self.hash_alg == self.HASH_ALG_SHA_512):
            digest = SHA512.new()
        elif (self.hash_alg == self.HASH_ALG_SHA_384):
            digest = SHA384.new()
        elif (self.hash_alg == self.HASH_ALG_SHA_256):
            digest = SHA256.new()
        else:
            raise Exception("Unknown hash algorithm '%s'" % (self.hash_alg, ))

        digest.update(message)
        return b64encode(signer.sign(digest))
Example #48
0
def sintese(algoritmo, data):

    if algoritmo == "SHA-256":
        h = SHA256.new(data)

    elif algoritmo == "SHA-512":
        h = SHA512.new(data)

    else:
        print("ERROR: Unsupported algorithm")
        sys.exit(0)

    return h.hexdigest()
Example #49
0
def calculate_dh_secret(their_public, my_private):
    # Calculate the shared secret using Diffie-Hellman key exchange algorithm
    shared_secret = str((their_public**my_private) % prime)

    # Hash the value to SHA512 so that:
    # (a) There's no bias in the bits of the output
    #     (there may be bias if the shared secret is used raw)
    # (b) Converting to raw bytes is easier
    # (c) Adding additional information is easier

    #Hashed with SHA512
    shared_hash = SHA512.new(bytes(shared_secret, "ascii")).hexdigest()
    return shared_hash
Example #50
0
    def verify(self, message, signature):
        signer = PKCS1_v1_5.new(self.public_key)
        if (self.hash_alg == self.HASH_ALG_SHA_512):
            digest = SHA512.new()
        elif (self.hash_alg == self.HASH_ALG_SHA_384):
            digest = SHA384.new()
        elif (self.hash_alg == self.HASH_ALG_SHA_256):
            digest = SHA256.new()
        else:
            raise Exception("Unknown hash algorithm '%s'" % (self.hash_alg, ))

        digest.update(message)
        return signer.verify(digest, b64decode(signature))
Example #51
0
def verify(pk, msg, sig):
    '''
    check sign is made for msg using public key PK, string MSG, 
    and byte string SIGN.
    suppose publicExponent is fixed at 0x10001.
    return boolean
    '''
    msgHash = SHA512.new(msg.encode("UTF-8"))
    try:
        pkcs1_15.new(pk).verify(msgHash, bytes.fromhex(sig))
        return True
    except (ValueError, TypeError):
        return False
Example #52
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
Example #53
0
def verify_nonce(args):
    "Verify a lot of nonoces. This is to counter ccontext switch time"
    data, nonce_list, n_zeros = args
    valid = False
    valid_nonce = None
    for nonce in nonce_list:
        string = '{} {}'.format(data, nonce)
        hsh = SHA512.new(string.encode()).hexdigest()
        valid = all(i == '0' for i in hsh[:n_zeros])
        if valid:
            valid_nonce = nonce
            break
    return valid_nonce, valid
Example #54
0
def handlingSignupEvent():
    username = txtUsername.get()
    password = txtPassword.get().encode()

    # print(username)
    # print(password)
    func = np.random.randint(4)  # generate a random integer from 0 to 3
    # print(func)

    if func == 0:
        passEncrypted = MD5.new(password)
    elif func == 1:
        passEncrypted = SHA1.new(password)
    elif func == 2:
        passEncrypted = SHA256.new(password)
    elif func == 3:
        passEncrypted = SHA512.new(password)

    passEncrypted = passEncrypted.hexdigest().upper()

    # print(passEncrypted)

    if os.path.isfile("../data/database.csv"):
        # print("File existed")
        if existedUser(username):
            messagebox.showinfo("Thông báo", "Tên đăng nhập đã tồn tại!")
            return

        userInfo = {'Username': username, 'Password': passEncrypted}

        df = pd.DataFrame(userInfo,
                          columns=['Username', 'Password'],
                          index=['Username'])
        df.to_csv("../data/database.csv",
                  index=False,
                  header=None,
                  sep='\t',
                  mode='a')
        messagebox.showinfo("Thông báo", "Bạn đã tạo tài khoản thành công!")

    else:
        # print("File did not exist")
        userInfo = {'Username': username, 'Password': passEncrypted}

        df = pd.DataFrame(userInfo,
                          columns=['Username', 'Password'],
                          index=['Username'])

        df.to_csv("../data/database.csv", index=False, header=None, sep='\t')

        messagebox.showinfo("Thông báo", "Bạn đã tạo tài khoản thành công!")
Example #55
0
    def _encrypt(self, passwd, pubkey, selected_block=None, fast=True):

        # Read public key
        try:
            PUBkey = RSA.importKey(open(pubkey, "r").read())
        except FileNotFoundError:
            raise ValueError('No such file or directory : {}'.format(pubkey))
        except ValueError:
            raise KeyError('Wrong key format')
        except PermissionError:
            raise PermissionError('Read permission denied : {}'.format(pubkey))
        if PUBkey.has_private(): raise KeyError('Wrong key format')

        # Select a valid block as symetric key
        if selected_block == None: selected_block = self.selectBlock()
        else:
            if type(selected_block) != int:
                raise ValueError('The selected block must be an int')
            if selected_block > len(self.blocks) - 1 or selected_block < 0:
                raise ValueError(
                    'The selected block ({}) must satisfy :\n\t{}\n\t{}'.
                    format(selected_block,
                           'selected block <= {}'.format(len(self.blocks) - 1),
                           'selected block >= 0'))

        # Padding
        block_size = len(self.blocks[-1])
        self.blocks[-1] = self.blocks[-1] + os.urandom(self.chunkSize -
                                                       block_size)

        #Get the symetric encryptor
        hash_sha = SHA256.new(self.blocks[selected_block] +
                              bytes(passwd, encoding='utf-8')).digest()
        hash_sha_sha = SHA.new(hash_sha).digest()
        encryptor = AES.new(hash_sha, AES.MODE_ECB, "")

        # Store the info
        self.info['fast'] = fast
        self.info['padding'] = self.chunkSize - block_size
        self.info['challenge'] = hash_sha_sha
        self.info['auth'] = SHA512.new(
            bytes('{}{}{}'.format(hash_sha_sha.hex(), selected_block, passwd),
                  encoding='utf-8')).digest()

        # Encrypt the file
        for i, b in enumerate(self.blocks):
            self.blocks[i] = PUBkey.encrypt(
                b, 32)[0] if (i == selected_block) else encryptor.encrypt(b)

        self.status = "encrypted"
        return self
Example #56
0
def validate_sign(public_certificate, key, cipher_text):

    cipher_text = b64decode(cipher_text)
    if hasattr(key, 'encode'):
        key = key.encode()

    digest = SHA512.new()
    digest.update(key)

    pub_key = RSA.importKey(public_certificate)
    verifier = PKCS1_v1_5.new(pub_key)
    result = verifier.verify(digest, cipher_text)
    logger.debug("validate_sign %i " % (result, ))
    return result
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)
Example #58
0
def RealmKeyDerivation(master_key, realm="", shard=""):

    if len(realm) < 1:
        raise ValueError("The realm label is missing or invalid.")
    elif len(shard) != 64:
        raise ValueError("The shard length is not 64 octets.")
    elif len(master_key) != 64 != 64:
        raise ValueError("The master key length is not 64 octets.")

    hashed = SHA512.new(master_key + realm + shard).digest()
    realm_key = str().join(chr(operator.xor(ord(a), ord(b))) \
        for a,b in zip(hashed, shard))

    return realm_key
Example #59
0
def verifyFileSig(fileName, pubKey, signature):
    verifySign = None
    # TODO:
    # 1. Read the contents of the input file (fileName)
    with open(fileName, 'r') as myFile:
        readFile = myFile.read()
        # 2. Compute the SHA-512 hash of the contents
        hashedData = SHA512.new(readFile).hexdigest()
        # 3. Use the verifySig function you implemented in
        # order to verify the file signature
        verifySign = verifySig(hashedData, signature, pubKey)
    # 4. Return the result of the verification i.e.,
    # True if matches and False if it does not match
    return verifySign
Example #60
0
def getFileSig(fileName, privKey):

    # TODO:
    # 1. Open the file
    # 2. Read the contents
    with open(fileName, 'r') as myFile:
        readFile = myFile.read()
        # 3. Compute the SHA-512 hash of the contents
        hashedData = SHA512.new(readFile).hexdigest()
        # 4. Sign the hash computed in 4. using the digSig() function
        # you implemented.
        signedHash = digSig(privKey, hashedData)
    # 5. Return the signed hash; this is your digital signature
    return signedHash