from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding data_file = open("data.bin", 'rb') data = data_file.read() data_file.close() key_file = open("master-private.pem", 'rb') key_data = key_file.read() key_file.close() private_key = serialization.load_pem_private_key( key_data, password=None, backend=default_backend() ) signature = private_key.sign( data, padding.PKCS1v15(), hashes.SHA256() ) signature_file = open("data.sig", 'wb') signature_file.write(signature) signature_file.close()
def test_derive_pbkdf2_raises_unsupported_on_old_openssl(self): if backend.pbkdf2_hmac_supported(hashes.SHA256()): pytest.skip("Requires an older OpenSSL") with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_HASH): backend.derive_pbkdf2_hmac(hashes.SHA256(), 10, b"", 1000, b"")
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"))
def sha256_hash(data): assert (isinstance(data, bytes)) digest = hashes.Hash(hashes.SHA256(), backend=default_backend()) digest.update(data) return digest.finalize()
# Open the zip archive archive = zipfile.ZipFile(sys.argv[2], 'r') try: archive_content_name_list = archive.namelist() for name in archive_content_name_list: if name.endswith('key'): symmetric_key_file = name elif name.endswith('enc'): data_file_encrypted = name # Read and decrypt the symmetric key symmetric_key_encrypted = archive.read(symmetric_key_file) symmetric_key = private_key.decrypt( symmetric_key_encrypted, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) data_encrypted = archive.read(data_file_encrypted) fernet = Fernet(symmetric_key) data = fernet.decrypt(data_encrypted) data = data.decode("utf8") current_date_str = datetime.now().strftime("%d-%m-%Y_%H:%M:%S") with open('backup_rebels_decrypt_' + current_date_str + '.json', 'w', encoding='utf-8') as output: output.write(data) finally:
def get_key(password): digest = hashes.Hash(hashes.SHA256(), backend=default_backend()) digest.update(password) return base64.urlsafe_b64encode(digest.finalize())
def sign(self, data): """ Generate a signature based on the data using the local private key. """ return self.private_key.sign( json.dumps(data).encode('utf-8'), ec.ECDSA(hashes.SHA256()))
@app.exception_handler(Exception) async def on_invalid_cookie(request: Request, exc: InvalidToken) -> Response: response = Response(status_code=status.HTTP_401_UNAUTHORIZED) response.unset_cookie(settings.COOKIE_NAME) return response connect( app=app, secret=secret_key, signer=Fernet( b64encode( PBKDF2HMAC( algorithm=hashes.SHA256(), length=32, salt=salt, iterations=100, ).derive(secret_key.encode("utf-8")))), on_load_cookie=on_load_cookie, ) @app.on_event("shutdown") async def close_session(): await app.session.save() @app.post("/init/") async def init_session(
def hashm(message): digest = hashes.Hash(hashes.SHA256(), backend=default_backend()) digest.update(message) hash_of_message = digest.finalize() return hash_of_message
def update(firmware,v, assinatura_falsa=False): if (firmware > 2 and firmware < 1): return print("Modelo inválido") if firmware == 1: with open('../firmware_tipo1.bin', 'rb') as file: fw = file.read() if firmware == 2: with open('../firmware_tipo2.bin', 'rb') as file: fw = file.read() with open('../chave_privada.pem', 'rb') as file: chave_privada = serialization.load_pem_private_key(file.read(), password=None) v = v.to_bytes(8, byteorder='big') sha256 = hashlib.sha256() sha256.update(fw) fw_digested = sha256.digest() size= len(fw) size = size.to_bytes(8, byteorder='big') quadros = [] num_quadros = math.floor(len(fw)/480) for i in range(num_quadros): quadros.append(fw[i*480:(i+1)*480]) mod = len(fw) % 480 quadros.append(fw[num_quadros*480:num_quadros*480+mod]) fw_sig = chave_privada.sign(fw+v, padding.PKCS1v15(), hashes.SHA256()) assets = fw_digested+fw_sig+size+v T = len(assets) T = T.to_bytes(4, byteorder='big') assets = bytes([4]) + T + assets ser = serial.Serial('COM21') print("Iniciando upload do novo firmware...") ser.write(assets) total = 100/len(quadros) completo = 0 print(f"Completado: {completo}%") for quadro in quadros: T = len(quadro) T = T.to_bytes(4, byteorder='big') codigo = bytes([5]) + T + quadro ser.write(codigo) flag = 1 while flag==1: r = ser.read(1) if r==bytes([0]): flag = 0 completo = completo + total print(f"Completado: {completo}%") print("Transmissão finalizada") fim = bytes([6]) T = 1 T = T.to_bytes(4, byteorder='big') (ser.write(fim+T))
def hmac(self, snowflake, secret): if not isinstance(secret, bytes): secret = str(secret).encode() hmac = HMAC(secret, hashes.SHA256(), backend=default_backend()) hmac.update(struct.pack('l', int(snowflake))) return base64.urlsafe_b64encode(hmac.finalize()).decode()
if shared_key != None: print("Our shared key is: ", shared_key.encode("string_escape")) # Obtain encrypted message from the server data = server.get_encrypted_message() iv = data["IV"] ciphertext = data["Ciphertext"] if shared_key == None: exit() ### Task 4 ### # Use HKDF to convert the shared key into an aes key # This HKDF uses Sha256, Length 32 (256 bits), no salt, 'ecdhexercise' info. from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.hkdf import HKDF hkdf = HKDF(algorithm=hashes.SHA256(), length=32, salt=None, info=b'ecdhexercise', backend=default_backend()) aes_key = hkdf.derive(shared_key) ### Task 5 ### # Use AES CTR to decrypt the message with the IV and aes key cipher = Cipher(algorithms.AES(aes_key), modes.CTR(iv), backend=default_backend()) decryptor = cipher.decryptor() message = decryptor.update(ciphertext) + decryptor.finalize() if message != None:
def process(self, msg): # Contador de mensagens aumenta self.msg_count += 1 # Se receber mensagem vazia, assume que o cliente se desconectou ou teve um # problema com a mensagem recebida (assinatura inválida, confidencialidade # comprometida, etc.) if len(msg) <= 0: return None # Se receber a 1ª mensagem, trata-se da chave pública de DH do cliente elif self.msg_count == 0: print('> Client #{} [{}] sent its public key.'.format(self.id, self.msg_count)) # Chave pública de DH do cliente cl_key_public_dh_bytes = msg cl_key_public_dh = load_pem_public_key ( cl_key_public_dh_bytes, backend = default_backend() ) # Chave partilhada (gerada a partir da chave privada de DH do servidor e da # pública do cliente) key_shared = sv_key_private_dh.exchange(cl_key_public_dh) hkdf = HKDF ( algorithm = hashes.SHA256(), length = 64, salt = None, info = hkdf_info, backend = default_backend() ) # Derivação da chave partilhada key_derived = hkdf.derive(key_shared) # Separação da chave derivada em chave de MAC e chave de encriptação e # desencriptação self.key_mac = key_derived[:32] self.key_enc = key_derived[32:] # Mensagem a assinar, constituida por ambas as chaves públicas de DH self.sig_message = sv_key_public_dh_bytes + cl_key_public_dh_bytes # Leitura da chave privada de RSA do servidor armazenada f = open('sv_key_private_rsa.txt', 'rb') sv_key_private_rsa_bytes = f.read() f.close() # Validação da chave privada de RSA do servidor try: sv_key_private_rsa = serialization.load_pem_private_key ( sv_key_private_rsa_bytes, password = None, backend = default_backend() ) except: print('» Invalid private RSA key!') return None # Assinatura do servidor assinada pela sua chave privade de RSA sv_signature = sv_key_private_rsa.sign ( self.sig_message, apadding.PSS ( mgf = apadding.MGF1(hashes.SHA256()), salt_length = apadding.PSS.MAX_LENGTH ), hashes.SHA256() ) print('» Sending my signature and public key #{}...'.format(self.id)) # Envio da assinatura e da chave pública de DH do servidor return sv_signature + sv_key_public_dh_bytes # Se receber a 2ª mensagem, trata-se da assinatura e da primeria mensagem # encriptada pelo cliente elif self.msg_count == 1: print('> Client #{} [{}] sent its signature.'.format(self.id, self.msg_count)) # Os primeiros 256 bytes estão reservados para a assinatura do cliente cl_signature = msg[:256] msg = msg[256:] # Leitura da chave pública de RSA do cliente armazenada f = open('cl_key_public_rsa.txt', 'rb') cl_key_public_rsa_bytes = f.read() f.close() # Validação da chave pública de RSA do cliente try: cl_key_public_rsa = load_pem_public_key ( cl_key_public_rsa_bytes, backend = default_backend() ) except: print('» Invalid RSA key from Client#{}!'.format(self.id)) return None # Verificação da assinatura do cliente através da sua chave pública de RSA try: cl_key_public_rsa.verify ( cl_signature, self.sig_message, apadding.PSS ( mgf = apadding.MGF1(hashes.SHA256()), salt_length = apadding.PSS.MAX_LENGTH ), hashes.SHA256() ) print('» Client #{}\'s signature accepted!'.format(self.id)) except: print('» Client #{}\'s signature denied!'.format(self.id)) return None # A partir da 2ª mensagem, trata-se de uma mensagem encriptada pelo cliente if self.msg_count >= 1: # Separação da mensagem recebida (1ºs 32 bytes formam a tag do MAC, os # restantes formam a mensagem encriptada) msg_tag = msg[:32] msg_enc = msg[32:] # Verificação da tag da mensagem mac_check = unmac(msg_enc, self.key_mac, msg_tag) # Se a integridade da mensagem tiver sido atacada if not mac_check: print('» Client #{}\'s message\'s integrity compromised!'.format(self.id)) return None else: # Desencriptação da mensagem msg_dec = decrypt(msg_enc, self.key_enc) # Se a confidencialidade da mensagem tiver sido atacada if not msg_dec: print('» Client #{}\'s message\'s confidentiality compromised!'.format(self.id)) return None else: # Unpadding da mensagem msg = unpad(msg_dec) text = msg.decode() print('> Client #{} [{}]: "{}"'.format(self.id, self.msg_count, text)) # Transformação das letras da mensagem para maiúsculas my_msg = text.upper().encode() print('» Input #{}: {}'.format(self.id, text.upper())) # Padding da mensagem msg_pad = pad(my_msg) # Encriptação da mensagem msg_enc = encrypt(msg_pad, self.key_enc) # Geração da tag da mensagem msg_tag = mac(msg_enc, self.key_mac) # Concatenação da tag com a mensagem encriptada return msg_tag + msg_enc
def authenticate(self): jwt_header_bytes = urlsafe_b64encode( json.dumps({ 'alg': 'RS256', 'typ': 'JWT' }).encode('utf-8')) epoch_time = int(time.time()) jwt_claims_bytes = urlsafe_b64encode( json.dumps({ 'iss': self._service_account_info['client_email'], 'scope': 'https://www.googleapis.com/auth/ndev.clouddns.readwrite', 'aud': 'https://www.googleapis.com/oauth2/v4/token', 'exp': epoch_time + 60 * 10, 'iat': epoch_time }).encode('utf-8')) private_key = serialization.load_pem_private_key( self._service_account_info['private_key'].encode('utf-8'), password=None, backend=default_backend()) jwt_sign_bytes = urlsafe_b64encode( private_key.sign(b'.'.join([jwt_header_bytes, jwt_claims_bytes]), padding.PKCS1v15(), hashes.SHA256())) jwt_bytes = b'.'.join( [jwt_header_bytes, jwt_claims_bytes, jwt_sign_bytes]) auth_request = requests.request( 'POST', 'https://www.googleapis.com/oauth2/v4/token', data={ 'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer', 'assertion': jwt_bytes }, headers={'Content-Type': 'application/x-www-form-urlencoded'}) auth_request.raise_for_status() post_result = auth_request.json() if not post_result['access_token']: raise Exception('Error, could not grant RW access on the ' 'Google Cloud DNS API for user: {0}'.format( self._get_provider_option('auth_email'))) self._token = post_result['access_token'] results = self._get('/managedZones') targeted_managed_zone_ids = [ managedZone['id'] for managedZone in results['managedZones'] if managedZone['dnsName'] == '{0}.'.format(self.domain) ] if not targeted_managed_zone_ids: raise Exception( 'Error, domain {0} is not registered for this project'.format( self.domain)) self.domain_id = targeted_managed_zone_ids[0]
def _extract_blacklisted_root_records(blacklisted_certs_content: str) -> List[ScrapedRootCertificateRecord]: # The file only contains a list of SHA-256 fingerprints blacklisted_records = [] for fingerprint in blacklisted_certs_content.split("\n")[1:]: if not fingerprint: continue blacklisted_records.append( ScrapedRootCertificateRecord('Blacklisted', bytes(bytearray.fromhex(fingerprint)), hashes.SHA256()) ) return blacklisted_records
# In summary: for RSA signatures, use sign-then-encrypt. # There are more paranoid schemes such as sign-then-encrypt-then-sign-again from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) public_key = private_key.public_key() message = b"Alice, this is Bob. Meet me at dawn" # Note the padding. # OAEP is recommended for encryption, but PSS for signatures signature = private_key.sign( message, padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256(), ) public_key.verify( signature, message, padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256(), ) print("Verification passed! It would have thrown an exception otherwise")
# csr key, used to apply for the certificate ''' Information about our public key (including a signature of the entire body). Information about who we are. Information about what domains this certificate is for. ''' csr = x509.CertificateSigningRequestBuilder().subject_name(x509.Name([\ x509.NameAttribute(NameOID.COUNTRY_NAME, u'CH'),\ x509.NameAttribute(NameOID.LOCALITY_NAME, u'SHENZHEN'),\ x509.NameAttribute(NameOID.COMMON_NAME, u'CAOBAOGUO'),\ ])).add_extension(\ x509.SubjectAlternativeName([\ x509.DNSName(u'caobaoguo.com'),\ x509.DNSName(u'baicells.com'),\ ]),\ critical=False,).sign(private_key, hashes.SHA256(), default_backend()) with open('rsa_csr.pem', 'wb') as f: f.write(csr.public_bytes(serialization.Encoding.PEM)) # certificate one_day = datetime.timedelta(1, 0, 0) public_key = private_key.public_key() builder = x509.CertificateBuilder() builder = builder.subject_name(x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, u'cryptography.io'), ])) builder = builder.issuer_name(x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, u'cryptography.io'), ])) builder = builder.not_valid_before(datetime.datetime.today() - one_day) builder = builder.not_valid_after(datetime.datetime.today() + (one_day * 30))
def precompute_values(self) -> bytes: capsule = self.task.capsule cfrag = self.task.cfrag umbral_params = default_params() e, v, _ = capsule.components() e1 = cfrag.point_e1 v1 = cfrag.point_v1 e2 = cfrag.proof.point_e2 v2 = cfrag.proof.point_v2 u = umbral_params.u u1 = cfrag.proof.point_kfrag_commitment u2 = cfrag.proof.point_kfrag_pok metadata = cfrag.proof.metadata h = self.get_proof_challenge_scalar() e1h = h * e1 v1h = h * v1 u1h = h * u1 z = cfrag.proof.bn_sig ez = z * e vz = z * v uz = z * u only_y_coord = dict(x_coord=False, y_coord=True) # E points e_y = get_coordinates_as_bytes(e, **only_y_coord) ez_xy = get_coordinates_as_bytes(ez) e1_y = get_coordinates_as_bytes(e1, **only_y_coord) e1h_xy = get_coordinates_as_bytes(e1h) e2_y = get_coordinates_as_bytes(e2, **only_y_coord) # V points v_y = get_coordinates_as_bytes(v, **only_y_coord) vz_xy = get_coordinates_as_bytes(vz) v1_y = get_coordinates_as_bytes(v1, **only_y_coord) v1h_xy = get_coordinates_as_bytes(v1h) v2_y = get_coordinates_as_bytes(v2, **only_y_coord) # U points uz_xy = get_coordinates_as_bytes(uz) u1_y = get_coordinates_as_bytes(u1, **only_y_coord) u1h_xy = get_coordinates_as_bytes(u1h) u2_y = get_coordinates_as_bytes(u2, **only_y_coord) # Get hashed KFrag validity message hash_function = hashes.Hash(hashes.SHA256(), backend=backend) kfrag_id = cfrag.kfrag_id precursor = cfrag.point_precursor delegating_pubkey = self.delegating_pubkey receiving_pubkey = self.receiving_pubkey validity_input = (kfrag_id, delegating_pubkey, receiving_pubkey, u1, precursor) kfrag_validity_message = bytes().join( bytes(item) for item in validity_input) hash_function.update(kfrag_validity_message) hashed_kfrag_validity_message = hash_function.finalize() # Get KFrag signature's v value kfrag_signature_v = get_signature_recovery_value( message=hashed_kfrag_validity_message, signature=cfrag.proof.kfrag_signature, public_key=self.verifying_pubkey, is_prehashed=True) cfrag_signature_v = get_signature_recovery_value( message=bytes(cfrag), signature=self.task.cfrag_signature, public_key=self.ursula_pubkey) metadata_signature_v = get_signature_recovery_value( message=self.task.signature, signature=metadata, public_key=self.ursula_pubkey) specification = self.task.get_specification( ursula_pubkey=self.ursula_pubkey, alice_address=self.alice_address, blockhash=self.blockhash) specification_signature_v = get_signature_recovery_value( message=specification, signature=self.task.signature, public_key=self.bob_pubkey) ursula_pubkey_prefix_byte = bytes(self.ursula_pubkey)[0:1] # Bundle everything together pieces = ( e_y, ez_xy, e1_y, e1h_xy, e2_y, v_y, vz_xy, v1_y, v1h_xy, v2_y, uz_xy, u1_y, u1h_xy, u2_y, hashed_kfrag_validity_message, self.alice_address, # The following single-byte values are interpreted as a single bytes5 variable by the Solidity contract kfrag_signature_v, cfrag_signature_v, metadata_signature_v, specification_signature_v, ursula_pubkey_prefix_byte, ) return b''.join(pieces)
class TestUtilsCryptoPBKDF2(unittest.TestCase): digest_map = { hashes.MD5: hashlib.md5, hashes.SHA1: hashlib.sha1, hashes.SHA224: hashlib.sha224, hashes.SHA256: hashlib.sha256, hashes.SHA384: hashlib.sha384, hashes.SHA512: hashlib.sha512, } # http://tools.ietf.org/html/draft-josefsson-pbkdf2-test-vectors-06 rfc_vectors = [ { "args": { "password": "******", "salt": "salt", "iterations": 1, "dklen": 20, "digest": hashes.SHA1(), }, "result": "0c60c80f961f0e71f3a9b524af6012062fe037a6", }, { "args": { "password": "******", "salt": "salt", "iterations": 2, "dklen": 20, "digest": hashes.SHA1(), }, "result": "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957", }, { "args": { "password": "******", "salt": "salt", "iterations": 4096, "dklen": 20, "digest": hashes.SHA1(), }, "result": "4b007901b765489abead49d926f721d065a429c1", }, # # this takes way too long :( # { # "args": { # "password": "******", # "salt": "salt", # "iterations": 16777216, # "dklen": 20, # "digest": hashes.SHA1(), # }, # "result": "eefe3d61cd4da4e4e9945b3d6ba2158c2634e984", # }, { "args": { "password": "******", "salt": "saltSALTsaltSALTsaltSALTsaltSALTsalt", "iterations": 4096, "dklen": 25, "digest": hashes.SHA1(), }, "result": "3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038", }, { "args": { "password": "******", "salt": "sa\0lt", "iterations": 4096, "dklen": 16, "digest": hashes.SHA1(), }, "result": "56fa6aa75548099dcc37d7f03425e0c3", }, ] regression_vectors = [ { "args": { "password": "******", "salt": "salt", "iterations": 1, "dklen": 20, "digest": hashes.SHA256(), }, "result": "120fb6cffcf8b32c43e7225256c4f837a86548c9", }, { "args": { "password": "******", "salt": "salt", "iterations": 1, "dklen": 20, "digest": hashes.SHA512(), }, "result": "867f70cf1ade02cff3752599a3a53dc4af34c7a6", }, { "args": { "password": "******", "salt": "salt", "iterations": 1000, "dklen": 0, "digest": hashes.SHA512(), }, "result": ("afe6c5530785b6cc6b1c6453384731bd5ee432ee" "549fd42fb6695779ad8a1c5bf59de69c48f774ef" "c4007d5298f9033c0241d5ab69305e7b64eceeb8d" "834cfec"), }, # Check leading zeros are not stripped (#17481) { "args": { "password": b'\xba', "salt": "salt", "iterations": 1, "dklen": 20, "digest": hashes.SHA1(), }, "result": '0053d3b91a7f1e54effebd6d68771e8a6e0b2c5b', }, ] def django_args(self, kwargs): kwargs = kwargs.copy() kwargs["digest"] = self.digest_map[kwargs["digest"].__class__] return kwargs @override_settings(CRYPTOGRAPHY_DIGEST=hashes.SHA1()) def test_defaults(self): result = pbkdf2('password', 'salt', 1) self.assertEqual('0c60c80f961f0e71f3a9b524af6012062fe037a6', binascii.hexlify(result).decode('ascii')) def test_public_vectors(self): for vector in self.rfc_vectors: result = pbkdf2(**vector['args']) self.assertEqual( binascii.hexlify(result).decode('ascii'), vector['result']) def test_regression_vectors(self): for vector in self.regression_vectors: result = pbkdf2(**vector['args']) self.assertEqual( binascii.hexlify(result).decode('ascii'), vector['result']) def test_django_parity(self): for vector in self.rfc_vectors: self.assertEqual(pbkdf2(**vector['args']), django_pbkdf2(**self.django_args(vector['args'])))
def get_certificates(name, pool): with open("sca.crt", "rb") as crt: CA_PK = extract_server_pk(crt.read()) #Génération de la clef secrète r_key = os.urandom(32) pub_key = serialization.load_pem_public_key(CA_PK, backend=default_backend()) #Chiffrement Asymétrique de la clef secrète ciphertext = pub_key.encrypt( r_key, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) #Début phase de connexion au serveur pour établir un échange # symétrique entre les deux acteurs payload = {} payload["data"] = b64encode(ciphertext) payload["host"] = name response = requests.post("{}/connexion".format(APIENDPOINT), data=payload) #print(response.text) data = json.loads(response.text) print("statut:{}".format(response.status_code)) dec = _decrypt_aes(r_key, b64decode(data['ct'].encode())) #print(b64decode(dec)) #Après les vérifications côté serveur, le serveur établit démarre une session # avec le client if (b64decode(dec) == b"etablished"): #horodatage _date = datetime.datetime.now() print("[{}] > Début de la session au SCA".format( _date.strftime("%H:%M:%S"))) #Place reservé pour la boucle (début) for i in range(int(pool)): _date = datetime.datetime.now() #Génération du csr csr = generate_keys(name, (i + 1)) print("[{}] > Envoie du CSR".format(_date.strftime("%H:%M:%S"))) #Chiffrement symétrqiue des échanges csr_crypt = _encrypt_aes(r_key, csr + (b"0" * (800 - len(csr)))) #Paramètres payload = {} payload["data"] = b64encode(csr_crypt) payload["host"] = name #Le client demande l'etablissement d'un certificat en envoyant son "CSR" response = requests.post("{}/ask_certificate".format(APIENDPOINT), data=payload) data = json.loads(response.text) #Réception et déchiffrement de la réponse du serveur qui contient # le certificat dec_certificate = _decrypt_aes( r_key, b64decode(data['certificate'].encode())) _date = datetime.datetime.now() print("[{}] > Reception du CRT".format(_date.strftime("%H:%M:%S"))) print("[{}] > Ecriture du CRT dans un fichier".format( _date.strftime("%H:%M:%S"))) with open("pool/certs/{}_{}.mrt.crt".format(name, i + 1), "wb") as fout: fout.write(dec_certificate.rstrip(b"0")) _date = datetime.datetime.now() print("[{}] > Fin de l ecriture du CRT dans un fichier".format( _date.strftime("%H:%M:%S"))) #Après avoir recu tous ses certificats signés par le SCA #Le client demande au serveur de le déconnecter end_message = b"deconnexion" end = _encrypt_aes(r_key, end_message + (b"0" * (16 - len(end_message)))) payload = {} payload["data"] = b64encode(end) payload["host"] = name response = requests.post("{}/deconnexion".format(APIENDPOINT), data=payload) data = json.loads(response.text) _date = datetime.datetime.now() print("[{}] > Fin de la session au serveur SCA".format( _date.strftime("%H:%M:%S"))) else: print("Erreur")
def create_device(device_file, device_key_file, signer_file, signer_key_file, root_file, root_key_file): # Make sure files exist if not (os.path.isfile(signer_file) and os.path.isfile(signer_key_file) and os.path.isfile(root_file)): raise FileNotFoundError('Failed to find {}, {}, or {}'.format(signer_file, signer_key_file, root_file)) # Setup cryptography be = cryptography.hazmat.backends.default_backend() print('\nLoad Device Public Key') # Load the public key from the device or a file print(' Loading from %s' % device_key_file) with open(device_key_file, 'r') as f: public_key_pem = f.read() # Convert the key into the cryptography format public_key = serialization.load_pem_public_key(public_key_pem.encode('ascii'), be) print('\nLoad Signer') # Load the Signing key from the file print(' Loading key from %s' % signer_key_file) with open(signer_key_file, 'rb') as f: signer_ca_priv_key = serialization.load_pem_private_key(data=f.read(), password=None, backend=be) # Load the Signing Certificate from the file print(' Loading certificate from %s' % signer_file) with open(signer_file, 'rb') as f: signer_ca_cert = x509.load_pem_x509_certificate(f.read(), be) with open(root_file, 'rb') as f: root_ca_cert = x509.load_pem_x509_certificate(f.read(), be) root_public = root_ca_cert.public_key() # Build certificate print('\nCreate Device Certificate template') builder = x509.CertificateBuilder() builder = builder.issuer_name(signer_ca_cert.subject) # Device cert must have minutes and seconds set to 0 builder = builder.not_valid_before(datetime.datetime.now(tz=pytz.utc).replace(minute=0,second=0)) # Should be year 9999, but this doesn't work on windows builder = builder.not_valid_after(datetime.datetime(3000, 12, 31, 23, 59, 59)) o = input("organization name:") cn = str('0123xxxxxxxxxxxxee') with open('ou.txt', 'w') as f: print(o, file=f) builder = builder.subject_name(x509.Name([ x509.NameAttribute(x509.oid.NameOID.ORGANIZATION_NAME, o), x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, cn)])) builder = builder.public_key(public_key) # Device certificate is generated from certificate dates and public key builder = builder.serial_number(device_cert_sn(16, builder)) # Subject Key ID is used as the thing name and MQTT client ID and is required for this demo builder = builder.add_extension( x509.SubjectKeyIdentifier.from_public_key(public_key), critical=False) issuer_ski = signer_ca_cert.extensions.get_extension_for_class(x509.SubjectKeyIdentifier) builder = builder.add_extension( x509.AuthorityKeyIdentifier.from_issuer_subject_key_identifier(issuer_ski.value), critical=False) # Sign certificate with longest R & S pattern while True: device_cert = builder.sign(private_key=signer_ca_priv_key, algorithm=hashes.SHA256(), backend=be) cert = decoder.decode(device_cert.public_bytes(encoding=serialization.Encoding.DER), asn1Spec=rfc2459.Certificate())[0] info = cert_sig_offset_length(cert) if info['length'] == 75: break # Save certificate for reference print(' Save Device Certificate to %s' % device_file) with open(device_file, 'wb') as f: f.write(device_cert.public_bytes(encoding=serialization.Encoding.PEM)) # Save root public key print(' Save Root Public Key to %s' % root_key_file) with open(root_key_file, 'wb') as f: f.write(root_public.public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo))
# License for the specific language governing permissions and limitations # under the License. # from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives.asymmetric import utils from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from openstack.image.iterable_chunked_file import IterableChunkedFile HASH_METHODS = { 'SHA-224': hashes.SHA224(), 'SHA-256': hashes.SHA256(), 'SHA-384': hashes.SHA384(), 'SHA-512': hashes.SHA512(), } class ImageSigner(object): """Image file signature generator. Generates signatures for files using a specified private key file. """ def __init__(self, hash_method='SHA-256', padding_method='RSA-PSS'): padding_types = { 'RSA-PSS': padding.PSS( mgf=padding.MGF1(HASH_METHODS[hash_method]),
def verify(self, message, sig, public): try: public.verify(sig,message,padding.PSS(mgf=padding.MGF1(hashes.SHA256()),salt_length=padding.PSS.MAX_LENGTH),hashes.SHA256()) return True except: return False
from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from bitstring import BitArray # Hashes are a method to authenticate that a message that was sent # has not been tampered with. It is essentially an irreversible # encryption that is unique to the message that is sent. So # if somehow the original message were to be tempered with, Alice # could send a hash of her message to Bob and Bob could hash the message # he received in order to verify the hashes are the same digest = hashes.Hash(hashes.SHA256(), backend=default_backend()) digest.update(b"Here is the message I want to send") digest.update(b"This is some additional information to add to my message") first_digest = digest.finalize() print(first_digest) # Observe what was printed to the terminal for from the above print statement and look at the next bit of code. # Here we are only adding one character to the message from before but you can see in the terminal output # that the corresponding hash is completely different. # The additional bit of code is to again demonstrate that the hash remains exactly the same until we add or remove from # it digest2 = hashes.Hash(hashes.SHA256(), backend=default_backend()) digest2.update(b"Here is the message I want to send") digest2.update(b"This is some additional information to add to my messagd") digest3 = digest2.copy() digest2.update(b"h") print(digest2.finalize())
key = os.urandom(32) #key = b'Delta@1234' print('Random Key generated: ', key) file = open('key.key', 'wb') file.write(key) file.close() # Encrypting the key file print('Now encrypting the key file.') password = getpass.getpass(prompt='Enter password to encrypt key file: ') backend = default_backend() salt = b'\xda\x06\xb23lHI\x90\xc49\x81\x9a\x8a\xc385' print(salt) encoded_passowrd = password.encode('utf-8') print('Encoded Pass: '******'key.key', 'rb') as file: # read all file data file_data = file.read() # encrypt data encrypted_data = fernet.encrypt(file_data)
def verify(public_key,data,signature): """ Verify a signature based on the original public key and data """ (r,s)=signature deserialized_public_key = serialization.load_pem_public_key( public_key.encode('utf-8'), default_backend() ) try: deserialized_public_key.verify(encode_dss_signature(r,s),json.dumps(data).encode('utf-8'),ec.ECDSA(hashes.SHA256())) return True except InvalidSignature: return False
def test_invalid_builder(self): private_key = RSA_KEY_2048.private_key(backend) with pytest.raises(TypeError): backend.create_x509_crl(object(), private_key, hashes.SHA256())
def process_ocsp_request(self, data): try: ocsp_req = ocsp.load_der_ocsp_request(data) # NOQA except Exception as e: log.exception(e) return self.malformed_request() # Fail if there are any critical extensions that we do not understand for ext in ocsp_req.extensions: if ext.critical and not isinstance(ext.value, OCSPNonce): # pragma: no cover # It seems impossible to get cryptography to create such a request, so it's not tested return self.malformed_request() # Get CA and certificate try: ca = self.get_ca() except CertificateAuthority.DoesNotExist: log.error('%s: Certificate Authority could not be found.', self.ca) return self.fail() try: cert = self.get_cert(ca, int_to_hex(ocsp_req.serial_number)) except Certificate.DoesNotExist: log.warning('OCSP request for unknown cert received.') return self.fail() except CertificateAuthority.DoesNotExist: log.warning('OCSP request for unknown CA received.') return self.fail() # get key/cert for OCSP responder try: responder_key = self.get_responder_key() responder_cert = self.get_responder_cert() except Exception: log.error('Could not read responder key/cert.') return self.fail() # get the certificate status if cert.revoked: status = ocsp.OCSPCertStatus.REVOKED else: status = ocsp.OCSPCertStatus.GOOD now = datetime.utcnow() builder = ocsp.OCSPResponseBuilder() expires = datetime.utcnow() + timedelta(seconds=self.expires) builder = builder.add_response( cert=cert.x509, issuer=ca.x509, algorithm=hashes.SHA1(), cert_status=status, this_update=now, next_update=expires, revocation_time=cert.get_revocation_time(), revocation_reason=cert.get_revocation_reason()).responder_id( ocsp.OCSPResponderEncoding.HASH, responder_cert) # Add the responder cert to the response, necessary because we (so far) always use delegate # certificates builder = builder.certificates([responder_cert]) # Add OCSP nonce if present try: nonce = ocsp_req.extensions.get_extension_for_class(OCSPNonce) builder = builder.add_extension(nonce.value, critical=nonce.critical) except ExtensionNotFound: pass response = builder.sign(responder_key, hashes.SHA256()) return self.http_response(response.public_bytes(Encoding.DER))
break else: print('Wallet or project not found! Please try again.') # Ask for password and convert to bytes password = getpass.getpass('Enter Password to be used for decryption: ') password = bytes(password, 'ascii') # Create and store salt f = open(project_dir/'salt.txt', 'rb') salt = f.readline() f.close() # Derive key and use it to encrypt the phrase kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt, iterations=100000) key = base64.urlsafe_b64encode(kdf.derive(password)) # Read in encrypted seedphrase f = open(project_dir/'encrypted.txt','rb') token = f.readline() f.close() # Create fernet object fern = Fernet(key) # decrypt and print results def yes_or_no(question): while "the answer is invalid": reply = str(input(question+' (y/n): ')).lower().strip() if reply[:1] == 'y':
def sign_message(data, invalid=False): # WARNING: This key is for dev only, not used in production private_key = """ -----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEA4MUnDktq5JQKsxrOFzED71YRp0AZPWqDe0BmKhRz1rE5oKlM 2p9FtRpe+eWuLdRIerRZ/8lqX3hC/HJ0YjzC9iL+YC4SNOecIBw5wW43r1seLfSm YkL2N5lf4R1mVNWjMwjboIKKzDbe9uDy6NCgKwUg1/aK2gD5A3aepkZugVOm+trJ RLoOusCuxSNbHPyWD7g65WUHY2p+i/eU+R230UvLAnBSl5Q+UuaA8ogH8zwAXpHr qrc1rDfSMEM9RBY6FbH9LTHYVNvR9QVihEmaLJ9oIrBNq28kyED0d20gh0n+y1vn yhISNQPtMGVhdX4KTyKD7epGN4msg6KGKm+TuQIDAQABAoIBACIciZLXyz8pYH5S ARjv7WLzMvao+auicJXR7i9Qr0vT1aUWTH2ZUmDrwaI3QzndT6qfmFEDZkta2v+o 9xS5l/T21pgOJeE1jTIqVnGOopDQSUI8MMwU0X0an7xwU8loKr5iB8LSTPI1GZ1q AjNnBgfBXXypA+WV5DSsWeNuKPMjUA8W4S/kFPemeXsstZjowMKTAQVWvGDuXWq6 /XDOYNgbRZ7N6b9C+XVGfD4rTdjycsbZubvJIWfGTc1aEdkf6LnThBxdKs8rnb78 bp3DXjcBbKOQDVBefuTe4mLDHBVxU0x6cNTWFKBdVwnZmDAxauGLgPCa5tZ4Alx6 CsBUUMkCgYEA9MZOM3zaUcp7p2PJa61SznC7ORtc7Q8x371Lgxk0RryzEMwY4juy ohft1Ni+YLwhLsMM2i068uLikVI+tz0fv7WzRIFq4GOSGTzIBQowjF2YL/EDWuh6 YnNQhZsIHXxOzIiM4snuOvT+E0SLJIKoYRvRSk95Hxux8qWKMQpK9/8CgYEA6xP9 rNK0AtpAXd9QInXvO2mPa7jYIfTQNsspQobO41leQWQ4b1nAivqS6abMLNh7Ccm7 7cbsF4WLQ8JGOuPcbxutcHNTD7d3ncf8xUBkNl0d4QQz5qdEDd3F+5xec9EinAB1 03Ij5/gOuIhuperqym4yvNVfgpnxIoKBXhK7NEcCgYBDWgGQl003bkDCGWoF7+Y2 GbzahNX4ANNXXi3V/+xrfmbDO3WpYoXPpkfx5kXUNk/nHxJ9Qi7TQGzZUckiAHao +KVAN2AiKCO+QARFpr0fEm3a2zVyIT/zsQk6CiOcgWTpULV7fdbIcDstMBIdVLpi JhZbnSyVy7gWLUiuH8frHwKBgQC9gJULn6NrdUNUKTQxQ38CFvt97DmXTgIXWbk+ Huxiy+U2s7Lm2KRlpM+PuV14fV7aKhzr9mLWJ1p32gHBcXR+wQIU13LLBaxQrinv XRQr2u6+OSQZuRccUn5KceiWVq4esiRJuwaE9ivvyFPiPrjdTO5r2VowLyb7Gddt 3Y25+wKBgC7ILXVv05sbEDXszauV4wMqplFre28h8m4oL/ALI7thH1T3LBe9IUBq 4jiC+7C510ZIxRN8YaNSXKT3U9hmbpbtm5PgpBLIc/wqD/Yu6u/0yvsd8Ue8O5Co h4kCbzDGKP8Jy0CMwq7srJqFWwTX7ab4Ga0srpG3JfHR11LgwUuG -----END RSA PRIVATE KEY-----""" invalid_priv_key = """-----BEGIN PRIVATE KEY----- MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAzmWPf8G41TOnWk/R +tw5QO6KHCEV0RhpfvdX5BOf/yWrqzpbkDZtkxTPMAfHmyQcKNc3i74b26RDIg+A EOqiRwIDAQABAkALkhH7XYbZHO4y1+qzn4juJPFFJm2srSus3Hzm4lrD2OUAhOaD UHB6d4GBsERDjQMd1mcB+PBoiaeT8ba+06XRAiEA7EFYBBQJI9ZTuPfOjwm9i4l2 lUHacUaGcDfJE8m1+UsCIQDfpWWLc1S9nqdyZCMRAMw/4BKskzH1dDlE8AnBG/o5 dQIhAKmAyFFEvroDj9XplT1y05dFbNrxgHQ9ET96Br43vmO5AiAqDkw+IP36em86 j6IYfHHsQRLB6Rwn8Cck047CBaTUUQIhALQ3dUZNfejgWkDzaNGr1EzIOazP+Y2f Nuada5lLL1eq -----END PRIVATE KEY-----""" json_bytes = bytes(json.dumps(data), 'utf-8') if invalid: key = invalid_priv_key.encode('utf8') else: key = private_key.encode('utf8') priv_key = serialization.load_pem_private_key( key, password=None, backend=default_backend(), ) signature = priv_key.sign( json_bytes, padding.PKCS1v15(), hashes.SHA256(), ) encoded_signature = base64.b64encode(signature) response = encoded_signature + b'^' + json_bytes return response.decode('utf-8')