本文整理匯總了Python中cryptography.x509.oid.NameOID.COMMON_NAME屬性的典型用法代碼示例。如果您正苦於以下問題:Python NameOID.COMMON_NAME屬性的具體用法?Python NameOID.COMMON_NAME怎麽用?Python NameOID.COMMON_NAME使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在類cryptography.x509.oid.NameOID
的用法示例。
在下文中一共展示了NameOID.COMMON_NAME屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: generate_csr
# 需要導入模塊: from cryptography.x509.oid import NameOID [as 別名]
# 或者: from cryptography.x509.oid.NameOID import COMMON_NAME [as 別名]
def generate_csr(common_name, dnsnames, ips, keysize):
key = rsa.generate_private_key(
public_exponent=65537,
key_size=keysize,
backend=default_backend()
)
key_pem = key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption(),
)
csr = x509.CertificateSigningRequestBuilder()
csr = csr.subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, common_name)]))
csr = csr.add_extension(
x509.SubjectAlternativeName(dnsnames + ips),
critical=False,
)
csr = csr.sign(key, hashes.SHA256(), default_backend())
csr_pem = csr.public_bytes(serialization.Encoding.PEM)
return key_pem, csr_pem
示例2: certificate
# 需要導入模塊: from cryptography.x509.oid import NameOID [as 別名]
# 或者: from cryptography.x509.oid.NameOID import COMMON_NAME [as 別名]
def certificate(private_key: rsa.RSAPrivateKey) -> x509.Certificate:
b = x509.CertificateBuilder()
name = x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"CA"),
x509.NameAttribute(NameOID.LOCALITY_NAME, u"San Francisco"),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"Commandment"),
x509.NameAttribute(NameOID.COMMON_NAME, u"CA-CERTIFICATE"),
])
cer = b.subject_name(name).issuer_name(name).public_key(
private_key.public_key()
).serial_number(1).not_valid_before(
datetime.datetime.utcnow()
).not_valid_after(
datetime.datetime.utcnow() + datetime.timedelta(days=10)
).add_extension(
x509.BasicConstraints(ca=False, path_length=None), True
).sign(private_key, hashes.SHA256(), default_backend())
return cer
示例3: ca_certificate
# 需要導入模塊: from cryptography.x509.oid import NameOID [as 別名]
# 或者: from cryptography.x509.oid.NameOID import COMMON_NAME [as 別名]
def ca_certificate(private_key: rsa.RSAPrivateKey) -> x509.Certificate:
b = x509.CertificateBuilder()
name = x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"CA"),
x509.NameAttribute(NameOID.LOCALITY_NAME, u"San Francisco"),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"Commandment"),
x509.NameAttribute(NameOID.COMMON_NAME, u"CA-CERTIFICATE"),
])
cert = b.serial_number(1).issuer_name(
name
).subject_name(
name
).public_key(
private_key.public_key()
).not_valid_before(
datetime.datetime.utcnow()
).not_valid_after(
datetime.datetime.utcnow() + datetime.timedelta(days=10)
).add_extension(
x509.BasicConstraints(ca=True, path_length=None), True
).sign(private_key, hashes.SHA256(), default_backend())
return cert
示例4: format_relative_name
# 需要導入模塊: from cryptography.x509.oid import NameOID [as 別名]
# 或者: from cryptography.x509.oid.NameOID import COMMON_NAME [as 別名]
def format_relative_name(name):
"""Convert a relative name (RDN) into a canonical form.
Examples::
>>> format_relative_name([('C', 'AT'), ('CN', 'example.com')])
'/C=AT/CN=example.com'
>>> format_relative_name(x509.RelativeDistinguishedName([
... x509.NameAttribute(NameOID.COMMON_NAME, u'example.com')
... ]))
'/CN=example.com'
"""
if isinstance(name, x509.RelativeDistinguishedName):
name = [(OID_NAME_MAPPINGS[s.oid], s.value) for s in name]
return '/%s' % ('/'.join(['%s=%s' % (force_text(k), force_text(v)) for k, v in name]))
示例5: test_getitem
# 需要導入模塊: from cryptography.x509.oid import NameOID [as 別名]
# 或者: from cryptography.x509.oid.NameOID import COMMON_NAME [as 別名]
def test_getitem(self):
self.assertEqual(Subject('/CN=example.com')['CN'], 'example.com')
self.assertEqual(Subject('/C=AT/CN=example.com')['C'], 'AT')
self.assertEqual(Subject('/C=AT/CN=example.com')['CN'], 'example.com')
# try NameOID:
self.assertEqual(Subject('/CN=example.com')[NameOID.COMMON_NAME], 'example.com')
self.assertEqual(Subject('/C=AT/CN=example.com')[NameOID.COUNTRY_NAME], 'AT')
self.assertEqual(Subject('/C=AT/CN=example.com')[NameOID.COMMON_NAME], 'example.com')
# OUs
self.assertEqual(Subject('/C=AT/OU=foo/CN=example.com')['OU'], ['foo'])
self.assertEqual(Subject('/C=AT/OU=foo/OU=bar/CN=example.com')['OU'], ['foo', 'bar'])
# test keyerror
with self.assertRaisesRegex(KeyError, r"^'L'$"):
Subject('/C=AT/OU=foo/CN=example.com')['L']
with self.assertRaisesRegex(KeyError, r"^'L'$"):
Subject('/C=AT/OU=foo/CN=example.com')[NameOID.LOCALITY_NAME]
示例6: test_get
# 需要導入模塊: from cryptography.x509.oid import NameOID [as 別名]
# 或者: from cryptography.x509.oid.NameOID import COMMON_NAME [as 別名]
def test_get(self):
self.assertEqual(Subject('/CN=example.com').get('CN'), 'example.com')
self.assertEqual(Subject('/C=AT/CN=example.com').get('C'), 'AT')
self.assertEqual(Subject('/C=AT/CN=example.com').get('CN'), 'example.com')
# try NameOID:
self.assertEqual(Subject('/CN=example.com').get(NameOID.COMMON_NAME), 'example.com')
self.assertEqual(Subject('/C=AT/CN=example.com').get(NameOID.COUNTRY_NAME), 'AT')
self.assertEqual(Subject('/C=AT/CN=example.com').get(NameOID.COMMON_NAME), 'example.com')
# OUs
self.assertEqual(Subject('/C=AT/OU=foo/CN=example.com').get('OU'), ['foo'])
self.assertEqual(Subject('/C=AT/OU=foo/OU=bar/CN=example.com').get('OU'), ['foo', 'bar'])
# test that default doesn't overwrite anytying
self.assertEqual(Subject('/CN=example.com').get('CN', 'x'), 'example.com')
self.assertEqual(Subject('/C=AT/CN=example.com').get('C', 'x'), 'AT')
self.assertEqual(Subject('/C=AT/CN=example.com').get('CN', 'x'), 'example.com')
# test default value
self.assertIsNone(Subject('/C=AT/OU=foo/CN=example.com').get('L'))
self.assertEqual(Subject('/C=AT/OU=foo/CN=example.com').get('L', 'foo'), 'foo')
self.assertIsNone(Subject('/C=AT/OU=foo/CN=example.com').get(NameOID.LOCALITY_NAME))
self.assertEqual(Subject('/C=AT/OU=foo/CN=example.com').get(NameOID.LOCALITY_NAME, 'foo'), 'foo')
示例7: _scan_a_cert
# 需要導入模塊: from cryptography.x509.oid import NameOID [as 別名]
# 或者: from cryptography.x509.oid.NameOID import COMMON_NAME [as 別名]
def _scan_a_cert(id, cert_path, key_path, assigns, is_acme=False):
with open(cert_path, "rb") as f:
crt = x509.load_pem_x509_certificate(f.read(), default_backend())
with open(key_path, "rb") as f:
key = serialization.load_pem_private_key(
f.read(),
password=None,
backend=default_backend()
)
sha1 = binascii.hexlify(crt.fingerprint(hashes.SHA1())).decode()
md5 = binascii.hexlify(crt.fingerprint(hashes.MD5())).decode()
sha1 = ":".join([sha1[i:i+2].upper() for i in range(0, len(sha1), 2)])
md5 = ":".join([md5[i:i+2].upper() for i in range(0, len(md5), 2)])
kt = "RSA" if isinstance(key.public_key(), rsa.RSAPublicKey) else "DSA"
common_name = crt.subject.get_attributes_for_oid(NameOID.COMMON_NAME)
return Certificate(
id=id, cert_path=cert_path, key_path=key_path, keytype=kt,
keylength=key.key_size, domain=common_name[0].value,
assigns=assigns.get(id, []), expiry=crt.not_valid_after, sha1=sha1,
md5=md5, is_acme=is_acme)
示例8: generate_csr
# 需要導入模塊: from cryptography.x509.oid import NameOID [as 別名]
# 或者: from cryptography.x509.oid.NameOID import COMMON_NAME [as 別名]
def generate_csr(key, domainname):
private_key = serialization.load_pem_private_key(key, password=None,
backend=default_backend())
csr = x509.CertificateSigningRequestBuilder().subject_name(x509.Name([
# Provide various details about who we are.
x509.NameAttribute(NameOID.COUNTRY_NAME, u"BR"),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"RJ"),
x509.NameAttribute(NameOID.LOCALITY_NAME, u"Rio de Janeiro"),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"globo.com"),
x509.NameAttribute(NameOID.COMMON_NAME, domainname),
])).add_extension(
x509.SubjectAlternativeName([x509.DNSName(domainname)]),
critical=False,
).sign(private_key, hashes.SHA256(), default_backend())
return csr.public_bytes(serialization.Encoding.PEM)
示例9: generate_csr_and_key
# 需要導入模塊: from cryptography.x509.oid import NameOID [as 別名]
# 或者: from cryptography.x509.oid.NameOID import COMMON_NAME [as 別名]
def generate_csr_and_key():
"""Return a dict with a new csr and key."""
key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend())
csr = x509.CertificateSigningRequestBuilder().subject_name(
x509.Name([
x509.NameAttribute(NameOID.COMMON_NAME, u"admin"),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"system:masters")
])).sign(key, hashes.SHA256(), default_backend())
result = {
'csr': csr.public_bytes(
encoding=serialization.Encoding.PEM).decode("utf-8"),
'key': key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()).decode("utf-8"),
}
return result
示例10: serialize
# 需要導入模塊: from cryptography.x509.oid import NameOID [as 別名]
# 或者: from cryptography.x509.oid.NameOID import COMMON_NAME [as 別名]
def serialize(self,
# password=None,
country=u"US",
state=u"CA",
city=u"San Francisco",
company=u"Lokey Examle",
common_name=u"example.com"):
# This should be handled already
# if not password:
# password = None
key = serialization.load_pem_private_key(
self.to('pem'),
password=None,
backend=default_backend())
subject = x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, country),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, state),
x509.NameAttribute(NameOID.LOCALITY_NAME, city),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, company),
x509.NameAttribute(NameOID.COMMON_NAME, common_name),
])
cert = x509.CertificateSigningRequestBuilder().subject_name(
subject
).sign(key, hashes.SHA256(), default_backend())
return cert.public_bytes(serialization.Encoding.PEM)
示例11: test_pfx
# 需要導入模塊: from cryptography.x509.oid import NameOID [as 別名]
# 或者: from cryptography.x509.oid.NameOID import COMMON_NAME [as 別名]
def test_pfx(_autorestart, _autocmd, _fix_permissions, fake_env, fake_config):
archive_path = fake_env["archive"]
key = rsa.generate_private_key(
public_exponent=65537, key_size=2048, backend=default_backend()
)
with open(archive_path / "privkey.pem", "wb") as f:
f.write(
key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption(),
)
)
subject = issuer = x509.Name(
[x509.NameAttribute(NameOID.COMMON_NAME, u"example.com")]
)
cert = (
x509.CertificateBuilder()
.subject_name(subject)
.issuer_name(issuer)
.public_key(key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(datetime.datetime.utcnow())
.not_valid_after(datetime.datetime.utcnow() + datetime.timedelta(days=10))
.sign(key, hashes.SHA256(), default_backend())
)
with open(archive_path / "cert.pem", "wb") as f:
f.write(cert.public_bytes(serialization.Encoding.PEM))
with open(archive_path / "chain.pem", "wb") as f:
f.write(cert.public_bytes(serialization.Encoding.PEM))
hooks.deploy(config.load(fake_config), LINEAGE)
assert os.path.exists(archive_path / "cert.pfx")
assert os.stat(archive_path / "cert.pfx").st_size != 0
示例12: create_root_ca_cert
# 需要導入模塊: from cryptography.x509.oid import NameOID [as 別名]
# 或者: from cryptography.x509.oid.NameOID import COMMON_NAME [as 別名]
def create_root_ca_cert(root_common_name, root_private_key, days=365):
"""
This method will create a root ca certificate.
:param root_common_name: The common name for the certificate.
:param root_private_key: The private key for the certificate.
:param days: The number of days for which the certificate is valid. The default is 1 year or 365 days.
:return: The root certificate.
:rtype: :class:`x509.Certificate`
"""
file_root_certificate = "demoCA/newcerts/ca_cert.pem"
root_public_key = root_private_key.public_key()
subject = x509.Name(
[x509.NameAttribute(NameOID.COMMON_NAME, str.encode(root_common_name).decode("utf-8"))]
)
builder = create_cert_builder(
subject=subject, issuer_name=subject, public_key=root_public_key, days=days, is_ca=True
)
root_cert = builder.sign(
private_key=root_private_key, algorithm=hashes.SHA256(), backend=default_backend()
)
with open(file_root_certificate, "wb") as f:
f.write(root_cert.public_bytes(serialization.Encoding.PEM))
return root_cert
示例13: create_csr
# 需要導入模塊: from cryptography.x509.oid import NameOID [as 別名]
# 或者: from cryptography.x509.oid.NameOID import COMMON_NAME [as 別名]
def create_csr(private_key, csr_file, subject, is_ca=False):
"""
Method to create a certificate signing request.
:param private_key: The private key to the certificate.
:param csr_file: The file name of the certificate signing request.
:param subject: The subject fo the certificate signing request.
:param is_ca: Boolean to indicate if a cert is ca or non ca.
:return: The certificate signing request.
:rtype: :class `x509.CertificateSigningRequest`
"""
builder = (
x509.CertificateSigningRequestBuilder()
.subject_name(
x509.Name(
[
# Provide various details about who we are.
x509.NameAttribute(NameOID.COMMON_NAME, str.encode(subject).decode("utf-8"))
]
)
)
.add_extension(x509.BasicConstraints(ca=is_ca, path_length=None), critical=False)
)
csr = builder.sign(
private_key=private_key, algorithm=hashes.SHA256(), backend=default_backend()
)
with open(csr_file, "wb") as f:
f.write(csr.public_bytes(serialization.Encoding.PEM))
return csr
示例14: generate_tls_sni_01_cert
# 需要導入模塊: from cryptography.x509.oid import NameOID [as 別名]
# 或者: from cryptography.x509.oid.NameOID import COMMON_NAME [as 別名]
def generate_tls_sni_01_cert(server_name, key_type=u'rsa',
_generate_private_key=None):
"""
Generate a certificate/key pair for responding to a tls-sni-01 challenge.
:param str server_name: The SAN the certificate should have.
:param str key_type: The type of key to generate; usually not necessary.
:rtype: ``Tuple[`~cryptography.x509.Certificate`, PrivateKey]``
:return: A tuple of the certificate and private key.
"""
key = (_generate_private_key or generate_private_key)(key_type)
name = x509.Name([
x509.NameAttribute(NameOID.COMMON_NAME, u'acme.invalid')])
cert = (
x509.CertificateBuilder()
.subject_name(name)
.issuer_name(name)
.not_valid_before(datetime.now() - timedelta(seconds=3600))
.not_valid_after(datetime.now() + timedelta(seconds=3600))
.serial_number(int(uuid.uuid4()))
.public_key(key.public_key())
.add_extension(
x509.SubjectAlternativeName([x509.DNSName(server_name)]),
critical=False)
.sign(
private_key=key,
algorithm=hashes.SHA256(),
backend=default_backend())
)
return (cert, key)
示例15: csr_for_names
# 需要導入模塊: from cryptography.x509.oid import NameOID [as 別名]
# 或者: from cryptography.x509.oid.NameOID import COMMON_NAME [as 別名]
def csr_for_names(names, key):
"""
Generate a certificate signing request for the given names and private key.
.. seealso:: `acme.client.Client.request_issuance`
.. seealso:: `generate_private_key`
:param ``List[str]``: One or more names (subjectAltName) for which to
request a certificate.
:param key: A Cryptography private key object.
:rtype: `cryptography.x509.CertificateSigningRequest`
:return: The certificate request message.
"""
if len(names) == 0:
raise ValueError('Must have at least one name')
if len(names[0]) > 64:
common_name = u'san.too.long.invalid'
else:
common_name = names[0]
return (
x509.CertificateSigningRequestBuilder()
.subject_name(x509.Name([
x509.NameAttribute(NameOID.COMMON_NAME, common_name)]))
.add_extension(
x509.SubjectAlternativeName(list(map(x509.DNSName, names))),
critical=False)
.sign(key, hashes.SHA256(), default_backend()))