How can I split a CA certificate bundle into separate files? How can I split a CA certificate bundle into separate files? linux linux

How can I split a CA certificate bundle into separate files?


You can split the bundle with awk, like this, in an appropriate directory:

awk 'BEGIN {c=0;} /BEGIN CERT/{c++} { print > "cert." c ".pem"}' < ca-bundle.pem 

Then, create the links OpenSSL wants by running the c_rehash utility that comes with OpenSSL:

c_rehash .

Note: use 'gawk' on non linux-platforms - as above relies on a GNU specific feature.


Just to give an alternative; facing the same issue I ended up with csplit:

csplit -k -f bar foo.pem '/END CERTIFICATE/+1' {10}


The following Ruby-script will split the bundle (with one or more certificates in it) into files named after the hashes -- side-stepping the c_rehash step in most cases.

To use, cd into the right directory (such as /etc/ssl/certs/) and run the script with the path to your certificate bundle as the sole argument. For example: ruby /tmp/split-certificates.rb ca-root-nss.crt.

#!/usr/bin/env rubyrequire 'openssl'blob = IO.binread(ARGV[0]) # Read the entire file at onceDELIMITER = "\n-----END CERTIFICATE-----\n"blobs = blob.split(DELIMITER)blobs.each do |blob|    blob.strip!    blob += DELIMITER # Does not break DER    begin        cert = OpenSSL::X509::Certificate.new blob    rescue        puts "Skipping what seems like junk"        next    end    begin        # XXX Need to handle clashes, suffix other than 0        filename=sprintf("%x.0", cert.subject.hash)        File.open(filename,            File::WRONLY|File::CREAT|File::EXCL) do |f|            f.write(blob)        end    rescue Errno::EEXIST        puts "#{filename} already exists, skipping"    endend