如何使用Regex perl在字符串之间提取CSR文本?

时间:2015-07-06 03:05:10

标签: regex perl openssl csr

我需要从整个提取的CSR信息中提取主题备用名称。示例如下:

some text........
                  c9:00:00:00:00:00:00:00:98:a3:22:4e:68:f0:44:
                    8a:ef
                Exponent: 65537 (0x10001)
        Attributes:
        Requested Extensions:
            X509v3 Subject Alternative Name:
                DNS:DNSName1234, IP Address: 192.168.0.0
    Signature Algorithm: sha1WithRSAEncryption
        2e:00:0d:08:ea:04:12:de:58:88:f0:50:72:d5:b3:03:9d:14:
        e9:d6:f2:75:4e:e1:64:57:0e:a8:61:as:55:2e:75:e7:72:0b:
        3d:db:a8:49:68:9f:11:b7:5a:a6:6k:49:25:ed:bc:e2:00:00:

some text...

我需要从上面的示例文本中提取 DNS:DNSName1234,IP地址:192.168.0.0 。 基本上我正在考虑的是将 X509v3主题替代名称:签名算法:sha1WithRSAEncryption 作为两个字符串并在其间获取文本

这是我的一些片段:

my $SubjAltName = `openssl req -in /opt2/myfile/perllib/custom/OpenSSL/certreq.csr -text -noout`; #or die "Could not get SAN";

my $SANtxt = $SubjAltName =~ /X509v3 Subject Alternative Name:(.|\n)*? Signature Algorithm: sha1WithRSAEncryption/;
print $SANtxt; 

应打印 DNS:DNSName1234,IP地址:192.168.0.0 。如果没有,则输出为空白。

感谢您的帮助,谢谢

1 个答案:

答案 0 :(得分:0)

这将提取我认为的要求,字符串是预定义的,因此不需要IP地址验证或其他调整:

#!/usr/bin/perl
use strict;
use warnings;

my $out= 'some text........
                  c9:00:00:00:00:00:00:00:98:a3:22:4e:68:f0:44:
                    8a:ef
                Exponent: 65537 (0x10001)
        Attributes:
        Requested Extensions:
            X509v3 Subject Alternative Name:
                DNS:DNSName1234, IP Address: 192.168.0.0
    Signature Algorithm: sha1WithRSAEncryption
        2e:00:0d:08:ea:04:12:de:58:88:f0:50:72:d5:b3:03:9d:14:
        e9:d6:f2:75:4e:e1:64:57:0e:a8:61:as:55:2e:75:e7:72:0b:
        3d:db:a8:49:68:9f:11:b7:5a:a6:6k:49:25:ed:bc:e2:00:00:

some text...';

my ($string) =grep{/DNS:/}split(/\n/,$out);
if($string){ 
$string=~s/^\s+|\s+$//g;
} 
else{
$string =  ' ';
};
print "$string \n";#prints DNS:DNSName1234, IP Address: 192.168.0.0