1

证书 PEM 文件包含开头和结尾,例如:

-----BEGIN CERTIFICATE----- [Base64 of certificate] -----END CERTIFICATE

我只需要提取[Base64 of certificate]部分,即剥离"-----BEGIN CERTIFICATE----- "" -----END CERTIFICATE-----"字符串,并且想知道这是否可以使用正则表达式完成,如果可以,那么该正则表达式会是什么样子?

我试过了:

-----BEGIN CERTIFICATE----- (.*) -----END CERTIFICATE-----

但是,它没有给我证书的 Base64,而是返回了所有内容。

谢谢,吉姆

4

4 回答 4

4

由于我不知道你使用的语言,我给你一个相对便携的模式(必须支持前瞻和后瞻):

(?<=-----BEGIN CERTIFICATE----- )(?:\S+|\s(?!-----END CERTIFICATE-----))+(?=\s-----END CERTIFICATE-----)

结果是整个模式,因为环视只是检查。

于 2013-07-16T01:28:14.290 回答
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
于 2016-01-21T07:00:59.743 回答
1

您好,下面是一个示例 perl 代码来支持您的要求。

my $Str = "-----BEGIN CERTIFICATE-----
MIIBuTC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6OaPQn7AmAB4uq1h+ffw+r
RKNHqnsCAwEAATANBgkqhkiG9w0BAQUFAAOBgQCZmj+pgRsN6HpoICawK3XXNAmi
cgfQkailX9akIjD3xSCwEQx4nG6tZjTz30u4NoSffW7pch58SxuZQDqW5NsJcQNq
Ngo/dMoqqpXdi2/0BYEcJ8pjsngrFm+fM2BnyGpXH7aWuKsWjVFGlWlF+yi8I35Q
8wFJt2Z/XGA7WWDjvw==
于 2014-03-25T12:43:53.337 回答
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

如果您想与语言无关,您可以期望页眉/页脚是一个或多个-字符,后跟大写字母,再后跟一个或多个-字符。

于 2020-10-14T14:38:59.007 回答