证书PEM文件包含开头和结尾,如:
-----BEGIN CERTIFICATE----- [Base64 of certificate] -----END CERTIFICATE
我只需要提取[Base64 of certificate]
部分,即剥离"-----BEGIN CERTIFICATE----- "
和" -----END CERTIFICATE-----"
字符串,并想知道是否可以使用正则表达式完成此操作,如果是,那么是什么那个正则表达式会是什么样的?
我试过了:
-----BEGIN CERTIFICATE----- (.*) -----END CERTIFICATE-----
但是,不是给我证书的Base64,而是返回所有内容。
谢谢, 吉姆
答案 0 :(得分:3)
由于我不知道你使用的语言,我给你一个相对便携的模式(必须支持前瞻和后视):
(?<=-----BEGIN CERTIFICATE----- )(?:\S+|\s(?!-----END CERTIFICATE-----))+(?=\s-----END CERTIFICATE-----)
结果是整个模式,因为看起来只是检查。
答案 1 :(得分:3)
在perl:
my base64_cert_data;
if ($certbuf=~/(-+BEGIN CERTIFICATE-+)(.*?)(-+END CERTIFICATE-+)/s) {
base64_cert_data = $2;
}
正则表达式解释:
/(-+BEGIN CERTIFICATE-+)(.*?)(-+END CERTIFICATE-+)/s
1st Capturing group (-+BEGIN CERTIFICATE-+)
-+ matches the character - literally
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
BEGIN CERTIFICATE matches the characters BEGIN CERTIFICATE literally (case sensitive)
-+ matches the character - literally
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
2nd Capturing group (.*?)
.*? matches any character
Quantifier: *? Between zero and unlimited times, as few times as possible, expanding as needed [lazy]
3rd Capturing group (-+END CERTIFICATE-+)
-+ matches the character - literally
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
END CERTIFICATE matches the characters END CERTIFICATE literally (case sensitive)
-+ matches the character - literally
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
s modifier: single line. Dot matches newline characters
答案 2 :(得分:1)
下面是一个支持您的要求的示例perl代码。
my $Str = "-----BEGIN CERTIFICATE-----
MIIBuTCCASKgAwIBAgIQNdNhtuV5GbNHYZsf+LvM0zANBg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iG9w0BAQUFAAOBgQCZmj+pgRsN6HpoICawK3XXNAmi
cgfQkailX9akIjD3xSCwEQx4nG6tZjTz30u4NoSffW7pch58SxuZQDqW5NsJcQNq
Ngo/dMoqqpXdi2/0BYEcJ8pjsngrFm+fM2BnyGpXH7aWuKsWjVFGlWlF+yi8I35Q
8wFJt2Z/XGA7WWDjvw==
答案 3 :(得分:1)
base64字符集是:
[A-Za-z0-9+/\r\n]+={0,2}
-这是对PEM文件(base64证书)通常使用的内容的准确描述。 =
用于填充(末尾),\r\n
是换行符。
将所有内容放在一起,我们得到:
"-+BEGIN\\s+.*CERTIFICATE[^-]*-+(?:\\s|\\r|\\n)+" // Header
+ "([A-Za-z0-9+/\r\n]+={0,2})" // Base64 text
+ "-+END\\s+.*CERTIFICATE[^-]*-+" // Footer
如果您想与语言无关,则可以期望页眉/页脚为一个或多个-
字符,后面仅是大写字母,再由一个或多个-
字符组成。< / p>