Example #1
0
 def test_rsa2048_pkcs1v1_5_sign(self):
     self.rsa_pkcs1v1_5_sign(2048, hashes.SHA256())
     self.rsa_pkcs1v1_5_sign(2048, hashes.SHA384())
     self.rsa_pkcs1v1_5_sign(2048, hashes.SHA512())
Example #2
0
 def _jwa_ES384(self):
     return _raw_ec('P-384', hashes.SHA384())
Example #3
0
    ECDSA_WITH_SHA224 = ObjectIdentifier("1.2.840.10045.4.3.1")
    ECDSA_WITH_SHA256 = ObjectIdentifier("1.2.840.10045.4.3.2")
    ECDSA_WITH_SHA384 = ObjectIdentifier("1.2.840.10045.4.3.3")
    ECDSA_WITH_SHA512 = ObjectIdentifier("1.2.840.10045.4.3.4")
    DSA_WITH_SHA1 = ObjectIdentifier("1.2.840.10040.4.3")
    DSA_WITH_SHA224 = ObjectIdentifier("2.16.840.1.101.3.4.3.1")
    DSA_WITH_SHA256 = ObjectIdentifier("2.16.840.1.101.3.4.3.2")


_SIG_OIDS_TO_HASH = {
    SignatureAlgorithmOID.RSA_WITH_MD5: hashes.MD5(),
    SignatureAlgorithmOID.RSA_WITH_SHA1: hashes.SHA1(),
    SignatureAlgorithmOID._RSA_WITH_SHA1: hashes.SHA1(),
    SignatureAlgorithmOID.RSA_WITH_SHA224: hashes.SHA224(),
    SignatureAlgorithmOID.RSA_WITH_SHA256: hashes.SHA256(),
    SignatureAlgorithmOID.RSA_WITH_SHA384: hashes.SHA384(),
    SignatureAlgorithmOID.RSA_WITH_SHA512: hashes.SHA512(),
    SignatureAlgorithmOID.ECDSA_WITH_SHA1: hashes.SHA1(),
    SignatureAlgorithmOID.ECDSA_WITH_SHA224: hashes.SHA224(),
    SignatureAlgorithmOID.ECDSA_WITH_SHA256: hashes.SHA256(),
    SignatureAlgorithmOID.ECDSA_WITH_SHA384: hashes.SHA384(),
    SignatureAlgorithmOID.ECDSA_WITH_SHA512: hashes.SHA512(),
    SignatureAlgorithmOID.DSA_WITH_SHA1: hashes.SHA1(),
    SignatureAlgorithmOID.DSA_WITH_SHA224: hashes.SHA224(),
    SignatureAlgorithmOID.DSA_WITH_SHA256: hashes.SHA256()
}


class ExtendedKeyUsageOID(object):
    SERVER_AUTH = ObjectIdentifier("1.3.6.1.5.5.7.3.1")
    CLIENT_AUTH = ObjectIdentifier("1.3.6.1.5.5.7.3.2")
Example #4
0
import binascii

import pytest

from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.backends.interfaces import RSABackend
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
Example #5
0
 def _jwa_HS384(self):
     return _raw_hmac(hashes.SHA384())
Example #6
0
             encryption_algorithm=serialization.NoEncryption(),
         )
     if qmsf == 'MD5':
         csr = csr_add_extension.sign(private_key, hashes.MD5(),
                                      default_backend())
     elif qmsf == 'SHA1':
         csr = csr_add_extension.sign(private_key, hashes.SHA1(),
                                      default_backend())
     elif qmsf == 'SHA224':
         csr = csr_add_extension.sign(private_key, hashes.SHA224(),
                                      default_backend())
     elif qmsf == 'SHA256':
         csr = csr_add_extension.sign(private_key, hashes.SHA256(),
                                      default_backend())
     elif qmsf == 'SHA384':
         csr = csr_add_extension.sign(private_key, hashes.SHA384(),
                                      default_backend())
     elif qmsf == 'SHA512':
         csr = csr_add_extension.sign(private_key, hashes.SHA512(),
                                      default_backend())
     else:
         csr = csr_add_extension.sign(private_key, hashes.SHA1(),
                                      default_backend())
     return {
         'error': True,
         'csr': csr.public_bytes(serialization.Encoding.PEM),
         'priv_key': key
     }
 elif mysf == 'DSA':
     private_key = dsa.generate_private_key(key_size=int(myqd),
                                            backend=default_backend())
Example #7
0
try:
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives import hashes
    from cryptography.hazmat.primitives.asymmetric import ec

    from cryptography.hazmat.primitives import serialization

    from cryptography.hazmat.primitives.serialization import load_pem_public_key
    from cryptography.hazmat.primitives.serialization import load_pem_private_key

    from cryptography.exceptions import (InvalidSignature,
                                         UnsupportedAlgorithm)

    _SCHEME_HASHER = {
        'ecdsa-sha2-nistp256': ec.ECDSA(hashes.SHA256()),
        'ecdsa-sha2-nistp384': ec.ECDSA(hashes.SHA384())
    }

except ImportError:
    CRYPTO = False

# Perform object format-checking and add ability to handle/raise exceptions.
from securesystemslib import exceptions
from securesystemslib import formats

_SUPPORTED_ECDSA_SCHEMES = ['ecdsa-sha2-nistp256']

logger = logging.getLogger(__name__)


def generate_public_and_private(scheme='ecdsa-sha2-nistp256'):
Example #8
0
        self._digest = digest
        self._padding = padding or PKCS1v15()

    def verify(self, pubkey, signed_data, signature):
        try:
            pubkey.verify(signature, signed_data, self._padding, self._digest)
        except InvalidSignature:
            return False
        else:
            return True


RSA_VERIFIERS = {
    SIG_RSA_SHA224: RSAVerifier(hashes.SHA224()),
    SIG_RSA_SHA256: RSAVerifier(hashes.SHA256()),
    SIG_RSA_SHA384: RSAVerifier(hashes.SHA384()),
    SIG_RSA_SHA512: RSAVerifier(hashes.SHA512()),
}

RSA_SIGNERS = {
    SIG_RSA_SHA224: RSASigner(hashes.SHA224()),
    SIG_RSA_SHA256: RSASigner(hashes.SHA256()),
    SIG_RSA_SHA384: RSASigner(hashes.SHA384()),
    SIG_RSA_SHA512: RSASigner(hashes.SHA512()),
}


def sign_http_post(xmlstr, key, cert, message=False, assertion=True):
    signer = XMLSigner(
        signature_algorithm='rsa-sha256',
        digest_algorithm='sha256',
Example #9
0
import debtcollector
from oslo_log import log as logging
from oslo_serialization import base64
from oslo_utils import encodeutils

from glance.common import exception
from glance.i18n import _, _LE

LOG = logging.getLogger(__name__)

# Note: This is the signature hash method, which is independent from the
# image data checksum hash method (which is handled elsewhere).
HASH_METHODS = {
    'SHA-224': hashes.SHA224(),
    'SHA-256': hashes.SHA256(),
    'SHA-384': hashes.SHA384(),
    'SHA-512': hashes.SHA512()
}

# Currently supported signature key types
# RSA Options
RSA_PSS = 'RSA-PSS'

# DSA Options
DSA = 'DSA'

# ECC curves -- note that only those with key sizes >=384 are included
# Note also that some of these may not be supported by the cryptography backend
ECC_CURVES = (
    ec.SECT571K1(),
    ec.SECT409K1(),
Example #10
0
class Ps384(RsaSsaPss):
    _name = "PS384"
    _default_hash_algorithm = hashes.SHA384()
Example #11
0
class Rs384(RsaSsaPkcs1v15):
    _name = "RS384"
    _default_hash_algorithm = hashes.SHA384()
Example #12
0
"""

from cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signature
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding

__all__ = ["certificate_signing_methods"]

#pylint: disable=invalid-name,line-too-long

SSH_CERTIFICATE_DIGESTMETHODS = {
    "ssh-dss": hashes.SHA1(),  # per RFC 4253, 6.6. Public Key Algorithms
    "ssh-rsa": hashes.SHA1(),
    "ecdsa-SHA2-nistp256": hashes.SHA256(
    ),  # per RFC 5656 6.2.1. Elliptic Curve Digital Signature Algorithm
    "ecdsa-SHA2-nistp384": hashes.SHA384(
    ),  # per RFC 5656 6.2.1. Elliptic Curve Digital Signature Algorithm
    "ecdsa-SHA2-nistp521": hashes.SHA512(
    ),  # per RFC 5656 6.2.1. Elliptic Curve Digital Signature Algorithm
    "ssh-ed25519":
    hashes.SHA512(),  # per draft-josefsson-eddsa-ed25519-03 5.6. Sign pp 2
}


def sign_rsa(data, private_key):
    """
    Sign the data in accordance with the 'ssh-rsa' key type, per
    RFC 4253, 6.6. Public Key Algorithms
    """
    return {
        "r":
        private_key.sign(data, padding.PKCS1v15(),
Example #13
0
 def test_rsa4096_pkcs1v1_5_sign(self):
     self.rsa_pkcs1v1_5_sign(4096, hashes.SHA256())
     self.rsa_pkcs1v1_5_sign(4096, hashes.SHA384())
     self.rsa_pkcs1v1_5_sign(4096, hashes.SHA512())
Example #14
0
 def test_rsa3072_pkcs1v1_5_sign(self):
     self.rsa_pkcs1v1_5_sign(3072, hashes.SHA256())
     self.rsa_pkcs1v1_5_sign(3072, hashes.SHA384())
     self.rsa_pkcs1v1_5_sign(3072, hashes.SHA512())
Example #15
0
 def __init__(self):
     padfn = padding.PSS(padding.MGF1(hashes.SHA384()),
                         hashes.SHA384.digest_size)
     super(_PS384, self).__init__(padfn, hashes.SHA384())
Example #16
0
    def sign(self, data):
        """
        Sign some data with this key.

        SECSH-TRANS RFC 4253 Section 6.6.

        @type data: L{bytes}
        @param data: The data to sign.

        @rtype: L{bytes}
        @return: A signature for the given data.
        """
        keyType = self.type()
        if keyType == 'RSA':
            sig = self._keyObject.sign(data, padding.PKCS1v15(), hashes.SHA1())
            ret = common.NS(sig)

        elif keyType == 'DSA':
            sig = self._keyObject.sign(data, hashes.SHA1())
            (r, s) = decode_dss_signature(sig)
            # SSH insists that the DSS signature blob be two 160-bit integers
            # concatenated together. The sig[0], [1] numbers from obj.sign
            # are just numbers, and could be any length from 0 to 160 bits.
            # Make sure they are padded out to 160 bits (20 bytes each)
            ret = common.NS(int_to_bytes(r, 20) + int_to_bytes(s, 20))

        elif keyType == 'EC':  # Pragma: no branch
            # Hash size depends on key size
            keySize = self.size()
            if keySize <= 256:
                hashSize = hashes.SHA256()
            elif keySize <= 384:
                hashSize = hashes.SHA384()
            else:
                hashSize = hashes.SHA512()
            signature = self._keyObject.sign(data, ec.ECDSA(hashSize))
            (r, s) = decode_dss_signature(signature)

            rb = int_to_bytes(r)
            sb = int_to_bytes(s)

            # Int_to_bytes returns rb[0] as a str in python2
            # and an as int in python3
            if type(rb[0]) is str:
                rcomp = ord(rb[0])
            else:
                rcomp = rb[0]

            # If the MSB is set, prepend a null byte for correct formatting.
            if rcomp & 0x80:
                rb = b"\x00" + rb

            if type(sb[0]) is str:
                scomp = ord(sb[0])
            else:
                scomp = sb[0]

            if scomp & 0x80:
                sb = b"\x00" + sb

            ret = common.NS(common.NS(rb) + common.NS(sb))
        return common.NS(self.sshType()) + ret
Example #17
0
 def __init__(self):
     super(_A192CbcHs384, self).__init__(hashes.SHA384())
Example #18
0
    def verify(self, signature, data):
        """
        Verify a signature using this key.

        @type signature: L{bytes}
        @param signature: The signature to verify.

        @type data: L{bytes}
        @param data: The signed data.

        @rtype: L{bool}
        @return: C{True} if the signature is valid.
        """
        if len(signature) == 40:
            # DSA key with no padding
            signatureType, signature = b'ssh-dss', common.NS(signature)
        else:
            signatureType, signature = common.getNS(signature)

        if signatureType != self.sshType():
            return False

        keyType = self.type()
        if keyType == 'RSA':
            k = self._keyObject
            if not self.isPublic():
                k = k.public_key()
            args = (
                common.getNS(signature)[0],
                data,
                padding.PKCS1v15(),
                hashes.SHA1(),
            )
        elif keyType == 'DSA':
            concatenatedSignature = common.getNS(signature)[0]
            r = int_from_bytes(concatenatedSignature[:20], 'big')
            s = int_from_bytes(concatenatedSignature[20:], 'big')
            signature = encode_dss_signature(r, s)
            k = self._keyObject
            if not self.isPublic():
                k = k.public_key()
            args = (signature, data, hashes.SHA1())

        elif keyType == 'EC':  # Pragma: no branch
            concatenatedSignature = common.getNS(signature)[0]
            rstr, sstr, rest = common.getNS(concatenatedSignature, 2)
            r = int_from_bytes(rstr, 'big')
            s = int_from_bytes(sstr, 'big')
            signature = encode_dss_signature(r, s)

            k = self._keyObject
            if not self.isPublic():
                k = k.public_key()

            keySize = self.size()
            if keySize <= 256:  # Hash size depends on key size
                hashSize = hashes.SHA256()
            elif keySize <= 384:
                hashSize = hashes.SHA384()
            else:
                hashSize = hashes.SHA512()
            args = (signature, data, ec.ECDSA(hashSize))

        try:
            k.verify(*args)
        except InvalidSignature:
            return False
        else:
            return True
Example #19
0
    ('RSA', 'SHA512'): sha512WithRSAEncryption,
    ('DSA', 'SHA224'): id_dsa_with_sha224,
    ('DSA', 'SHA256'): id_dsa_with_sha256,
}


SIGNING_ALGORITHMS_INV = dict((v, k) for k, v in SIGNING_ALGORITHMS.items())


VERIFIER_CONSTRUCTION = {
    sha224WithRSAEncryption: (lambda key, signature: key.verifier(
        signature, padding.PKCS1v15(), hashes.SHA224())),
    sha256WithRSAEncryption: (lambda key, signature: key.verifier(
        signature, padding.PKCS1v15(), hashes.SHA256())),
    sha384WithRSAEncryption: (lambda key, signature: key.verifier(
        signature, padding.PKCS1v15(), hashes.SHA384())),
    sha512WithRSAEncryption: (lambda key, signature: key.verifier(
        signature, padding.PKCS1v15(), hashes.SHA512())),
    id_dsa_with_sha224: (lambda key, signature: key.verifier(
        signature, hashes.SHA224())),
    id_dsa_with_sha256: (lambda key, signature: key.verifier(
        signature, hashes.SHA256())),
}


ALGORITHM_PARAMETERS = {
    sha224WithRSAEncryption: encoder.encode(asn1_univ.Null()),
    sha256WithRSAEncryption: encoder.encode(asn1_univ.Null()),
    sha384WithRSAEncryption: encoder.encode(asn1_univ.Null()),
    sha512WithRSAEncryption: encoder.encode(asn1_univ.Null()),
    id_dsa_with_sha224: None,
Example #20
0
class TestSHA384(object):
    test_SHA384 = generate_base_hash_test(
        hashes.SHA384(),
        digest_size=48,
        block_size=128,
    )
Example #21
0
class TrustBasics:
    """Anything shared between the main code and the (keygen/signing) scripts which does not need state.

    See 'Trust' (below) and the 'createkeypair.py', 'signfile.py' and 'signfolder.py' scripts in the 'scripts' folder.
    """

    # Considered SHA256 at first, but this is reportedly robust against something called 'length extension attacks'.
    __hash_algorithm = hashes.SHA384()

    # For (in) directories (plugins for example):
    __signatures_relative_filename = "signature.json"
    __root_signatures_category = "root_signatures"

    # For(/next to) single files:
    __signature_filename_extension = ".signature"
    __root_signature_entry = "root_signature"

    @staticmethod
    def defaultViolationHandler(message: str) -> None:
        """This violationHandler is called after any other handlers"""

        Logger.logException("e", message)
        raise TrustException()

    @classmethod
    def getHashAlgorithm(cls):
        """To ensure the same hash-algorithm is used by every part of this code.

        :return: The hash-algorithm used for the entire 'suite'.
        """

        return cls.__hash_algorithm

    @classmethod
    def getSignaturesLocalFilename(cls) -> str:
        """'Signed folder' scenario: Get the filename the signature file in a folder has.

        :return: The filename of the signatures file (not the path).
        """

        return cls.__signatures_relative_filename

    @classmethod
    def getRootSignatureCategory(cls) -> str:
        """'Signed folder' scenario: In anticipation of other keys, put the 'master' signature into this category.

        :return: The json 'name' for the main signatures category.
        """

        return cls.__root_signatures_category

    @classmethod
    def getSignaturePathForFile(cls, filename: str) -> str:
        """'Single signed file' scenario: Get the name of the signature-file that should be located next to the file.

        :param filename: The file that has (or needs to be) signed.
        :return: The path of the signature-file of this file.
        """

        return os.path.join(
            os.path.dirname(filename),
            os.path.basename(filename).split(".")[0] +
            cls.__signature_filename_extension)

    @classmethod
    def getRootSignatureEntry(cls) -> str:
        """'Single signed file' scenario: In anticipation of other keys, put the 'master' signature into this entry.

        :return: The json 'name' for the main signature.
        """

        return cls.__root_signature_entry

    @classmethod
    def getFilePathInfo(cls, base_folder_path: str, current_full_path: str,
                        local_filename: str) -> Tuple[str, str]:
        """'Signed folder' scenario: When walking over directory, it's convenient to have the full path on one hand,
        and the 'name' of the file in the signature json file just below the signed directory on the other.

        :param base_folder_path: The signed folder(name), where the signature file resides.
        :param current_full_path: The full path to the current folder.
        :param local_filename: The local filename of the current file.
        :return: A tuple with the full path to the file on disk and the 'signed-folder-local' path of that same file.
        """

        name_on_disk = os.path.join(current_full_path, local_filename)
        name_in_data = name_on_disk.replace(base_folder_path,
                                            "").replace("\\", "/")
        return name_on_disk, name_in_data if not name_in_data.startswith(
            "/") else name_in_data[1:]

    @classmethod
    def getFileHash(cls, filename: str) -> Optional[str]:
        """Gets the hash for the provided file.

        :param filename: The filename of the file to be hashed.
        :return: The hash of the file.
        """

        hasher = hashes.Hash(cls.__hash_algorithm, backend=default_backend())
        try:
            with open(filename, "rb") as file:
                hasher.update(file.read())
                return base64.b64encode(hasher.finalize()).decode("utf-8")
        except:  # Yes, we  do really want this on _every_ exception that might occur.
            Logger.logException(
                "e", "Couldn't read '{0}' for plain hash generation.".format(
                    filename))
        return None

    @classmethod
    def getFileSignature(cls, filename: str,
                         private_key: RSAPrivateKey) -> Optional[str]:
        """Creates the signature for the (hash of the) provided file, given a private key.

        :param filename: The file to be signed.
        :param private_key: The private key used for signing.
        :return: The signature if successful, 'None' otherwise.
        """

        file_hash = cls.getFileHash(filename)
        if file_hash is None:
            return None
        try:
            file_hash_bytes = base64.b64decode(file_hash)
            signature_bytes = private_key.sign(
                file_hash_bytes,
                padding.PSS(mgf=padding.MGF1(cls.__hash_algorithm),
                            salt_length=padding.PSS.MAX_LENGTH),
                Prehashed(cls.__hash_algorithm))
            return base64.b64encode(signature_bytes).decode("utf-8")
        except:  # Yes, we  do really want this on _every_ exception that might occur.
            Logger.logException(
                "e", "Couldn't sign '{0}', no signature generated.".format(
                    filename))
        return None

    @staticmethod
    def generateNewKeyPair(
    ) -> Tuple[RSAPrivateKeyWithSerialization, RSAPublicKey]:
        """Create a new private-public key-pair.

        :return: A tulple of private-key/public key.
        """

        private_key = rsa.generate_private_key(public_exponent=65537,
                                               key_size=4096,
                                               backend=default_backend())
        return private_key, private_key.public_key()

    @staticmethod
    def loadPrivateKey(
            private_filename: str,
            optional_password: Optional[str]) -> Optional[RSAPrivateKey]:
        """Load a private key from a file.

        :param private_filename: The filename of the file containing the private key.
        :param optional_password: The key can be signed with a password as well (or not).
        :return: The private key contained in the file.
        """

        try:
            password_bytes = None if optional_password is None else optional_password.encode(
            )
            with open(private_filename, "rb") as file:
                private_key = load_pem_private_key(file.read(),
                                                   backend=default_backend(),
                                                   password=password_bytes)
                return private_key
        except:  # Yes, we  do really want this on _every_ exception that might occur.
            Logger.logException("e", "Couldn't load private-key.")
        return None

    @staticmethod
    def saveKeyPair(private_key: "RSAPrivateKeyWithSerialization",
                    private_path: str,
                    public_path: str,
                    optional_password: Optional[str] = None) -> bool:
        """Save a key-pair to two distinct files.

        :param private_key: The private key to save. The public one will be generated from it.
        :param private_path: Path to the filename where the private key will be saved.
        :param public_path: Path to the filename where the public key will be saved.
        :param optional_password: The private key can be signed with a password as well (or not).
        :return: True on success.
        """

        try:
            encrypt_method = serialization.NoEncryption()  # type: ignore
            if optional_password is not None:
                encrypt_method = serialization.BestAvailableEncryption(
                    optional_password.encode())  # type: ignore
            private_pem = private_key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.PKCS8,
                encryption_algorithm=encrypt_method)
            with open(private_path, "wb") as private_file:
                private_file.write(private_pem)

            public_pem = private_key.public_key().public_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PublicFormat.PKCS1)
            with open(public_path, "wb") as public_file:
                public_file.write(public_pem)

            Logger.log(
                "i", "Private/public key-pair saved to '{0}','{1}'.".format(
                    private_path, public_path))
            return True

        except:  # Yes, we  do really want this on _every_ exception that might occur.
            Logger.logException(
                "e", "Save private/public key to '{0}','{1}' failed.".format(
                    private_path, public_path))
        return False

    @staticmethod
    def removeCached(path: str) -> bool:
        try:
            cache_folders_to_empty = []  # List[str]
            for root, dirnames, filenames in os.walk(path, followlinks=True):
                for dirname in dirnames:
                    if dirname == "__pycache__":
                        cache_folders_to_empty.append(
                            os.path.join(root, dirname))
            for cache_folder in cache_folders_to_empty:
                for root, dirnames, filenames in os.walk(cache_folder,
                                                         followlinks=True):
                    for filename in filenames:
                        os.remove(os.path.join(root, filename))
            return True
        except:  # Yes, we  do really want this on _every_ exception that might occur.
            Logger.logException(
                "e",
                "Removal of pycache for unbundled path '{0}' failed.".format(
                    path))
        return False
Example #22
0
def generate_web_server_certificate(intermediary_key, intermediary_cert,
                                    server_public_key, server, names,
                                    new_cert_path):
    """generate a web server certificate expiring in 1 year"""
    subject_name = x509.Name([
        intermediary_cert.subject.get_attributes_for_oid(
            x509.NameOID.ORGANIZATION_NAME)[0],
        intermediary_cert.subject.get_attributes_for_oid(
            x509.NameOID.ORGANIZATIONAL_UNIT_NAME)[0],
        x509.NameAttribute(x509.NameOID.COMMON_NAME, server),

        # TODO: ExtendedValidation
        # x509.NameAttribute(x509.NameOID.JURISDICTION_COUNTRY_NAME, "Earth"),
        # x509.NameAttribute(x509.NameOID.BUSINESS_CATEGORY, )
    ])

    cert = x509.CertificateBuilder(
        issuer_name=intermediary_cert.subject,
        subject_name=subject_name,
        public_key=server_public_key,
        serial_number=x509.random_serial_number(),
        not_valid_before=datetime.utcnow(),
        not_valid_after=datetime.utcnow() + timedelta(days=365 * 1),
        extensions=[]
    ).add_extension(
        critical=True,
        extension=x509.SubjectAlternativeName(
            [x509.DNSName(name) for name in names])
    ).add_extension(
        critical=True,
        extension=x509.BasicConstraints(ca=False, path_length=None)
    ).add_extension(
        critical=True,
        extension=x509.KeyUsage(
            digital_signature=True,
            content_commitment=False,
            key_encipherment=True,
            data_encipherment=False,
            key_agreement=False,
            key_cert_sign=False,
            crl_sign=False,
            encipher_only=False,
            decipher_only=False,
        )
    ).add_extension(
        critical=True,
        extension=x509.ExtendedKeyUsage(
            [x509.oid.ExtendedKeyUsageOID.SERVER_AUTH])
        # TODO: ExtendedValidation
        # ).add_extension(
        #     critical=True,
        #     extension=x509.PrecertificateSignedCertificateTimestamps(
        #         []
        #     )
    ).sign(
        private_key=intermediary_key,
        algorithm=hashes.SHA384(),
        backend=default_backend(),
    )
    with open(new_cert_path, mode='wb',
              opener=mode_openers.public_file_opener) as f:
        f.write(cert.public_bytes(Encoding.PEM))
Example #23
0
from cryptography import utils
from cryptography import x509
from cryptography.hazmat.bindings._rust import ocsp
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.x509.base import (
    PRIVATE_KEY_TYPES,
    _EARLIEST_UTC_TIME,
    _convert_to_naive_utc_time,
    _reject_duplicate_extension,
)

_OIDS_TO_HASH = {
    "1.3.14.3.2.26": hashes.SHA1(),
    "2.16.840.1.101.3.4.2.4": hashes.SHA224(),
    "2.16.840.1.101.3.4.2.1": hashes.SHA256(),
    "2.16.840.1.101.3.4.2.2": hashes.SHA384(),
    "2.16.840.1.101.3.4.2.3": hashes.SHA512(),
}


class OCSPResponderEncoding(utils.Enum):
    HASH = "By Hash"
    NAME = "By Name"


class OCSPResponseStatus(utils.Enum):
    SUCCESSFUL = 0
    MALFORMED_REQUEST = 1
    INTERNAL_ERROR = 2
    TRY_LATER = 3
    SIG_REQUIRED = 5
Example #24
0
 def __init__(self):
     super(_HS384, self).__init__(hashes.SHA384())
Example #25
0
 def _jwa_RS384(self):
     return _raw_rsa(padding.PKCS1v15(), hashes.SHA384())
Example #26
0
 def __init__(self):
     super(_RS384, self).__init__(padding.PKCS1v15(), hashes.SHA384())
Example #27
0
 def _jwa_PS384(self):
     return _raw_rsa(
         padding.PSS(padding.MGF1(hashes.SHA384()),
                     hashes.SHA384.digest_size), hashes.SHA384())
Example #28
0
 def __init__(self):
     super(_ES384, self).__init__('P-384', hashes.SHA384())
)
@pytest.mark.requires_backend_interface(interface=HashBackend)
class TestSHA256(object):
    test_SHA256 = generate_hash_test(
        load_hash_vectors,
        os.path.join("hashes", "SHA2"),
        [
            "SHA256LongMsg.rsp",
            "SHA256ShortMsg.rsp",
        ],
        hashes.SHA256(),
    )


@pytest.mark.supported(
    only_if=lambda backend: backend.hash_supported(hashes.SHA384()),
    skip_message="Does not support SHA384",
)
@pytest.mark.requires_backend_interface(interface=HashBackend)
class TestSHA384(object):
    test_SHA384 = generate_hash_test(
        load_hash_vectors,
        os.path.join("hashes", "SHA2"),
        [
            "SHA384LongMsg.rsp",
            "SHA384ShortMsg.rsp",
        ],
        hashes.SHA384(),
    )

Example #30
0
    def test_rsa4096_pss_sign(self):
        self.rsa_pss_sign(4096, hashes.SHA256())
        self.rsa_pss_sign(4096, hashes.SHA384())
        self.rsa_pss_sign(4096, hashes.SHA512())

        self.rsa_pss_sign(4096, hashes.SHA256(), hashes.SHA1())