Search code examples
regexperlopensslcsr

CSR Subject with Special Characters extract


I would need to extract the $subj as seen below snippet, but looks like my Regex isn't working as expected. This is actually similar with this: How to string manipulate/extract subject contents in a CSR using OpenSSL command + Perl? but with a different subject entry in the CSR. I'm not sure if I did a good thing in my regex for the %subjinfo

#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;

my $subj =
    'subject=/O=test~@#$^()_+-=\{}|;':",./<>/OU=test~@#$^()_+-=\{}|;':",./<>/emailAd‌​dress=test~@#$^()_+-=\{}|;':",./<>/L=CDE/ST=ABC/C=AU/CN=test~@#$^()_+ -=\{}|;':",./<>';

my %subjinfo = ( $subj =~ m,(\w+)=([^=]*)(?:/|$),g );
print Dumper \%subjinfo;

and so must give a result to this:

$VAR1 = {
          'subject' => '',
          'L' => 'NYC',
          'C' => 'AMER',
          'OU' => 'test~@#$^()_+-=\{}|;':",./<>',
          'emailAddress' => 'test~@#$^()_+-=\{}|;':",./<>',
          'ST' => 'AMER',
          'CN' => 'test~@#$^()_+-=\{}|;':",./<>',
          'O' => 'test~@#$^()_+-=\{}|;':",./<>'
        };

Is that possible? Can you advise?


Solution

  • Splitting on regex looks more natural than regex only solution,

    use Data::Dumper;
    
    my $subj = q(subject=/O=test~@#$^()_+-=\{}|;':",./<>/OU=test~@#$^()_+-=\{}|;':",./<>/emailAddress=test~@#$^()_+-=\{}|;':",./<>/L=CDE/ST=ABC/C=AU/CN=test~@#$^()_+ -=\{}|;':",./<>);
    
    (undef, my %subjinfo) = split m|/?(\w+)=|, $subj;
    
    print Dumper \%subjinfo;
    

    output

    $VAR1 = {
          'emailAddress' => 'test~@#$^()_+-=\\{}|;\':",./<>',
          'CN' => 'test~@#$^()_+ -=\\{}|;\':",./<>',
          'OU' => 'test~@#$^()_+-=\\{}|;\':",./<>',
          'L' => 'CDE',
          'C' => 'AU',
          'ST' => 'ABC',
          'subject' => '',
          'O' => 'test~@#$^()_+-=\\{}|;\':",./<>'
        };