将(一行)证书包拆分为 2 个文件

将(一行)证书包拆分为 2 个文件

我在一行中有一个 RSA 私钥和一个证书,我必须将其拆分为一个 .key 和 .crt 文件。

sed 或/和 awk 可以吗?

EDI1:示例(正如您所见,它实际上是一行)

-----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEAoigkOEwqD/d5VsRgCZx8ZjTG+2lMZ+q1QyRaOXZ0OXIFWoKq JlFKI2BauRYl83pM1CLcwrdmnPGGyU9ld5JkWgj9zwI5O7kvyl0sW9ekiDGRdyT+ AEGV5E5aCiki9hgrj61CyvGV4audP3jG+dNi07yFnm40uC1HkrKtFDgiTYMDb2L4 m/UP8pszFiar9rBY0AEhL55gLREX4a/QDxbmP5puUvTErgt0mfbe444+ke5fxxTZ BKhZbVhaPEVVcUVgPlw1EH9wmgj4fTnlNDZBPVqvej8CEt4y/RcEOZ6nPddjBZm+ inr3QbOHc9bvUy5El8RlkqCU/kWkgj1sZlkMGwIDAQABAoIBAG3c6H1EDRN4Rbtl nPOmFBpjE5VuiBe3y0tMK9zWxnPNLpdeA82mMaa6N31C5j+J0te/Lva1r04RzZJC uqpCgr8FbIB+LyypkRl3+v/WoGCtxLKGW5js1pMyCorryAYX5huX9bLt7vBQh19j gtvsPf7asWTfodROyTk42U7joUoFr4TiqBftjVGl3gLB1AidLMHukbiCgRoqGC3v H80VAmc8bt8S46MOvfw1p1Wj/hfyz57pwrU/8/+FHFExzjtkA5Kd8KidzcBc6OnA 3dfsdfsdfdghhhrdfghgfhfghfghhNR0ze6qvlQc6+QQcVIuKxOhmObtBsagnAHJ eqr7FXECgYEAzy881viDqAmsbFC5BN/4GRdUK5nKWFbjD8bo8PbCFMh8Mb+K/GKc dHhUZSMKGQ4u2NNI8fcnh3M0F2zdoaVqZndwr9GxMWyPoB+KBeelDFIWHcY7z55c N2r4CRyWAOMU4lkvBn5RQz1Qxv2de/Tbr3VdxT1tkbWIruIl+wisfwUCgYEAyFz2 xJRugSIBH89haeoHs4JqIKiuHm7+U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96PwIS3jL9FwQ5
nqc912MFmb6KevdBs4dz1u9TLkSXxGWSoJT+RaSCPWxmWQwbAgMBAAGjggEnMIIB
IzAOBgNVHQ8BAf8EBAMCA6gwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMC
MB0GA1UdDgQWBBTkq4+xrl/ODW8rrp3BdTRw849a9jAfBgNVHSMEGDAWgBRbQpEM
sHkbVhoSNGSHqhu+gJBgWTBRBggrBgEFBQcBAQRFMEMwQQYIKwYBBQUHMAKGNWh0
dHA6Ly9zZWN1cml0eV9wb2xpY3lfbWdsfdssdfdsfdsfdsdsfsdfsdffZWNlcnRz
L2NhMBwGA1UdEQQVMBOCEXdvcmtlcm5vZGUubWljYWRvMEEGA1UdHwQ6MDgwNqA0
oDKGMGh0dHA6Ly9zZWN1cml0eV9wb2xpY3lfbWFuYWdlcjo1MDAzL3YxLjAvbm9k
ZWNybDANBgkqhsdfsdfsdfsdfdsffQEAtnBFseEJBzMGMuqRYeXa0rFGcZUXK4S8
HXvpGU95IX988hlv6d4lKc9gEIFBZrqdSk2Q3+GVy3mAGhRpdwwpY5fwlG6wBlOk
4iQOzMVzjYSdsfdsfsdfsfsdfsfsdfdggtz+6Bc+Rs3o2y9L82O14fYBeDPKKh/1
/VBDvVnGlXjXy8FJWgp4Zfsdfdsfdsfsdfsdfsdfdsdsfddfsdsfsdf0UKplawwP
V9Jh+Ruj0Q1MVPjYisNypyZ5F/snO2v9Tgy9/7FID378ZoWRAHYkMljow+ZSt9pF
+p7GR/BLA+vfcWV2482KeYdsfsdfsdfdsfdsfdsfsdfsfd2Or3Q==
-----END CERTIFICATE-----

答案1

delimiter='-{5}[^-]+-{5}'
key=1
crt=2

# get the key
grep -o -P "\\${delimiter}.*?${delimiter}" cert | cut -d $'\n' -f $key | fmt -w 64 > the.key

# get the certificate
grep -o -P "\\${delimiter}.*?${delimiter}" cert | cut -d $'\n' -f $crt | fmt -w 64 > the.crt

输出文件是the.keythe.crt

我认为您的意图是,.key并且.crt是扩展而不是隐藏文件。

另外,cert输入文件是否在一行中包含密钥和证书。

答案2

使用fmt -w 35 filewhere fileis 单行文件,会将其转换为您在问题中显示的确切格式。 fmt是一个简单的文本格式化程序,它将折叠长行,并fmt -w 35尝试将行折叠到file每行 35 个字符,但不会分解太长的单词,这就是它在这种情况下起作用的原因。

命令awk

awk 'BEGIN { of="file.pem" } { print >of } /^-----END/ { of="file.crt" }'

将读取此内容并将第一位输出到file.pem,将第二位输出到file.crt。它通过of在第一个文件名的开头定义变量(“输出文件”),然后在^-----END找到与模式匹配的行时将其更改为第二个文件名来实现此目的。输出中的所有行都fmt将打印到恰好of包含的文件名中。

全部一起:

fmt -w 35 file |
awk 'BEGIN { of="file.pem" } { print >of } /^-----END/ { of="file.crt" }'

相关内容