コード例 #1
0
class TestSHA3384(object):
    test_sha3_384 = generate_hash_test(
        load_hash_vectors,
        os.path.join("hashes", "SHA3"),
        ["SHA3_384LongMsg.rsp", "SHA3_384ShortMsg.rsp"],
        hashes.SHA3_384(),
    )
コード例 #2
0
def deriveKey(shared_secret, hashAlg, BlukEnc):

    if hashAlg == "sha256":
        hashAlg = hashes.SHA256()

    else:
        hashAlg = hashes.SHA3_384()

    salt = bytes(bytearray(shared_secret)[0:16])
    key = HKDF(algorithm=hashAlg,
               length=24,
               salt=salt,
               info=b'handshake data',
               backend=default_backend()).derive(shared_secret)

    iv = bytearray(shared_secret)[0:16]

    if BlukEnc == "AES-256-CBC":
        BlukEnc = modes.CBC(iv)
    else:
        BlukEnc = modes.OFB(iv)

    cipher = Cipher(algorithms.AES(key), BlukEnc, default_backend())
    print("Symmetric key has been generated successfully...")
    return cipher
コード例 #3
0
def Verification(client_pub_key,signature,message,hashAlg):

    try:

        if hashAlg == "sha256":
            hashAlg = hashes.SHA256()

        else:
            hashAlg = hashes.SHA3_384()

        client_pub_key.verify(
        signature,
        message,
        pad.PSS(
            mgf=pad.MGF1(hashAlg),
            salt_length=pad.PSS.MAX_LENGTH
            ),
        hashAlg
        )

        print(bcolors.succ + "Signature has been verified successfully" + bcolors.ENDC)
        return True
    except InvalidSignature:
        print(bcolors.FAIL + "invalidSignature" + bcolors.ENDC)
        return False
コード例 #4
0
ファイル: sha3.py プロジェクト: OverwatchHeir/CryptOn
 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()
コード例 #5
0
def Signing_Data(private_key, message, hashAlg):

    if hashAlg == "sha256":
        hashAlg = hashes.SHA256()

    else:
        hashAlg = hashes.SHA3_384()

    signature = private_key.sign(
        message, pad.PSS(mgf=pad.MGF1(hashAlg),
                         salt_length=pad.PSS.MAX_LENGTH), hashAlg)
    print("Message has been signed successfully....")
    return signature
コード例 #6
0
    async def SHA3_384(message):

        message = message.encode()

        kdf = PBKDF2HMAC(
            algorithm=hashes.SHA3_384(),
            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)
コード例 #7
0
ファイル: test_hmac.py プロジェクト: simo5/cryptography
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",
    "hmac_sha512_test.json",
)
コード例 #8
0
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


@wycheproof_tests(
コード例 #9
0
)
@pytest.mark.requires_backend_interface(interface=HashBackend)
class TestSHA3256(object):
    test_sha3_256 = generate_hash_test(
        load_hash_vectors,
        os.path.join("hashes", "SHA3"),
        [
            "SHA3_256LongMsg.rsp",
            "SHA3_256ShortMsg.rsp",
        ],
        hashes.SHA3_256(),
    )


@pytest.mark.supported(
    only_if=lambda backend: backend.hash_supported(hashes.SHA3_384()),
    skip_message="Does not support SHA3_384",
)
@pytest.mark.requires_backend_interface(interface=HashBackend)
class TestSHA3384(object):
    test_sha3_384 = generate_hash_test(
        load_hash_vectors,
        os.path.join("hashes", "SHA3"),
        [
            "SHA3_384LongMsg.rsp",
            "SHA3_384ShortMsg.rsp",
        ],
        hashes.SHA3_384(),
    )

コード例 #10
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"))
コード例 #11
0
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':
コード例 #12
0
ファイル: bloom_filters.py プロジェクト: 0x00C0DE/cs370_proj2
        #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)
        b1_h5_hval = int(b1_h5_hval, 16)
        b1_h5_hval = int(b1_h5_hval) % (len(bit_vect2))

        bit_vect2[b1_h5_hval] = 1

        b1_h6 = hashes.Hash(hashes.SHA3_384(), backend=backend)
        b1_h6.update(TempHash.encode())
        b1_h6_hval = b1_h6.finalize()
        b1_h6_hval = hexlify(b1_h6_hval)
        b1_h6_hval = int(b1_h6_hval, 16)
        b1_h6_hval = int(b1_h6_hval) % (len(bit_vect2))

        bit_vect2[b1_h6_hval] = 1

        b1_h7 = hashes.Hash(hashes.SHA3_512(), backend=backend)
        b1_h7.update(TempHash.encode())
        b1_h7_hval = b1_h7.finalize()
        b1_h7_hval = hexlify(b1_h7_hval)
        b1_h7_hval = int(b1_h7_hval, 16)
        b1_h7_hval = int(b1_h7_hval) % (len(bit_vect2))
コード例 #13
0
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())