class TestSHA512256(object):
    test_sha512_256 = generate_hash_test(
        load_hash_vectors,
        os.path.join("hashes", "SHA2"),
        ["SHA512_256LongMsg.rsp", "SHA512_256ShortMsg.rsp"],
        hashes.SHA512_256(),
    )
Пример #2
0
 def test_unsupported_hash_alg(self, backend):
     cert, key = _load_cert_key()
     with pytest.raises(TypeError):
         pkcs7.PKCS7SignatureBuilder().add_signer(
             cert,
             key,
             hashes.SHA512_256()  # type: ignore[arg-type]
         )
Пример #3
0
 def generate_key(self, password: Text, write_to_file: bool = False) -> bytes:
     byte_password = password.encode()  # Convert to type bytes
     salt = os.urandom(16)
     kdf = PBKDF2HMAC(
         algorithm=hashes.SHA512_256(), length=32, salt=salt, iterations=100000, backend=default_backend()
     )
     key = base64.urlsafe_b64encode(kdf.derive(byte_password))  # Can only use kdf once
     if write_to_file:
         self._loader.put_file(key, "wb")
     return key
Пример #4
0
 def address(self):
     """Return the multisig account address."""
     msig_bytes = (bytes(constants.msig_addr_prefix, "utf-8") +
                   bytes([self.version]) + bytes([self.threshold]))
     for s in self.subsigs:
         msig_bytes += s.public_key
     hash = hashes.Hash(hashes.SHA512_256(), default_backend())
     hash.update(msig_bytes)
     addr = hash.finalize()
     return encoding.encode_address(addr)
Пример #5
0
def get_kdf():
    """Gets a KDF object to perform cryptography with.

    Returns:
        PBKDF2HMAC: the KDF to perform encryption/decryption with
    """
    return PBKDF2HMAC(algorithm=hashes.SHA512_256(),
                      length=32,
                      salt=get_salt(),
                      iterations=140000,
                      backend=default_backend())
def print_metadata(filename):
    """Prints metadata associated with this run of the validator."""
    print("Validator version: {}".format(version.__version__))

    blocksize = 65536
    digest = hashes.Hash(hashes.SHA512_256(), backend=default_backend())
    with open(filename, "rb") as f:
        for block in iter(lambda: f.read(blocksize), b""):
            digest.update(block)
    print("SHA-512/256 checksum: 0x{:x}".format(
        int(codecs.encode(digest.finalize(), "hex"), 16)))
Пример #7
0
def checksum(data):
    """
    Compute the checksum of arbitrary binary input.

    Args:
        data (bytes): data as bytes

    Returns:
        bytes: checksum of the data
    """
    chksum = hashes.Hash(hashes.SHA512_256(), default_backend())
    chksum.update(data)
    return chksum.finalize()
Пример #8
0
    def get_txid(self):
        """
        Get a transaction's ID.

        Returns:
            str: transaction ID
        """
        txn = encoding.msgpack_encode(self)
        to_sign = constants.txid_prefix + base64.b64decode(bytes(txn, "utf-8"))
        txidbytes = hashes.Hash(hashes.SHA512_256(), default_backend())
        txidbytes.update(to_sign)
        txid = txidbytes.finalize()
        txid = base64.b32encode(txid).decode()
        return encoding._undo_padding(txid)
Пример #9
0
    def create_digest(message, digst_algorithm):
        hash_algorithm = None

        if digst_algorithm == "SHA512":
            hash_algorithm = hashes.SHA512_256()
        elif digst_algorithm == "BLAKE2":
            hash_algorithm = hashes.BLAKE2b(64)
        else:
            raise Exception("Digest Algorithm name not found!")

        digest = hashes.Hash(hash_algorithm)
        digest.update(message)

        return digest.finalize()
Пример #10
0
def _checksum(addr):
    """
    Compute the checksum of size checkSumLenBytes for the address.

    Args:
        addr (bytes): address in bytes

    Returns:
        bytes: checksum of the address
    """
    hash = hashes.Hash(hashes.SHA512_256(), default_backend())
    hash.update(addr)
    chksum = hash.finalize()[-constants.check_sum_len_bytes:]
    return chksum
    async def SHA512_256(message):

        message = message.encode()

        kdf = PBKDF2HMAC(
            algorithm=hashes.SHA512_256(),
            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)
Пример #12
0
def _checksum(data):
    """
    Compute the mnemonic checksum.

    Args:
        data (bytes): data to compute checksum of

    Returns:
        bytes: checksum
    """
    hash = hashes.Hash(hashes.SHA512_256(), default_backend())
    hash.update(data)
    chksum = hash.finalize()
    temp = chksum[0:2]
    nums = _to_11_bit(temp)
    return _apply_words(nums)[0]
Пример #13
0
    def _get_hasher(T: int):
        hash_algo = None
        if T == Dss1Verifier.TRAILER_IMPLICIT or T == Dss1Verifier.TRAILER_SHA1:
            hash_algo = hashes.SHA1()
        elif T == Dss1Verifier.TRAILER_SHA224:
            hash_algo = hashes.SHA224()
        elif T == Dss1Verifier.TRAILER_SHA256:
            hash_algo = hashes.SHA256()
        elif T == Dss1Verifier.TRAILER_SHA384:
            hash_algo = hashes.SHA384()
        elif T == Dss1Verifier.TRAILER_SHA512:
            hash_algo = hashes.SHA512()
        elif T == Dss1Verifier.TRAILER_SHA512_224:
            hash_algo = hashes.SHA512_224()
        elif T == Dss1Verifier.TRAILER_SHA512_256:
            hash_algo = hashes.SHA512_256()

        if hash_algo is None:
            raise Dss1VerifierError("Unrecognized hash algorithm in signature")
        return hashes.Hash(hash_algo, backend=default_backend())
Пример #14
0
def get_key(password):
    digest = hashes.Hash(hashes.SHA512_256(), backend=default_backend())
    digest.update(password)
    return urlsafe_b64encode(digest.finalize())
Пример #15
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())
Пример #16
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':
Пример #17
0
)
@pytest.mark.requires_backend_interface(interface=HashBackend)
class TestSHA512224(object):
    test_sha512_224 = generate_hash_test(
        load_hash_vectors,
        os.path.join("hashes", "SHA2"),
        [
            "SHA512_224LongMsg.rsp",
            "SHA512_224ShortMsg.rsp",
        ],
        hashes.SHA512_224(),
    )


@pytest.mark.supported(
    only_if=lambda backend: backend.hash_supported(hashes.SHA512_256()),
    skip_message="Does not support SHA512/256",
)
@pytest.mark.requires_backend_interface(interface=HashBackend)
class TestSHA512256(object):
    test_sha512_256 = generate_hash_test(
        load_hash_vectors,
        os.path.join("hashes", "SHA2"),
        [
            "SHA512_256LongMsg.rsp",
            "SHA512_256ShortMsg.rsp",
        ],
        hashes.SHA512_256(),
    )

Пример #18
0
 def test_unsupported_hash_alg(self):
     cert, key = _load_cert_key()
     with pytest.raises(TypeError):
         smime.SMIMESignatureBuilder().add_signer(cert, key,
                                                  hashes.SHA512_256())