예제 #1
0
    def test_invalid_digest_size(self, backend):
        with pytest.raises(ValueError):
            hashes.BLAKE2s(digest_size=33)

        with pytest.raises(ValueError):
            hashes.BLAKE2s(digest_size=0)

        with pytest.raises(ValueError):
            hashes.BLAKE2s(digest_size=-1)
예제 #2
0
def hash(sorceFile_name, hashFunction_name):
    #define hash funcition
    if hashFunction_name == "MD5":
        hashFunction = hashes.MD5()
    elif hashFunction_name == "SHA-384":
        hashFunction = hashes.SHA384()
    elif hashFunction_name == "SHA-512":
        hashFunction = hashes.SHA512()
    elif hashFunction_name == "BLAKE-2":
        hashFunction = hashes.BLAKE2s(32)
    else:
        hashFunction = hashes.SHA256()
    #block length
    blockLength = 32
    #open sorce file
    sorceFile = open(sorceFile_name, 'r')
    #messa digest init
    digest = hashes.Hash(hashFunction)
    block = "."
    while block != "":
        #read block
        block = sorceFile.read(blockLength)
        #update digest
        digest.update(block.encode())
    #get hash
    h = digest.finalize()
    #close file
    sorceFile.close()

    return h
    def __init__(self, app, pipeline, id=None, config=None):
        super().__init__(app, pipeline, id, config)

        self.Backend = default_backend()

        algorithm = self.Config['algorithm'].upper()

        if algorithm == "SHA224":
            self.Algorithm = hashes.SHA224()
        elif algorithm == "SHA256":
            self.Algorithm = hashes.SHA256()
        elif algorithm == "SHA384":
            self.Algorithm = hashes.SHA384()
        elif algorithm == "SHA512":
            self.Algorithm = hashes.SHA512()
        elif algorithm == "SHA1":
            self.Algorithm = hashes.SHA1()
        elif algorithm == "MD5":
            self.Algorithm = hashes.MD5()
        elif algorithm == "BLAKE2B":
            digest_size = int(self.Config['digest_size'])
            self.Algorithm = hashes.BLAKE2b(digest_size)
        elif algorithm == "BLAKE2S":
            digest_size = int(self.Config['digest_size'])
            self.Algorithm = hashes.BLAKE2s(digest_size)
        else:
            L.error("Unknown hashing algorithm '{}'".format(
                self.Config['algorithm']))
            raise RuntimeError("Unknown hashing algorithm '{}'".format(
                self.Config['algorithm']))
class TestBLAKE2s256(object):
    test_b2s = generate_hash_test(
        load_hash_vectors,
        os.path.join("hashes", "blake2"),
        ["blake2s.txt"],
        hashes.BLAKE2s(digest_size=32),
    )
 def test_blake2s(self, backend):
     h = hmac.HMAC(b"0" * 32, hashes.BLAKE2s(digest_size=32), backend)
     h.update(b"test")
     digest = h.finalize()
     assert digest == binascii.unhexlify(
         b"51477cc5bdf1faf952cf97bb934ee936de1f4d5d7448a84eeb6f98d23b392166"
     )
예제 #6
0
def dechachacry(data, salt, nonce):
    keyraw = salt + bytes(getpass(), "UTF-8")
    key = hashes.Hash(hashes.BLAKE2s(32), backend=default_backend())
    key.update(keyraw)
    key = key.finalize()
    algorithm = algorithms.ChaCha20(key, nonce)
    cipher = Cipher(algorithm, mode=None, backend=default_backend())
    decrypt = cipher.decryptor()
    return decrypt.update(data)
    def issueCreate(self):
        self.enable_help = False

        tipo = "create"

        # client cannot create account without citizen card
        assert self.cc.citizen_card_detected() 

        self.cc.save_certificates(self.id) # saves the citizen card certicates

        attribs = self.cc.get_cert_attributes()
        attributes = attribs[0]

        log(logging.DEBUG, "%s" % json.dumps(tipo))

        try:
            for file in glob.glob('client_certificates/'+str(self.id)+'/EC de Autenticação do Cartão de Cidadão*.cer'):
                spt = file.split('/')
                cert_name = spt[-1]
            
            #Linux & Mac   
            cert = open("client_certificates/"+str(self.id)+"/"+cert_name, "rb").read()
            #Windows
            #cert = open("client_certificates\\"+cert_name, "rb").read()
            certificate = crypto.load_certificate(crypto.FILETYPE_ASN1, cert)
            
            #self.uuid = int(input("UUID: "))
            self.uuid = int(self.cc.get_digest_pub_key(certificate))
            log(logging.DEBUG, "%s" % json.dumps(self.uuid))

        except ValueError:
            log(logging.ERROR,"USER UNIVERSAL ID MUST BE A INTEGER")
            log(logging.ERROR,"USER UNIVERSAL ID NOT VALID")
            return None

        digest = hashes.Hash(hashes.BLAKE2s(32), backend = default_backend())
        digest.update(getpass.getpass("Password: "******"_"+str(password)

        signature = self.cc.sign(to_sign).decode() # bytes

        # Generate a random number for the CTR mode
        ctr = counterMode()

        # Cipher the message with the session key
        msg = AES_encrypt(self.client_session_key, ctr, json.dumps({"type": tipo, "uuid":self.uuid, 
            "pass": base64.b64encode(password).decode('utf-8'), 
            "signature": signature, 
            "to_sign": to_sign, 
            "cert_attributes": attributes})+TERMINATOR)

        self.socket.send(base64.b64encode(msg)+"\n".encode('utf-8')+base64.b64encode(ctr))
예제 #8
0
def enchachacry(data):
    nonce = bytes(token_hex(8), "UTF-8")
    salt = bytes(token_hex(8), "UTF-8")
    keyraw = salt + bytes(getpass(), "UTF-8")
    key = hashes.Hash(hashes.BLAKE2s(32), backend=default_backend())
    key.update(keyraw)
    key = key.finalize()
    algorithm = algorithms.ChaCha20(key, nonce)
    cipher = Cipher(algorithm, mode=None, backend=default_backend())
    marker = bytes(
        b"\x8c\x14\xf6t\xea\xd5\xe3\x88Z\xa8~\xceE\x02w\\\xf4/w\xfa\xc6\xc5g}")
    encrypt = cipher.encryptor()
    return (marker + salt + nonce + encrypt.update(data))
예제 #9
0
 def __init__(self):
     a = str(time())
     b = str(time())
     c = str(time())
     nonce = bytes((a[len(a) - 5:] + b[len(b) - 5:] + c[len(c) - 6:]),
                   "UTF-8")
     key = urandom(32)
     hasher = hashes.Hash(hashes.BLAKE2s(32), backend=default_backend())
     hasher.update(key)
     key = hasher.finalize()
     algorithm = algorithms.ChaCha20(key, nonce)
     cipher = Cipher(algorithm, mode=None, backend=default_backend())
     self.encryptor = cipher.encryptor()
예제 #10
0
def main():
    # Derive a secret key from 3 secrets generated from at least 2 keys.
    backend = default_backend()
    hkdf = HKDF(
        algorithm=hashes.BLAKE2s(32),
        length=32,
        salt=public_bytes(ephemeral_key),
        info=b'MofN-Encryption-demo',
        backend=backend
    )
    key = hkdf.derive(ephemeral_alice_joe + b'\x01' +
                      ephemeral_alice_bob + b'\x02' + ephemeral_bob_joe)
    print(base64.b64encode(key))
예제 #11
0
class TestBLAKE2s(object):
    test_blake2s = generate_base_hash_test(
        hashes.BLAKE2s(digest_size=32), digest_size=32,
    )

    def test_invalid_digest_size(self, backend):
        with pytest.raises(ValueError):
            hashes.BLAKE2s(digest_size=33)

        with pytest.raises(ValueError):
            hashes.BLAKE2s(digest_size=0)

        with pytest.raises(ValueError):
            hashes.BLAKE2s(digest_size=-1)
예제 #12
0
파일: rsa.py 프로젝트: juanlessa/message_py
def rsa_decryption(ciphertext, private_key, hashFunction_name=None):
    #define hash funcition
    if hashFunction_name == "SHA-384":
        hashFunction = hashes.SHA384()
    elif hashFunction_name == "SHA-512":
        hashFunction = hashes.SHA512()
    elif hashFunction_name == "BLAKE-2":
        hashFunction = hashes.BLAKE2s(32)
    else:
        hashFunction = hashes.SHA256()
    #decryption
    plaintext = private_key.decrypt(
        ciphertext,
        padding.OAEP(mgf=padding.MGF1(algorithm=hashFunction),
                     algorithm=hashFunction,
                     label=None))
    #decode message
    plaintext = plaintext.decode()
    return plaintext
예제 #13
0
def hash(sorceFile_name: str, hashFunction_name: str) -> bytes:
    """Function that read a file and generate the Hash according chosen hash function

    Args:
        sorceFile_name (str): source file name to generate hash
        hashFunction_name (str): hash function to be used ("SHA-256",
         "SHA-384", "SHA-512", "MD5", "BLAKE-2")

    Returns:
        bytes: generated hash
    """
    # define hash funcition
    if hashFunction_name == "MD5":
        hashFunction = hashes.MD5()
    elif hashFunction_name == "SHA-384":
        hashFunction = hashes.SHA384()
    elif hashFunction_name == "SHA-512":
        hashFunction = hashes.SHA512()
    elif hashFunction_name == "BLAKE-2":
        hashFunction = hashes.BLAKE2s(32)
    else:
        hashFunction = hashes.SHA256()
    # block length
    blockLength = 32
    # open sorce file
    sorceFile = open(sorceFile_name, 'r')
    # messa digest init
    digest = hashes.Hash(hashFunction)
    block = "."
    while block != "":
        # read block
        block = sorceFile.read(blockLength)
        # update digest
        digest.update(block.encode())
    # get hash
    h = digest.finalize()
    # close file
    sorceFile.close()

    return h
예제 #14
0
        lambda params: cr_hashes.MD5(),
        hashes.HashAlgorithmId.SHA1:
        lambda params: cr_hashes.SHA1(),
        hashes.HashAlgorithmId.SHA2_224:
        lambda params: cr_hashes.SHA224(),
        hashes.HashAlgorithmId.SHA2_256:
        lambda params: cr_hashes.SHA256(),
        hashes.HashAlgorithmId.SHA2_384:
        lambda params: cr_hashes.SHA384(),
        hashes.HashAlgorithmId.SHA2_512:
        lambda params: cr_hashes.SHA512(),
        hashes.HashAlgorithmId.BLAKE2B:
        lambda params: cr_hashes.BLAKE2b(
            cast(hashes.Blake2Params, params).length),
        hashes.HashAlgorithmId.BLAKE2S:
        lambda params: cr_hashes.BLAKE2s(
            cast(hashes.Blake2Params, params).length),
    }


def create_hash(hash_alg: hashes.HashAlgorithm) -> cr_hashes.HashAlgorithm:
    try:
        func = _hash_factories[hash_alg.algorithm_id]
    except KeyError as ex:
        raise NotImplementedError(
            f"Hash {hash_alg.algorithm_id} not supported") from ex

    return func(hash_alg.parameters)


@dataclass(eq=False)
class CryptographyHash(hashes.HashFunction):
예제 #15
0
    )

    def test_invalid_digest_size(self, backend):
        with pytest.raises(ValueError):
            hashes.BLAKE2b(digest_size=65)

        with pytest.raises(ValueError):
            hashes.BLAKE2b(digest_size=0)

        with pytest.raises(ValueError):
            hashes.BLAKE2b(digest_size=-1)


@pytest.mark.supported(
    only_if=lambda backend: backend.hash_supported(
        hashes.BLAKE2s(digest_size=32)),
    skip_message="Does not support BLAKE2s",
)
class TestBLAKE2s(object):
    test_blake2s = generate_base_hash_test(
        hashes.BLAKE2s(digest_size=32),
        digest_size=32,
    )

    def test_invalid_digest_size(self, backend):
        with pytest.raises(ValueError):
            hashes.BLAKE2s(digest_size=33)

        with pytest.raises(ValueError):
            hashes.BLAKE2s(digest_size=0)
예제 #16
0
 def hmac_hash(self, key, data):
     hmac = HMAC(key=key,
                 algorithm=hashes.BLAKE2s(32),
                 backend=default_backend())
     hmac.update(data=data)
     return hmac.finalize()
예제 #17
0
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"))
예제 #18
0
    def issueLogin(self):
        tipo = "login"

        try:
            self.uuid = int(input("User Universal Identification: "))
        except:
            log(logging.ERROR, "User Universal Identification must be an integer")
            return None

        digest = hashes.Hash(hashes.BLAKE2s(32), backend = default_backend())
        digest.update(getpass.getpass("Password: "******"_"+str(password)
        signature = self.cc.sign(to_sign).decode() # bytes

        # Generate a random number for the CTR mode
        ctr = counterMode()

        # Cipher the message with the session key
        msg = AES_encrypt(self.client_session_key, ctr, json.dumps({"type": tipo, "uuid": self.uuid, 
            "pass": base64.b64encode(password).decode('utf-8'), 
            "signature":signature, 
            "to_sign": to_sign})+TERMINATOR)
    	
        # Send the login parameters
        socket.send(base64.b64encode(msg)+"\n".encode('utf-8')+base64.b64encode(ctr))
    	
        # Receive response
        data = self.socket.recv(BUFSIZE)
        data = data.split(b"\n")
        msg = base64.b64decode(data[0])
        ctr = base64.b64decode(data[1])
        data = AES_decrypt(self.client_session_key, ctr, msg)
        parsed = json.loads(data.decode('utf-8'))

        try:
            pwd = base64.b64decode(parsed["pass"])
            #Checks if the password is correct
            if password == pwd:
                self.logged_in = True
                self.id = parsed["id"]
                int(self.id)
                log(logging.DEBUG, "Login Successful")
                log(logging.DEBUG, "USER ID: {}".format(self.id))
                #Updates the public key in the server datatabase
                pK = self.public_key.public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo)
                # Generate a random number for the CTR mode
                ctr = counterMode()
                # Cipher the message with the session key
                msg = AES_encrypt(self.client_session_key, ctr, json.dumps({"type": "update", "id": self.id, "public_key": pK.decode('utf-8'), 
                    "signature": base64.b64encode(sign_msg(self.private_key, pK)).decode('utf-8')})+TERMINATOR)
                # Send the update parameters
                socket.send(base64.b64encode(msg)+"\n".encode('utf-8')+base64.b64encode(ctr))
                # Update dirname to save messages
                self.dirname = os.path.join(self.dirname,str(self.uuid))
            else:
                self.logged_in = False
                log(logging.ERROR, "ERROR: password doesn't match")
        except:
            self.logged_in = False
            log(logging.ERROR, "ERROR: {}".format(parsed['error']))
예제 #19
0
    "sha3_384":
    h.SHA3_384,
    "sha3_512":
    h.SHA3_512,
    "sha512_224":
    h.SHA512_224,
    "sha512_256":
    h.SHA512_256,
    "shake128":
    h.SHAKE128,
    "shake256":
    h.SHAKE256,
    "blake2b":
    lambda digest_size=None: h.BLAKE2b(digest_size or 64),
    "blake2s":
    lambda digest_size=None: h.BLAKE2s(digest_size or 32),
})

VAR_DIGEST_SIZE = frozenset((
    "shake128",
    "shake256",
    "blake2b",
    "blake2s",
))

XOFS = frozenset((
    "shake128",
    "shake256",
))

# the ASN.1 Object IDs
예제 #20
0
 def hash(self, data):
     digest = hashes.Hash(hashes.BLAKE2s(32), backend=default_backend())
     digest.update(data)
     return digest.finalize()
예제 #21
0
 def _hash_blake2s(self, data):
     digest = hashes.Hash(hashes.BLAKE2s(digest_size=self.hashlen), backend)
     digest.update(data)
     return digest.finalize()