class TestSHA3224(object): test_sha3_224 = generate_hash_test( load_hash_vectors, os.path.join("hashes", "SHA3"), ["SHA3_224LongMsg.rsp", "SHA3_224ShortMsg.rsp"], hashes.SHA3_224(), )
def keygenerate(): global key global user_salt user_password = input( "Enter your encryption key (or enter K if you wish to generate one): " ) #if file exists load from that or generate for user? if user_password == "K": user_password = base64.b64encode(os.urandom(128)) else: user_password = user_password.encode() user_salt = input( "Enter your encryption salt (or enter G if you wish to generate one): " ) #Same with salt? if user_salt == "G": print("Hashing key...") user_salt = base64.b64encode(os.urandom(128)) kdf = PBKDF2HMAC(algorithm=hashes.SHA3_224(), length=32, salt=user_salt, iterations=1000000, backend=default_backend()) key = base64.urlsafe_b64encode(kdf.derive(user_password)) writekey = open('key.key', 'wb') writekey.write(key) writekey.close() writesalt = open('salt.salt', 'wb') writesalt.write(user_salt) writesalt.close() else: print("Unlocking...") key = user_password menu()
def get_algorithm(self): if self.bits == 224: return hashes.SHA3_224() elif self.bits == 256: return hashes.SHA3_256() elif self.bits == 384: return hashes.SHA3_384() elif self.bits == 521: return hashes.SHA3_512()
def keygenerate(): progressspin = Spinner() global key global user_salt user_password = input( "Enter your encryption key (or enter K if you wish to generate one): ") if user_password == "K": user_password = base64.b64encode(os.urandom(512)) else: user_password = user_password.encode() user_salt = input( "Enter your encryption salt (or enter G if you wish to generate one): " ) if user_salt == "G": try: start = time.time() print("Hashing key...") progressspin.start() user_salt = base64.b64encode(os.urandom(512)) kdf = PBKDF2HMAC(algorithm=hashes.SHA3_224(), length=32, salt=user_salt, iterations=1000000, backend=default_backend()) key = base64.urlsafe_b64encode(kdf.derive(user_password)) writekey = open('key.key', 'wb') writekey.write(key) writekey.close() writesalt = open('salt.salt', 'wb') writesalt.write(user_salt) writesalt.close() progressspin.stop() end = time.time() elapsed_time = start - end print("Key generation took " + str(elapsed_time)[1:-13] + " seconds.") input("Press 'Enter' to go to main menu.") menu() except: print("Hashing error occured", sys.exc_info()[0]) print( "It is highly recommended you generate both a key and salt via the program for maximum security" ) print( "However at the very least it is recommended you generate a salt to avoid hashing errors as above" ) keygenerate() else: print("Unlocking...") key = user_password menu()
async def SHA3_224(message): message = message.encode() kdf = PBKDF2HMAC( algorithm=hashes.SHA3_224(), length=hashLen, salt= b'\xe7\xde\xc1\xf0\x81\x99\xde}\xa4\xb50u;&\x06\xe7\xa4\xbfn\xbc', iterations=hashIter, backend=default_backend()) output = base64.urlsafe_b64encode(kdf.derive(message)) return (output)
def keygenerate(): progressspin = Spinner() global key global user_salt user_password = input("Enter your encryption key (or enter K if you wish to generate one): ") #if file exists load from that or generate for user? if user_password == "K": user_password = base64.b64encode(os.urandom(128)) else: user_password = user_password.encode() user_salt = input("Enter your encryption salt (or enter G if you wish to generate one): ") #Same with salt? if user_salt == "G": try: print("Hashing key...") progressspin.start() user_salt = base64.b64encode(os.urandom(128)) kdf = PBKDF2HMAC( algorithm=hashes.SHA3_224(), length=32, salt=user_salt, iterations=1000000, backend=default_backend() ) key = base64.urlsafe_b64encode(kdf.derive(user_password)) writekey = open('key.key', 'wb') writekey.write(key) writekey.close() writesalt = open('salt.salt', 'wb') writesalt.write(user_salt) writesalt.close() progressspin.stop() except: print("Hashing error occured", sys.exc_info()[0]) print("It is highly recommended you generate both a key and salt via the program for maximum security") print("However at the very least it is recommended you generate a salt to avoid hashing errors as above") keygenerate() else: print("Unlocking...") key = user_password menu()
import binascii import pytest from cryptography.exceptions import InvalidSignature from cryptography.hazmat.primitives import hashes, hmac from .utils import wycheproof_tests _HMAC_ALGORITHMS = { "HMACSHA1": hashes.SHA1(), "HMACSHA224": hashes.SHA224(), "HMACSHA256": hashes.SHA256(), "HMACSHA384": hashes.SHA384(), "HMACSHA512": hashes.SHA512(), "HMACSHA3-224": hashes.SHA3_224(), "HMACSHA3-256": hashes.SHA3_256(), "HMACSHA3-384": hashes.SHA3_384(), "HMACSHA3-512": hashes.SHA3_512(), } @wycheproof_tests( "hmac_sha1_test.json", "hmac_sha224_test.json", "hmac_sha256_test.json", "hmac_sha384_test.json", "hmac_sha3_224_test.json", "hmac_sha3_256_test.json", "hmac_sha3_384_test.json", "hmac_sha3_512_test.json",
from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import padding, rsa from .utils import wycheproof_tests _DIGESTS = { "SHA-1": hashes.SHA1(), "SHA-224": hashes.SHA224(), "SHA-256": hashes.SHA256(), "SHA-384": hashes.SHA384(), "SHA-512": hashes.SHA512(), # Not supported by OpenSSL for RSA signing "SHA-512/224": None, "SHA-512/256": None, "SHA3-224": hashes.SHA3_224(), "SHA3-256": hashes.SHA3_256(), "SHA3-384": hashes.SHA3_384(), "SHA3-512": hashes.SHA3_512(), } def should_verify(backend, wycheproof): if wycheproof.valid: return True if wycheproof.acceptable: return not wycheproof.has_flag("MissingNull") return False
skip_message="Does not support BLAKE2s", ) @pytest.mark.requires_backend_interface(interface=HashBackend) class TestBLAKE2s256(object): test_b2s = generate_hash_test( load_hash_vectors, os.path.join("hashes", "blake2"), [ "blake2s.txt", ], hashes.BLAKE2s(digest_size=32), ) @pytest.mark.supported( only_if=lambda backend: backend.hash_supported(hashes.SHA3_224()), skip_message="Does not support SHA3_224", ) @pytest.mark.requires_backend_interface(interface=HashBackend) class TestSHA3224(object): test_sha3_224 = generate_hash_test( load_hash_vectors, os.path.join("hashes", "SHA3"), [ "SHA3_224LongMsg.rsp", "SHA3_224ShortMsg.rsp", ], hashes.SHA3_224(), )
def user_auth(): CM8_mast_salt = b'"P@\xccb9\x9a\x06\xcfq=mA\xd3\x12f\xbf\xb5\x08\xe5~\xed\x1c\xc9\x81UU\xdeL\xa3\xdb\x81\xb8\x9d@*\ xefi\xde\xcb\x8b\xe7kp7\xd4E\x0e\xc7\x0c\\\x05\x99X\x9fQ\x0f\xd4L\xf1\x1a\xf6\xab\x94\xa5\x8dM\xe0+\x0f\x1b\x0fS*\ xa1\xa3!\xf8B\x93\xbd\xe6\x1f\xc5\r\xaa\x12\x7f,BB\x81\x87\xfe\x96Th\x93\x9c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~\xa9\xedl\x08\xd4\xef\xa0\x08,\x11\x08\x80\xbf?\xf5\x99\x1d\xdc"' user_key_exists = os.path.isfile('data.dat') if user_key_exists == True: print( "This version of CryptM8 is secured with a user key, please enter it below to access the full encryption suite" ) user_key = input("User Key: ") print("Unlocking...") user_salt = base64.b64encode(CM8_mast_salt) kdf = PBKDF2HMAC(algorithm=hashes.SHA3_224(), length=32, salt=user_salt, iterations=1000000, backend=default_backend()) saved_key = open('data.dat', 'rb').read() hashed_key = base64.urlsafe_b64encode(kdf.derive(user_key.encode())) print("Saved Hash: " + str(saved_key)) print("User Hash: " + str(hashed_key)) if hashed_key != saved_key: print( "Hash mismatch! This is due to a wrong password! Please try again." ) user_auth() if hashed_key == saved_key: print("CryptM8 unlocked successfully, initialising main menu...") time.sleep(5) menu() if user_key_exists == False: print( "CryptM8 password not currently set, this will be required every time you start CryptM8, please enter one" " below...") user_key = input("Enter a user password: "******"Hashing password, please wait...") hashed_key = base64.urlsafe_b64encode(kdf.derive(user_key.encode())) print("Hash created successfully, writing to disk...") write_key = open("data.dat", "wb") write_key.write(hashed_key) write_key.close() print("Password successfully set.") input("Initialising main menu...Please wait...") time.sleep(5) menu()
class CryptoUtils: pwd_context = CryptContext(schemes=["pbkdf2_sha256"], default="pbkdf2_sha256", pbkdf2_sha256__default_rounds=30000) algorithms = { "sha256": hashes.SHA256(), "sha224": hashes.SHA224(), "sha384": hashes.SHA256(), "sha512": hashes.SHA256(), "blake2b": hashes.BLAKE2b(64), "blake2s": hashes.BLAKE2s(32), "sha3_256": hashes.SHA3_256(), "sha3_224": hashes.SHA3_224(), "sha3_384": hashes.SHA3_384(), "sha3_512": hashes.SHA3_512() } @staticmethod def hash(password): return CryptoUtils.pwd_context.hash(password) @staticmethod def check_hash(password, hashed): return CryptoUtils.pwd_context.verify(password, hashed) @staticmethod def make_key(password, algorithm, salt): if algorithm not in CryptoUtils.algorithms: raise casket.invalid_algorithm("Algorithm %s is not supported." % (algorithm)) kdf = PBKDF2HMAC(algorithm=CryptoUtils.algorithms[algorithm], length=32, salt=salt, iterations=100000, backend=default_backend()) return base64.urlsafe_b64encode(kdf.derive(password)) @staticmethod def encrypt_password(master_pswd, plain_pswd, salt=os.urandom(16), algorithm="sha256"): key = CryptoUtils.make_key(master_pswd.encode("utf-8"), algorithm, salt) cipher_suite = Fernet(key) cipher_text = cipher_suite.encrypt(plain_pswd.encode("utf-8")) enc_pswd = base64.b64encode(salt).decode('utf-8') + cipher_text.decode( 'utf-8') return enc_pswd @staticmethod def decrypt_password(master_pswd, enc_pswd, algorithm="sha256"): salt = base64.b64decode(enc_pswd[:24].encode("utf-8")) key = CryptoUtils.make_key(master_pswd.encode("utf-8"), algorithm, salt) cipher_suite = Fernet(key) plain_text = cipher_suite.decrypt(enc_pswd[24:].encode("utf-8")) plain_text_utf8 = plain_text.decode("utf-8") return plain_text_utf8 @staticmethod def get_salt(encrypted_string): return base64.b64decode(encrypted_string[:24].encode("utf-8"))
from asn1crypto.algos import SignedDigestAlgorithm from cryptography.hazmat.primitives import hashes _STR_TO_HASH_ALGO = { 'md5' : hashes.MD5(), 'sha1' : hashes.SHA1(), 'sha224' : hashes.SHA224(), 'sha256' : hashes.SHA256(), 'sha384' : hashes.SHA384(), 'sha512' : hashes.SHA512(), 'sha512_224' : hashes.SHA512_224(), 'sha512_256' : hashes.SHA512_256(), 'sha3_224' : hashes.SHA3_224(), 'sha3_256' : hashes.SHA3_256(), 'sha3_384' : hashes.SHA3_384(), 'sha3_512' : hashes.SHA3_512(), } def get_hash_algo_by_name(hash_algo: str): hash_algo = hash_algo.lower() if hash_algo not in _STR_TO_HASH_ALGO: raise ValueError("Invalid hash algorithm '{}'".format(hash_algo)) return _STR_TO_HASH_ALGO[hash_algo] def update_sig_algo_if_no_hash_algo(sig_algo: SignedDigestAlgorithm, hash_algo: str): n_sig_algo = sig_algo['algorithm'].native if n_sig_algo == 'rsassa_pkcs1v15' or n_sig_algo == 'ecdsa' or n_sig_algo == 'dsa': if n_sig_algo == 'rsassa_pkcs1v15': n_sig_algo = 'rsa' if hash_algo == 'md5':
b1_h2_hval = int(b1_h2_hval, 16) b1_h2_hval = int(b1_h2_hval) % (len(bit_vect1)) bit_vect1[b1_h2_hval] = 1 b1_h3 = hashes.Hash(hashes.SHA384(), backend=backend) b1_h3.update(TempHash.encode()) b1_h3_hval = b1_h3.finalize() b1_h3_hval = hexlify(b1_h3_hval) b1_h3_hval = int(b1_h3_hval, 16) b1_h3_hval = int(b1_h3_hval) % (len(bit_vect1)) bit_vect1[b1_h3_hval] = 1 #bloom filter 2 setting bad passwords b1_h4 = hashes.Hash(hashes.SHA3_224(), backend=backend) b1_h4.update(TempHash.encode()) b1_h4_hval = b1_h4.finalize() b1_h4_hval = hexlify(b1_h4_hval) b1_h4_hval = int(b1_h4_hval, 16) #calculated index for each bloomfilter b1_h4_hval = int(b1_h4_hval) % (len(bit_vect2)) #set corresponding bloom filter index to 1 bit_vect2[b1_h4_hval] = 1 b1_h5 = hashes.Hash(hashes.SHA3_256(), backend=backend) b1_h5.update(TempHash.encode()) b1_h5_hval = b1_h5.finalize() b1_h5_hval = hexlify(b1_h5_hval)
def _publish_certificate(req: object, issuer: dict): logger.info('Create a certificate builder...') crt_builder = x509.CertificateBuilder() crt_builder = crt_builder.subject_name(name=req._subject()) crt_builder = crt_builder.public_key(key=req._public_key()) for extension in req._extensions(): crt_builder = crt_builder.add_extension(extension=extension.value, critical=extension.critical) logger.info('Ready to sign the certificate request...') if not isinstance(issuer['valid_year'], int): issuer['valid_year'] = int(issuer['valid_year']) if issuer['is_ca'] == 'true': issuer['is_ca'] = True if issuer['is_ca'] == 'false': issuer['is_ca'] = False crt_builder = crt_builder.not_valid_before(time=datetime.datetime.today()) crt_builder = crt_builder.not_valid_after( time=datetime.datetime.today() + datetime.timedelta(days=issuer['valid_year'] * 365)) crt_builder = crt_builder.serial_number(number=x509.random_serial_number()) crt_builder = crt_builder.add_extension(extension=x509.BasicConstraints( ca=issuer['is_ca'], path_length=None), critical=True) logger.info( 'Select CA to sign the certificate signing request and output certificate' ) if issuer['ca'] == 'SelfSign': logger.debug('CA is self-signed') crt_builder = crt_builder.issuer_name(name=req._subject()) ca_key = req.private_key() else: ca_dir = os.path.join( os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'common_static/ca') ca_file = "{}/{}.pfx".format(ca_dir, issuer['ca']) logger.debug("CA file is located in {}".format(ca_file)) with open(file=ca_file, mode='rb') as f: ca_bytes = f.read() logger.debug('CA file content is \n{}'.format(ca_bytes)) crt_chain = ReadCertificateChain({ 'bytes': ca_bytes, 'password': b'Cisco123!' }) ca_crt = crt_chain.certificate(data_type='object') ca_key = crt_chain.private_key(data_type='object') crt_builder = crt_builder.issuer_name(name=ca_crt.subject) hash_obj_list = { hashes.MD5(), hashes.SHA1(), hashes.SHA224(), hashes.SHA256(), hashes.SHA384(), hashes.SHA512(), hashes.SHA512_224(), hashes.SHA512_256(), hashes.SHA3_224(), hashes.SHA3_256(), hashes.SHA3_384(), hashes.SHA3_512() } for hash_obj in hash_obj_list: if issuer['hash_alg'] == hash_obj.name: hash_algor = hash_obj break else: hash_algor = hashes.MD5() return crt_builder.sign(private_key=ca_key, algorithm=hash_algor, backend=default_backend())