Пример #1
0
def generate_tls_keys():
	""" Creates a TLS private key (RSA, 4096 bits, PEM format) and certificate signing request (CSR). """

	# Query the user for CSR attributes
	country = input("Country: ")
	state = input("State or province: ")
	locality = input("Locality: ")
	organization = input("Organization: ")
	organizational_unit = input("Organizational unit: ")
	email = input("Email: ")
	common_name = input("Common name: ")

	print("Enter any subject alternative names (SANs) you wish to attach to the certificate. Leave blank to continue.")
	sans = []
	while True:
		san = input("Subject alternative name: ")
		if san == '':
			break
		sans.append(DNSName(san))

	# Make sure we can open the output files first
	private_key_file = open("private.key", "wb")
	csr_file = open("certificate_signing_request", "wb")

	# Generate the private key
	key = generate_private_key(public_exponent=65537, key_size=4096, backend=default_backend())

	attributes = [
		NameAttribute(NameOID.COUNTRY_NAME, country),
		NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, state),
		NameAttribute(NameOID.LOCALITY_NAME, locality),
		NameAttribute(NameOID.ORGANIZATION_NAME, organization),
		NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, organizational_unit),
		NameAttribute(NameOID.EMAIL_ADDRESS, email),
		NameAttribute(NameOID.COMMON_NAME, common_name),
	]

	# Generate the CSR and sign it with the private key
	csr = CertificateSigningRequestBuilder().subject_name(Name(attributes))
	if sans:
		csr = csr.add_extension(SubjectAlternativeName(sans), critical=False)
	csr = csr.sign(key, SHA256(), default_backend())

	# Write the private key and CSR to disk
	private_key_file.write(key.private_bytes(encoding=Encoding.PEM, format=PrivateFormat.TraditionalOpenSSL, encryption_algorithm=NoEncryption()))
	csr_file.write(csr.public_bytes(Encoding.PEM))

	private_key_file.close()
	csr_file.close()

	# Success!
	print("Successfully generated a private key and certificate signing request.")
Пример #2
0
def sign_csr_builder(
    session: PivSession,
    slot: SLOT,
    public_key: Union[rsa.RSAPublicKey, ec.EllipticCurvePublicKey],
    builder: x509.CertificateSigningRequestBuilder,
    hash_algorithm: Type[hashes.HashAlgorithm] = hashes.SHA256,
) -> x509.CertificateSigningRequest:
    """Sign a CSR."""
    key_type = KEY_TYPE.from_public_key(public_key)
    dummy_key = _dummy_key(key_type)
    csr = builder.sign(dummy_key, hash_algorithm(), default_backend())
    seq = Tlv.parse_list(Tlv.unpack(0x30, csr.public_bytes(Encoding.DER)))

    # Replace public key
    pub_format = (PublicFormat.PKCS1 if key_type.algorithm == ALGORITHM.RSA
                  else PublicFormat.SubjectPublicKeyInfo)
    dummy_bytes = dummy_key.public_key().public_bytes(Encoding.DER, pub_format)
    pub_bytes = public_key.public_bytes(Encoding.DER, pub_format)
    seq[0] = Tlv(seq[0].replace(dummy_bytes, pub_bytes))

    sig = session.sign(
        slot,
        key_type,
        seq[0],
        hash_algorithm(),
        padding.PKCS1v15(),  # Only used for RSA
    )

    # Replace signature, add unused bits = 0
    seq[2] = Tlv(seq[2].tag, b"\0" + sig)
    # Re-assemble sequence
    der = Tlv(0x30, b"".join(seq))

    return x509.load_der_x509_csr(der, default_backend())
Пример #3
0
def _make_csr(
    subject_name: Name,
    private_key: RSAPrivateKeyWithSerialization,
) -> CertificateSigningRequest:
    return (CertificateSigningRequestBuilder().subject_name(subject_name).sign(
        private_key,
        SHA256(),
    ))
Пример #4
0
def create_csr(key: EllipticCurvePrivateKey,
               template_cert: Certificate) -> CertificateSigningRequest:
    """
    Create a Certificate Signing Request (CSR)
    matching to a corresponding template_cert and sign it with a private key.
    :param key: the private key to sign the CSR
    :param template_cert: a template for retrieving the subject information.
    :return: CSR (https://en.wikipedia.org/wiki/Certificate_signing_request)
    """
    csr_builder = CertificateSigningRequestBuilder().subject_name(
        template_cert.subject)
    try:
        subject_alt_name = template_cert.extensions.get_extension_for_class(
            SubjectAlternativeName)
        csr_builder = csr_builder.add_extension(subject_alt_name.value,
                                                critical=False)
    except ExtensionNotFound:
        pass

    return csr_builder.sign(key, SHA256(), backends.default_backend())
Пример #5
0
    def _sign_with_key_info(
        csr: proto.CertificateSigningRequest,
        builder: x509.CertificateSigningRequestBuilder,
    ):
        """Sign a CertificateSigningRequest with filesystem key."""
        key = SigningKey.from_key_info(csr.key_info, csr.hash_type)

        return builder.sign(
            private_key=key.private_key,
            algorithm=key.algorithm,
            backend=MyBackend(),
        )
Пример #6
0
    def _sign_with_hsm_info(
        csr: proto.CertificateSigningRequest,
        builder: x509.CertificateSigningRequestBuilder,
    ):
        """Sign a CertificateSigningRequest with key information in an HSM."""
        hsm = HsmFactory.from_hsm_info(csr.hsm_info, csr.hash_type)

        dummy_key = SigningKey.from_hsm_info(csr.hsm_info, csr.hash_type)

        base_csr = builder.sign(
            private_key=dummy_key.private_key,
            algorithm=dummy_key.algorithm,
            backend=MyBackend(),
        )

        base_csr.set_pubkey(hsm.public_key)
        base_csr.set_signature(hsm.sign(base_csr.tbs_certrequest_bytes))

        return base_csr