0

I'd like to parse a .csr file in order to retrieve a Common Name (CN) value.

I have a csr file with the following structure:

verify OK
Certificate Request:
Data:
   Version: 0(0x0)
   Subject: C=XX, ST=SSSSSSS, L=SSSSSS, O=CORPORATION X.X, OUT=XX, CN=IAM.YOUARE.COM
   .....

I'd like to retrieve the CN value (in the example above "IAM.YOUARE.COM")

Once I have this value, I'd like to insert it in a .txt file next to the DNS.X field (please notice that it's important to respect the white space between the equal operator and the inserted value). The structure of the .txt field is shown below:

[xxxxx]
basicConstraints = CA:FALSE^M
extendedkeyUsage = serverAuth
subjectAltNAme = @alt_names

[alt_name]
DNS.X = IAM.YOUARE.COM

Up until now, I've been accessing the csr file using the command "openssl req -text - noout -verify -in XXX.csr" and copying the CN value manually. However, I now have a vast list of .csr files to "parse" and I was wondering whether you could give me some indications on how to automate this process.

Alex
  • 151
  • 13

1 Answers1

1

Assuming that using php would be an option (while it's obvious that one can use php to create websites, it's maybe less known that php scripts can also be run from the command line, like shell scripts but with .

// Load and decode the csr file
$csrfiledata=file_get_contents("/path/to/file.csr");
$csr = openssl_csr_get_subject($csrfiledata);
// openssl_csr_get_subject('file://path/to/file.csr') also works
// if the file was read properly, $csr['CN'] will contain the value of CN

Then, assuming that you created a template called template.txt that contains

[alt_name]
DNS.X = $$CN$$

where $$CN$$ is a randomly-chosen placeholder for the CN value. It's now easy to substitute the value read from the csr file and write the result to a file:

$path_to_infile = 'template.txt';
$path_to_outfile = 'outfile.txt';
$file_contents = file_get_contents($path_to_infile);
$file_contents = str_replace('$$CN$$',$csr['CN'],$file_contents);
file_put_contents($path_to_outfile,$file_contents);

How to iterate over files with php is explained here

Community
  • 1
  • 1
fvu
  • 32,488
  • 6
  • 61
  • 79