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
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
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))
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
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}
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}
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
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), ) )
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)
def crypto_hash_sha512(data): """ 调用 Crypto 库的 sha512 函数进行哈希操作 :param data: 待哈希的数值, 比如 b"test_hash" :return: "5a32f0967623012cdd4c29257f808f3f209184e992c39dc6d931f89831e7b1eb9379f9e3a20da09eb06d0ca53bd9c0845dda91baed17a713c0cac8a24259c0b9" """ return SHA512.new(data).hexdigest()
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)
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;
def make_hash(data): """ make hash @param data: @type data: """ sha = SHA512.new(data) return sha.hexdigest()
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()
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 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]))
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)
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
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 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 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)
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
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"
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))
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 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()
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;
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)
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]
def decrypt(self, encrypted_text, key, nonce): tempkey = SHA512.new(key + nonce).digest() cipher = ARC4.new(tempkey) text = cipher.decrypt(encrypted_text) return text
def main(): # Make sure that all the arguments have been provided if len(sys.argv) != 5: print( "USAGE: " + sys.argv[0] + " <KEY FILE NAME> <SIGNATURE FILE NAME> <INPUT FILE NAME> <sign/verify>\n" ) print("Below can be used to test the extra credit portion:\n") print( "EXTRA CREDIT USAGE: " + sys.argv[0] + " <KEY FILE NAME> <AES KEY> <INPUT FILE NAME> <sign-aes/verify-aes>\n" ) exit(-1) # The key file keyFileName = sys.argv[1] # Signature file name sigFileName = sys.argv[2] # The input file name inputFileName = sys.argv[3] # The mode i.e., sign or verify mode = sys.argv[4] # TODO: Load the key using the loadKey() function provided. key = loadKey(keyFileName) # We are signing if mode == "sign": # TODO: 1. Get the file signature # 2. Save the signature to the file sig = getFileSig(inputFileName, key) saveSig(sigFileName, sig) print("Signature saved to file: {}".format(sigFileName)) # We are verifying the signature elif mode == "verify": # TODO Use the verifyFileSig() function to check if the # signature signature in the signature file matches the # signature of the input file verifyFileSig(inputFileName, key, sigFileName) ################################################################################ #########################SIGN EXTRA CREDIT PORTION############################## ################################################################################ elif mode == "sign-aes": k = set_key(sys.argv[2].replace(" ", "")) #get the file signature sig = getFileSig(inputFileName, key) #Save the signature to the file outFile = aesenc(inputFileName, sig, k) print("Encryption saved to: " + format(outFile)) ################################################################################ #########################VERIFY EXTRA CREDIT PORTION############################ ################################################################################ elif mode == "verify-aes": k = set_key(sys.argv[2].replace(" ", "")) (outFile, sig) = aesdec(inputFileName, k) with open(outFile, "r") as file: contents = file.read() dHash = SHA512.new(contents).hexdigest() # signature signature in the signature file matches the # signature of the input file verifySig(dHash, sig, key) print("Decryption saved to: " + format(outFile)) else: print("Error!!! Invalid mode:" + format(mode))
def generate_hash(data): data_hash = SHA512.new(data) return data_hash
from base64 import b64decode from Crypto.Cipher import AES from Crypto.Util.Padding import unpad from Crypto.Hash import SHA256, SHA512 key_digest = '31af112461ca634ea7468e685a6edec4b63a1b1a324a2d77e2172d0d14a84ac455c7448836ec9ab98a614e14487e010ed88ef80f081a7bf911b8e20e04e1c9d7' iv = b64decode('750dddjhwyJSJ2YhRFZAjw==') flag = b64decode('L1i39WIWpALQBHZiZWzXdU/mCzwD6pbVZowcJiGUz237mfOBEuYK3/dpJMHq+DP4') pswd = input('Insert password: '******'You did it: ', pt.decode('utf-8')) else: print("lol nope")
# Return the key return key # Load the public and private keys from files pubKey = loadKey("pubKey.pem") privKey = loadKey("privKey.pem") # The data to be digitally signed data = "hello world" ############## GENERATING SIGNATURE ##################### # First, lets compute the SHA-512 hash of the data dataHash = SHA512.new(data).hexdigest() # Lets generate the signature by encrypting our hash with the private key dataSig = privKey.sign(dataHash, '') ############# VERIFYING THE SIGNATURE #################### # First, lets compute the SHA-512 hash of the data dataHash = SHA512.new(data).hexdigest() # Now, verify the signature against the hash. I.e., the verify function # will decrypt the digital signature using the public key and then compare # the decrypted result to the dataHash if pubKey.verify(dataHash, dataSig) == True:
resp = hand.client(["akey"]) if resp[0] != "OK": print("key resp", resp) sys.exit(1) if conf.verbose: print("got response to akey: ", resp[:-1]) if conf.pgdebug > 2: print("Got hash:", "'" + resp[1] + "'") if conf.pgdebug > 3: print("Server pub key response:\n" + "'" + str(resp[2]) + "'\n") hhh = SHA512.new() hhh.update(resp[2]) ddd = hhh.hexdigest() if conf.pgdebug > 1: print("Hash1:\n" + resp[2], "\nHash2:\n" + ddd + "\n") # Remember key if ddd != resp[1]: print("Tainted key") else: hand.pkey = resp[2] if conf.quiet == False: print("Key OK") if conf.showkey:
from Crypto.Hash import SHA512 from Crypto.PublicKey import RSA from Crypto import Random s = socket.socket() host = socket.gethostname() port = 1274 s.connect((host, port)) '''receive public key from server''' import cPickle hashofpuk = s.recv(1024) s.send('ok') Picklekey = s.recv(1024) if hashofpuk != SHA512.new(Picklekey).hexdigest(): s.send('1') s.close() print 'Public key not valid' exit(0) print 'public_key valid' public_key = cPickle.loads(Picklekey) s.send('2') '''convert file into hash file at client side''' fname = 'r.pdf' import hashlib BLOCKSIZE = 65536
def _validate_authorization_header(self, request_target, actual_headers, authorization_header): """Validate the signature. """ # Extract (created) r1 = re.compile(r'created=([0-9]+)') m1 = r1.search(authorization_header) self._tc.assertIsNotNone(m1) created = m1.group(1) # Extract list of signed headers r1 = re.compile(r'headers="([^"]+)"') m1 = r1.search(authorization_header) self._tc.assertIsNotNone(m1) headers = m1.group(1).split(' ') signed_headers_list = [] for h in headers: if h == '(created)': signed_headers_list.append((h, created)) elif h == '(request-target)': url = request_target[1] target_path = urlparse(url).path signed_headers_list.append( (h, "{0} {1}".format(request_target[0].lower(), target_path))) else: value = next( (v for k, v in actual_headers.items() if k.lower() == h), None) self._tc.assertIsNotNone(value) signed_headers_list.append((h, value)) header_items = [ "{0}: {1}".format(key.lower(), value) for key, value in signed_headers_list ] string_to_sign = "\n".join(header_items) digest = None if self.signing_cfg.signing_scheme in { signing.SCHEME_RSA_SHA512, signing.SCHEME_HS2019 }: digest = SHA512.new() elif self.signing_cfg.signing_scheme == signing.SCHEME_RSA_SHA256: digest = SHA256.new() else: self._tc.fail("Unsupported signature scheme: {0}".format( self.signing_cfg.signing_scheme)) digest.update(string_to_sign.encode()) b64_body_digest = base64.b64encode(digest.digest()).decode() # Extract the signature r2 = re.compile(r'signature="([^"]+)"') m2 = r2.search(authorization_header) self._tc.assertIsNotNone(m2) b64_signature = m2.group(1) signature = base64.b64decode(b64_signature) # Build the message signing_alg = self.signing_cfg.signing_algorithm if signing_alg is None: # Determine default if isinstance(self.pubkey, RSA.RsaKey): signing_alg = signing.ALGORITHM_RSASSA_PSS elif isinstance(self.pubkey, ECC.EccKey): signing_alg = signing.ALGORITHM_ECDSA_MODE_FIPS_186_3 else: self._tc.fail("Unsupported key: {0}".format(type(self.pubkey))) if signing_alg == signing.ALGORITHM_RSASSA_PKCS1v15: pkcs1_15.new(self.pubkey).verify(digest, signature) elif signing_alg == signing.ALGORITHM_RSASSA_PSS: pss.new(self.pubkey).verify(digest, signature) elif signing_alg == signing.ALGORITHM_ECDSA_MODE_FIPS_186_3: verifier = DSS.new(self.pubkey, signing.ALGORITHM_ECDSA_MODE_FIPS_186_3) verifier.verify(digest, signature) elif signing_alg == signing.ALGORITHM_ECDSA_MODE_DETERMINISTIC_RFC6979: verifier = DSS.new( self.pubkey, signing.ALGORITHM_ECDSA_MODE_DETERMINISTIC_RFC6979) verifier.verify(digest, signature) else: self._tc.fail( "Unsupported signing algorithm: {0}".format(signing_alg))
from Crypto.Hash import SHA512 from Crypto.Hash import SHA384 from Crypto.Hash import SHA256 from Crypto.Hash import SHA224 from Crypto.Hash import RIPEMD from Crypto.Hash import MD5 from Crypto.Hash import MD4 from Crypto.Hash import MD2 import whirlpool import hashlib a = raw_input("Digite uma string: ") b = SHA512.new(a).hexdigest() c = SHA384.new(a).hexdigest() d = SHA256.new(a).hexdigest() e = SHA224.new(a).hexdigest() f = RIPEMD.new(a).hexdigest() g = MD5.new(a).hexdigest() h = MD4.new(a).hexdigest() i = MD2.new(a).hexdigest() j = whirlpool.new(a).hexdigest() l = hashlib.sha1(a).hexdigest() print "SHA512 = ", b print "SHA384 = ", c print "SHA256 = ", d print "SHA224 = ", e print "RIPEMD160 = ", f print "MD5 = ", g print "MD4 = ", h print "MD2 = ", i print "Whirlpool = ", j
def get_akey_func(self, strx): if pgdebug > 1: print("get_akey_func() called") ddd = os.path.abspath("keys") try: self.keyfroot = pyservsup.pickkey(ddd) except: print("No keys generated yet.", sys.exc_info()[1]) support.put_exception("no keys key") rrr = ["ERR", "No keys yet. Run keygen"] self.resp.datahandler.putencode(rrr, self.resp.ekey) return if pgdebug > 2: print("self.keyfroot", self.keyfroot) try: # Do public import fp = open(ddd + "/" + self.keyfroot + ".pub", "rb") self.keyx = fp.read() fp.close() try: self.pubkey = RSA.importKey(self.keyx) except: print("Cannot read key:", self.keyx[:12], sys.exc_info()[1]) support.put_exception("import key") rrr = ["ERR", "Cannot read public key"] self.resp.datahandler.putencode(rrr, self.resp.ekey) return if pgdebug > 5: print("Key read: \n'" + self.keyx.decode("cp437") + "'\n") # Do private import; we are handleing it here, so key signals errors fp2 = open(ddd + "/" + self.keyfroot + ".pem", "rb") self.keyx2 = fp2.read() fp2.close() try: self.privkey = RSA.importKey(self.keyx2) self.priv_cipher = PKCS1_v1_5.new(self.privkey) except: print("Cannot create private key:", self.keyx2[:12], sys.exc_info()[1]) support.put_exception("import private key") rrr = ["ERR", "Cannot create private key"] self.resp.datahandler.putencode(rrr, self.resp.ekey) return if pgdebug > 5: print("Key read: \n'" + self.keyx.decode("cp437") + "'\n") hh = SHA512.new() hh.update(self.keyx) if pgdebug > 3: print("Key digest: \n'" + hh.hexdigest() + "'\n") # Deliver the answer in two parts: rrr = ["OK", "%s" % hh.hexdigest(), self.keyx] self.resp.datahandler.putencode(rrr, self.resp.ekey) except: print("Cannot read key:", self.keyfroot, sys.exc_info()[1]) support.put_exception("read key") rrr = ["ERR", "cannot open keyfile."] self.resp.datahandler.putencode(rrr, self.resp.ekey)
def _sha512_new(*args): from Crypto.Hash import SHA512 _new_funcs['SHA512'] = _new_funcs['sha512'] = SHA512.new return SHA512.new(*args)
def writeHash(password, salt): hashes = {} hashes[password] = "Plain-text" hashes[urllib.quote(password, safe='')] = "URL Encoded" hashes[password.encode("hex")] = "Hex" hashes[base64.b16encode(password)] = "Base16" hashes[base64.b32encode(password)] = "Base32" hashes[base64.b64encode(password)] = "Base64" hashes[base64.b64encode(salt + ":" + password)] = "Basic Auth" hashes[base64.b64encode(MD5.new(password).digest())] = "md5" hashes[base64.b64encode(MD5.new(password + salt).digest())] = "md5+salt" hashes[base64.b64encode(MD5.new(salt + password).digest())] = "salt+md5" hashes[base64.b64encode(HMAC.new( password, salt, SHA).digest())] = "hmac-sha1; key=password" hashes[base64.b64encode(HMAC.new(salt, password, SHA).digest())] = "hmac-sha1; key=salt" hashes[base64.b64encode(HMAC.new( password, salt, SHA256).digest())] = "hmac-sha256; key=password" hashes[base64.b64encode(HMAC.new( salt, password, SHA256).digest())] = "hmac-sha256; key=salt" hashes[base64.b64encode(HMAC.new( password, salt, SHA512).digest())] = "hmac-sha512; key=password" hashes[base64.b64encode(HMAC.new( salt, password, SHA512).digest())] = "hmac-sha512; key=salt" hashes[base64.b64encode(SHA.new(password).digest())] = "sha1" hashes[base64.b64encode(SHA224.new(password).digest())] = "sha224" hashes[base64.b64encode(SHA256.new(password).digest())] = "sha256" hashes[base64.b64encode(SHA512.new(password).digest())] = "sha512" hashes[base64.b64encode(SHA.new(password + salt).digest())] = "sha1+salt" hashes[base64.b64encode(SHA224.new(password + salt).digest())] = "sha224+salt" hashes[base64.b64encode(SHA256.new(password + salt).digest())] = "sha256+salt" hashes[base64.b64encode(SHA512.new(password + salt).digest())] = "sha512+salt" hashes[base64.b64encode(SHA.new(salt + password).digest())] = "salt+sha1" hashes[base64.b64encode(SHA224.new(salt + password).digest())] = "salt+sha224" hashes[base64.b64encode(SHA256.new(salt + password).digest())] = "salt+sha256" hashes[base64.b64encode(SHA512.new(salt + password).digest())] = "salt+sha512" hashes[base64.b64encode(MD4.new(password).digest())] = "md4" hashes[MD5.new(password).hexdigest()] = "md5" hashes[MD5.new(password + salt).hexdigest()] = "md5+salt" hashes[MD5.new(salt + password).hexdigest()] = "salt+md5" hashes[HMAC.new(password, salt, SHA).hexdigest()] = "hmac-sha1; key=password" hashes[HMAC.new(salt, password, SHA).hexdigest()] = "hmac-sha1; key=salt" hashes[HMAC.new(password, salt, SHA256).hexdigest()] = "hmac-sha256; key=password" hashes[HMAC.new(salt, password, SHA256).hexdigest()] = "hmac-sha256; key=salt" hashes[HMAC.new(password, salt, SHA512).hexdigest()] = "hmac-sha512; key=password" hashes[HMAC.new(salt, password, SHA512).hexdigest()] = "hmac-sha512; key=salt" hashes[SHA.new(password).hexdigest()] = "sha1" hashes[SHA224.new(password).hexdigest()] = "sha224" hashes[SHA256.new(password).hexdigest()] = "sha256" hashes[SHA512.new(password).hexdigest()] = "sha512" hashes[SHA.new(password + salt).hexdigest()] = "sha1+salt" hashes[SHA224.new(password + salt).hexdigest()] = "sha224+salt" hashes[SHA256.new(password + salt).hexdigest()] = "sha256+salt" hashes[SHA512.new(password + salt).hexdigest()] = "sha512+salt" hashes[SHA.new(salt + password).hexdigest()] = "salt+sha1" hashes[SHA224.new(salt + password).hexdigest()] = "salt+sha224" hashes[SHA256.new(salt + password).hexdigest()] = "salt+sha256" hashes[SHA512.new(salt + password).hexdigest()] = "salt+sha512" hashes[MD4.new(password).hexdigest()] = "md4" hashes[passlib.hash.mysql323.hash(password)] = "mysql323" hashes[passlib.hash.mysql41.hash(password)] = "mysql41" hashes[passlib.hash.mssql2005.hash(password).split("x")[1]] = "mssql2005" hashes[passlib.hash.mssql2000.hash(password).split("x")[1]] = "mssql2000" hashes[passlib.hash.md5_crypt.hash(password)] = "md5crypt (unix)" hashes[passlib.hash.nthash.hash(password)] = "nt" return hashes
input_files = ['smallfile.txt', 'bigfile.txt'] capture_time = [] for input_file in input_files: start = timer() with open(input_file, 'rb') as fin: data = fin.read() hash = SHA256.new() hash.update(data) print('SHA256') print(hash.hexdigest()) end = timer() capture_time.append(end - start) start = timer() with open(input_file, 'rb') as fin: data = fin.read() hash = SHA512.new() hash.update(data) print('SHA512') print(hash.hexdigest()) end = timer() capture_time.append(end - start) start = timer() with open(input_file, 'rb') as fin: data = fin.read() hash = SHA3_256.new() hash.update(data) print('SHA3_256') print(hash.hexdigest()) end = timer() capture_time.append(end - start)
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 = securesystemslib.hash.digest() digest_object = securesystemslib.hash.digest('sha384') digest_object = securesystemslib.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 = securesystemslib.hash.digest_fileobject(file_object) digest_object = securesystemslib.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> securesystemslib.exceptions.UnsupportedAlgorithmError securesystemslib.exceptions.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 securesystemslib.exceptions.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 securesystemslib.exceptions.UnsupportedAlgorithmError( algorithm) # The requested hash library is not supported. else: raise securesystemslib.exceptions.UnsupportedLibraryError( 'Unsupported library requested. ' 'Supported hash libraries: ' + str(_SUPPORTED_LIB_LIST))
def sha512_random_line(line): hasher = SHA512.new(line) return hasher.digest()
}, "sha224": { "hashlib_hash": hashlib.new("sha224"), "crypto_hash": SHA224.SHA224Hash() }, "sha256": { "hashlib_hash": hashlib.new("sha256"), "crypto_hash": SHA256.SHA256Hash() }, "sha384": { "hashlib_hash": hashlib.new("sha384"), "crypto_hash": SHA384.SHA384Hash() }, "sha512": { "hashlib_hash": hashlib.new("sha512"), "crypto_hash": SHA512.SHA512Hash() }, "sha1": { "hashlib_hash": hashlib.new("sha1"), "crypto_hash": SHA.SHA1Hash() }, "ripemd160": { "hashlib_hash": hashlib.new("ripemd160"), "crypto_hash": RIPEMD.RIPEMD160Hash() } } # takes hasher def hashFile(filename, hasher): return hashit.hashIter(hashit.blockIter(open(filename, "rb")), hasher)
Created on Wed Apr 8 17:17:32 2015 @author: zazkia """ import itertools from Crypto.Hash import MD2,MD5,SHA,SHA256,SHA512 charset = 'abcdefghijklmnopqrstuvwxyz0123456789' for i in itertools.product(charset, repeat=6): MD2hash = MD2.new(''.join(i)).hexdigest() MD5hash = MD5.new(''.join(i)).hexdigest() SHA1hash = SHA.new(''.join(i)).hexdigest() SHA256hash = SHA256.new(''.join(i)).hexdigest() SHA512hash = SHA512.new(''.join(i)).hexdigest() if MD2hash.startswith('757c47'): print 'MD2: '+''.join(i)+' '+MD2hash with open("egg_24_MD2.txt", "a") as myfile: myfile.write('MD2: '+''.join(i)+' '+MD2hash) if MD5hash[6:].startswith('9895d6'): print 'MD5: '+''.join(i)+' '+MD5hash with open("egg_24_MD5.txt", "a") as myfile2: myfile2.write('MD5: '+''.join(i)+' '+MD5hash) if SHA1hash[12:].startswith('845b2b'): print 'SHA1: '+''.join(i)+' '+SHA1hash with open("egg_24_SHA1.txt", "a") as myfile3: myfile3.write('SHA1: '+''.join(i)+' '+SHA1hash)
def toggleBit(number, bit): mask = (1 << bit) return (number ^ mask) def testBit(number, bit): mask = 1 << bit return (number & mask) i = 4222864395 k = hex(i).replace('0x', '').replace('L', '') entrada = '0' * (128 - len(k)) + k m = SHA512.new(entrada) finalHash = m.hexdigest() nCambios = [0] * (512) cPosicion = [0] * (512) for x in range(512): newEntrada = toggleBit(int(entrada, 16), x) mx = SHA512.new(hex(newEntrada).replace('0x', '').replace('L', '')) hashx = mx.hexdigest() cambios = 0 for index in range(512): if (testBit(int(finalHash, 16), index)
from Crypto.Hash import SHA512 string = input("enter string") print(SHA512.new(string.encode()).hexdigest())
def main(): cliParser = ArgumentParser(description="RSA encryption Tool") subparsers = cliParser.add_subparsers(help='sub-command help', dest='command') # Add subparser parserEncrypt = subparsers.add_parser('encrypt', help='RSA encrypt') parserDecrypt = subparsers.add_parser('decrypt', help='RSA Decrypt') parserSign = subparsers.add_parser('sign', help='RSA Sign') parserVerify = subparsers.add_parser('verify', help='RSA Verify') # add arg to Encrypt parserEncrypt.add_argument('-pub', '--public', help='Public Key', required=True) parserEncrypt.add_argument('-i', '--input', help="Input Clear text", required=True) # add arg to Decrypt parserDecrypt.add_argument('-pri', '--private', help='Private Key', required=True) parserDecrypt.add_argument('-i', '--input', help="Input Cipher text", required=True) # add arg to Sign parserSign.add_argument('-pri', '--private', help='Private Key', required=True) parserSign.add_argument('-b', '--base64', help="Base64 Decode", action='store_true') parserSign.add_argument('-u', '--url', help="URL Decode", action='store_true') parserSign.add_argument( '-hh', '--hash', help="hash function {md5, sha-1, sha-224, sha-256, sha-384, sha-512}", required=True) parserSign.add_argument('-i', '--input', help="Input Clear text", required=True) # add arg to Verify parserVerify.add_argument('-pub', '--public', help='Public Key', required=True) parserVerify.add_argument('-b', '--base64', help="Base64 Decode", action='store_true') parserVerify.add_argument('-u', '--url', help="URL Decode", action='store_true') parserVerify.add_argument('-i', '--input', help="Input Signature text", required=True) cliParser.add_argument('-v', '--version', action='version', version='RSA Tool {} - M4rK0v'.format(VERSION), help='Version of this tool') args = cliParser.parse_args() # Load input try: inputFile = open(args.input, 'rb') except (FileExistsError, FileNotFoundError) as e: print(e) return -1 input = inputFile.read() input = input.strip() # check to do encrypt if args.command == 'encrypt': try: key = loadKey(args.public) except (FileNotFoundError, FileExistsError) as e: print("[!] Key file not found.") return 0 except (ValueError, TypeError, IndexError) as e: print("[!] Key has improper format.") return 0 pubKey = PKCS1_v1_5.new(key) cipher = key.encrypt(input, 32)[0] print("[+] Cipher Text:") print(base64.b64encode(cipher)) # check to elif args.command == 'decrypt': try: key = loadKey(args.private) except (FileNotFoundError, FileExistsError) as e: print("[!] Key file not found.") return 0 except (ValueError, TypeError, IndexError) as e: print("[!] Key has improper format.") return 0 cipher = base64.b64decode(input) clearText = key.decrypt(cipher) print("[+] Clear Text:") print(clearText) elif args.command == 'sign': try: key = loadKey(args.private) except (FileNotFoundError, FileExistsError) as e: print("[!] Key file not found.") return 0 except (ValueError, TypeError, IndexError) as e: print("[!] Key has improper format.") return 0 keySign = PKCS1_v1_5.new(key) if args.hash: if args.hash.lower() == 'md5': digest = MD5.new() elif args.hash.lower() == 'sha-1': digest = SHA.new() elif args.hash.lower() == 'sha-224': digest = SHA224.new() elif args.hash.lower() == 'sha-256': digest = SHA256.new() elif args.hash.lower() == 'sha-384': digest = SHA384.new() elif args.hash.lower() == 'SHA-512': digest = SHA512.new() else: print("[!] Hash algorithm not found.") return 0 digest.update(input) sign = keySign.sign(digest) print("[+] Hex Formart:") print(codecs.getencoder('hex')(sign)) # check if encode base64 if args.base64: signBase64 = base64.b64encode(sign) print("[+] Base64 format:") print(signBase64) # check if encode url if args.url: signURL = UrlEncode(signBase64) print("[+] URL encoded:") print(signURL) else: return -1 elif args.command == 'verify': try: key = loadKey(args.public) except (FileNotFoundError, FileExistsError) as e: print("[!] Key file not found.") return 0 except (ValueError, TypeError, IndexError) as e: print("[!] Key has improper format.") return 0 # Check to decode URL if args.url: input = UrlDecode(input.decode()) # Check to decode Base64 if args.base64: input = base64.b64decode(input) # Convert Input Bytes to Long sigLong = number.bytes_to_long(input) clearSigLong = pow(sigLong, key.e, key.n) # Convert clear Sign Long to Bytes clearSigByte = number.long_to_bytes(clearSigLong) print(codecs.getencoder('hex')(clearSigByte)) hashArg, clearSig = removePadding(clearSigByte) if hashArg == -1 or clearSig == -1: print("[!] Error! in remove padding.") else: print("[+] Hash algorithm: {}".format(hashArg)) print("[+] Clear Signature: ") print(codecs.getencoder('hex')(clearSig))
file_mb = open("dummy_1MB.txt", "r") #dummy_1KB and dummy_1MB files were created using command line argument #echo "This is just a sample line appended to create a big file.. " > dummy_1KB.txt #for /L %i in (1,1,1) do type dummy.txt >> dummy_1KB.txt #echo "This is just a sample line appended to create a big file.. " > dummy_1MB.txt #for /L %i in (1,1,14) do type dummy.txt >> dummy_1MB.txt #File is stored in the same directory as the program #reading the file message_kb = file_kb.read() message_mb = file_mb.read() filesize_kb = os.path.getsize("dummy_1KB.txt") filesize_mb = os.path.getsize("dummy_1MB.txt") print("-----1 KB File-----") h = SHA512.new() f = open("dummy_1KB.txt", "r") start_time = time.clock() for i in range(1): h.update(message_kb.encode("utf-8")) print("SHA512 time for 1 KB file: %s seconds" % (time.clock() - start_time)) print("SHA512 time for 1 byte: %s seconds" % ((time.clock() - start_time) / filesize_kb)) print("\n") print(h.hexdigest()) print("\n-----1 MB File-----") h = SHA512.new() f = open("dummy_1MB.txt", "r")
#Main #random_generator = Random.new().read #private_key = RSA.generate(1024, random_generator) #if( not (private_key.can_encrypt() and private_key.can_sign() and private_key.has_private())): # print "An unexpected error occurred while generating private key" # sys.exit() #public_key = private_key.publickey() ip = socket.gethostbyname(socket.gethostname()) hostname = socket.gethostname() hash = SHA512.new(str(hostname)) port = find_port(hostname) port = int(port) if port == -1: sys.exit("Host could not be found in relays file") relayThread = relay_Thread(1, "Thread-" + str(thread_counter), 1) thread_counter += 1 thread_list.append(relayThread) relayThread.start() input = ''
print("Bob generates and sends a challenge phrase to Alice be inserted anywhere in the nonce") print("Alice ACKs") bobChallenge = secrets.token_bytes(challengeSize) print("Alice sends encrypted hash + a signs the double hash") # 0:rock, 1:paper, 2:scissors aliceChallengeOffset = secrets.randbelow(nonceSize - challengeSize) aliceSelection = secrets.randbelow(3) aliceNonce = bytearray(secrets.token_bytes(nonceSize)) for index in range(aliceChallengeOffset, aliceChallengeOffset + challengeSize): aliceNonce[index] = bobChallenge[index - aliceChallengeOffset] aliceCombined = bytes(aliceSelection) + aliceNonce aliceHash = SHA512.new(aliceCombined) aliceDoubleHash = SHA512.new(aliceHash.digest()) aliceEncryptedMessage = PKCS1_OAEP.new(bobPublicKey).encrypt(aliceHash.digest()) aliceSignature = pss.new(alicePrivateKey).sign(aliceDoubleHash) print("Bob ACKs") print("Bob sends encrypted hash + a signs the double hash") bobChallengeOffset = secrets.randbelow(nonceSize - challengeSize) bobSelection = secrets.randbelow(3) bobNonce = bytearray(secrets.token_bytes(nonceSize)) for index in range(bobChallengeOffset, bobChallengeOffset + challengeSize): bobNonce[index] = aliceChallenge[index - bobChallengeOffset] bobCombined = bytes(bobSelection) + aliceNonce bobHash = SHA512.new(bobCombined) bobDoubleHash = SHA512.new(bobHash.digest())
def Question_D(): from Crypto.Hash import SHA256 from Crypto.Hash import SHA512 from Crypto.Hash import SHA3_256 import timeit kb = open('1kb.bin', 'rb') Mb = open('1Mb.bin', 'rb') kb_cont = kb.read() Mb_cont = Mb.read() #________SHA 256__________ sha256k = SHA256.new() a = timeit.default_timer() sha256k.update(kb_cont) b = timeit.default_timer() print(sha256k.hexdigest()) sha256M = SHA256.new() c = timeit.default_timer() sha256M.update(Mb_cont) d = timeit.default_timer() print(sha256M.hexdigest()) #________SHA 512__________ sha512k = SHA512.new() e = timeit.default_timer() sha512k.update(kb_cont) f = timeit.default_timer() print(sha512k.hexdigest()) sha512M = SHA512.new() g = timeit.default_timer() sha512M.update(Mb_cont) h = timeit.default_timer() print(sha512M.hexdigest()) #________SHA3 256_________ sha3256k = SHA3_256.new() i = timeit.default_timer() sha3256k.update(kb_cont) j = timeit.default_timer() print(sha3256k.hexdigest()) sha3256M = SHA3_256.new() k = timeit.default_timer() sha3256M.update(Mb_cont) l = timeit.default_timer() print(sha3256M.hexdigest()) print() print() print("Time required to compute a hash using SHA256 for 1kb file: ", b - a) print("Time required to compute a hash using SHA256 for 1Mb file: ", d - c) print("Time required to compute a hash using SHA512 for 1kb file: ", f - e) print("Time required to compute a hash using SHA512 for 1Mb file: ", h - g) print("Time required to compute a hash using SHA3-256 for 1kb file:", j - i) print("Time required to compute a hash using SHA3-256 for 1Mb file:", l - k) print() print("Hash speed using SHA256 for 1kb file (seconds per byte): ", (b - a) / 1024) print("Hash speed using SHA256 for 1Mb file (seconds per byte): ", (d - c) / 1024000) print("Hash speed using SHA512 for 1kb file (seconds per byte): ", (f - e) / 1024) print("Hash speed using SHA512 for 1Mb file (seconds per byte): ", (h - g) / 1024000) print("Hash speed using SHA3-256 for 1kb file (seconds per byte):", (j - i) / 1024) print("Hash speed using SHA3-256 for 1Mb file (seconds per byte):", (l - k) / 1024000)
def encrypt(self, text, key): nonce = Random.new().read(8) tempkey = SHA512.new(key + nonce).digest() cipher = ARC4.new(tempkey) encrypted_text = cipher.encrypt(text) return encrypted_text, nonce
} 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, basestring): if isinstance(key, unicode): key = key.encode('utf-8')
new_mssg0 = buf #print "new_mssg0 has %s" % buf decr_mssg = keyB.decrypt(buf) print('Decrypted Query at server: %s' % decr_mssg) buf = "" for num in range(i + 3, len(data)): buf += data[num] #print len(data)-i-3 #print "Buffer has %s" %buf f = open('mykeyA.pem', 'r') read_pub_keyA = RSA.importKey(f.read()) f.close() hash2 = SHA512.new(decr_mssg).digest() new_mssg1 = "" for i in range(len(buf)): if buf[i] == 'L': #print "Breaking on getting %s" %buf[i] break else: new_mssg1 += buf[i] #print "new_mssg1 has %s" %new_mssg1 new_mssg1 = long(new_mssg1) integrity_B = read_pub_keyA.verify(hash2, (new_mssg1, )) if (integrity_B == True): print("Signature of client is verified at the server") else: print("Signature of client at server is incorrect")
def digSig(sigKey, string): dataHash = SHA512.new(string).digest() return sigKey.sign(dataHash, '')
from Crypto.Hash import SHA512 """ En el caso de que se quiera generar el archivo automáticamente: documento = "ejercicio1ab.txt" abredocumento = open(documento,"w") texto = "Ivan\n Garcia Aguilar" abredocumento.write(texto) abredocumento.close() """ documento = 'ejercicio1ab.txt' leedocumento = open(documento, "r") texto = leedocumento.read() leedocumento.close() codigohash = SHA512.new(texto.encode("UTF-8")) print("El hash SHA512 de dicho fichero es:") print(codigohash.hexdigest())
def _sha512_digest(self, body): digest = binascii.hexlify(SHA512.new(body).digest()).decode("utf-8") return digest