我试图使用OpenSSL v1.1.1创建一些证书,它将保留一些特定的数据,作为v3扩展字段。我正在使用一个简单的bash脚本,它将自动执行所有这些操作:
#!/bin/bash
set -e
openssl genrsa -out client.key 4096
openssl req -sha256 -new -utf8 -key client.key -out client.csr -config openssl_client.cnf
openssl x509 -req -days 1000 -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -CAserial certserial -out client.crt -extensions v3_req -extfile client_ext.cnf
openssl x509 -in client.crt -text -noout
openssl_client.cnf结构如下:
[ req ]
prompt = no
distinguished_name = server_distinguished_name
req_extensions = v3_req
[ server_distinguished_name ]
commonName = localhost
stateOrProvinceName = VA
countryName = US
emailAddress = george@me.com
organizationName = Home
organizationalUnitName = Workstation
[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = @alt_names
和openssl_client.cnf包含:
[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = @alt_names
1.2.3.4.5.6.7.8 = ASN1:UTF8:User1
[ alt_names ]
DNS.0 = localhost
脚本运行时,v3扩展的输出如下所示:
...........
X509v3 extensions:
X509v3 Basic Constraints:
CA:FALSE
X509v3 Key Usage:
Digital Signature, Non Repudiation, Key Encipherment
X509v3 Subject Alternative Name:
DNS:localhost
1.2.3.4.5.6.7.8:
..User1
Signature Algorithm: sha256WithRSAEncryption
07:1c:89:eb:1f:30:47:a6:0b:71:33:18:66:b6:00:8f:02:52:
55:41:0c:12:e5:ba:94:a6:7c:f5:7b:97:ba:6e:1a:55:8b:ea:
21:4c:c9:f9:b3:09:6f:6c:99:e3:38:89:f5:65:90:25:15:82:
9e:a6:bf:ce:a5:58:73:01:b1:51:71:cf:10:f1:b0:13:c6:5f:
...........
我正在尝试用一个简单的python程序读取这些扩展:
from OpenSSL import crypto as c
cert = c.load_certificate(c.FILETYPE_PEM, open('./client.crt').read())
count = cert.get_extension_count()
print(count)
for i in range(0, count):
ext = cert.get_extension(i)
ext.get_short_name()
data = ext.get_data()
print("Extension {0}".format(data))
if data == "User1":
print("User1 found!")
else:
print("User1 not found!")
但是,每个扩展名在开头都包含额外的字节:
4
Extensions b'0x00'
User1 not found!
Extension b'x03x02x05xe0'
User1 not found!
Extension b'0x0bx82tlocalhost'
User1 not found!
Extension b'x0cx05User1'
User1 not found!
缺少该主题的文档。有人能解释一下为什么两个额外的字节包含在每个字符串的开头吗?
.get_data()
返回一个编码为ASN.1的bytes
值。它不是字符串
如果您需要扩展名的字符串表示,只需使用str()
:
data = str(ext)
基于@Selcuk的帮助,我发现您可以使用asn1
Python模块进行转换。下面的代码可以很好地打印User1扩展名。
import asn1
from OpenSSL import crypto as c
cert = c.load_certificate(c.FILETYPE_PEM, open('../client.crt').read())
count = cert.get_extension_count()
print(count)
for i in range(0, count):
ext = cert.get_extension(i)
ext.get_short_name()
data = ext.get_data()
decoder = asn1.Decoder()
decoder.start(data)
tag, value = decoder.read()
if i == 3:
if value.decode("utf-8") == "User1":
print("User1 found!")
else:
print("User1 not found!")