从“ openssl s_client”的输出中提取证书

时间:2019-12-23 14:08:22

标签: awk openssl

我想获得http站点的证书链的所有证书。 使用openssl,我连接到http站点,并将输出存储到文件 out.txt

openssl s_client -connect www.openssl.org:443 -showcerts > out.txt

out.txt 的内容如下所示。它包含两个证书:

...
 0 s:CN = www.openssl.org
   i:C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3
-----BEGIN CERTIFICATE-----
MIIFVTCCBD2gAwIBAgISAwk9QUiwVmoQAtcCLKybaK7yMA0GCSqGSIb3DQEBCwUA
...
mQBom1EISBOiNyu5koR6iRZcXsn6x/4kwA==
-----END CERTIFICATE-----
 1 s:C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3
   i:O = Digital Signature Trust Co., CN = DST Root CA X3
-----BEGIN CERTIFICATE-----
MIIEkjCCA3qgAwIBAgIQCgFBQgAAAVOFc2oLheynCDANBgkqhkiG9w0BAQsFADA/
...
KOqkqm57TH2H3eDJAkSnh6/DNFu0Qg==
-----END CERTIFICATE-----
---
...

现在,我想将每个证书存储在扩展名为 .cer 的文件中。 对于上面的示例,应创建文件让我们的加密颁发机构X3.cer www.openssl.org.cer

使用命令 openssl x509 ,我只能存储 out.txt 中包含的第一份证书。

cat out.txt | openssl x509 > www.openssl.org.cer

但是我想存储 out.txt 中包含的所有证书,而不仅仅是第一个。

可以通过 openssl 完成此操作吗?或使用 awk 吗?

1 个答案:

答案 0 :(得分:0)

是的,这可以通过awk完成。我想逐个介绍我的解决方案。

步骤1:提取“ BEGIN证书”和“ END证书”之间的所有内容

仅在“ BEGIN CERTIFICATE”和“ END CERTIFICATE”之间写入行以输出:

awk '
/BEGIN CERTIFICATE/,/END CERTIFICATE/ {
print $0
}
' out.txt

步骤2:提取包含CN的行

选择包含CN的行(例如0 s:CN = www.openssl.org)

awk '
/^ [0-9]+ s:.*CN = / {
print $0
}
' out.txt

这将产生输出:

 0 s:CN = www.openssl.org
 1 s:C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3

步骤3:提取字段CN的内容

awk '
BEGIN {
# change field separator, so that $2 returns everything after "CN = "
FS="CN = "
}
# selects line which contains CN (e.g.  0 s:CN = www.openssl.org)
/^ [0-9]+ s:.*CN = / {
# use CN (e.g. www.openssl.org) as filename
print $2
}
' out.txt

这将产生输出:

www.openssl.org
Let's Encrypt Authority X3

步骤4:完整解决方案

这将创建文件让我们的加密授权机构X3.cer www.openssl.org.cer

awk '
BEGIN {
# change field separator, so that $2 returns everything after "CN = "
FS="CN = "
}
# selects line which contains CN (e.g.  0 s:CN = www.openssl.org)
/^ [0-9]+ s:.*CN = / {
# use CN (e.g. www.openssl.org) as filename
filename=$2".cer"
}
# write all lines between "BEGIN CERTIFICATE" and "END CERTIFICATE" to filename
/BEGIN CERTIFICATE/,/END CERTIFICATE/ {
print $0 > filename
}
' out.txt

AWK文档: https://www.gnu.org/software/gawk/manual/html_node/index.html