Skip to content

Instantly share code, notes, and snippets.

@cthornton
Last active September 12, 2017 21:53
Show Gist options
  • Save cthornton/fe1f9d68e18cc4d1ba20 to your computer and use it in GitHub Desktop.
Save cthornton/fe1f9d68e18cc4d1ba20 to your computer and use it in GitHub Desktop.
Ruby PKCS#7 Certificate Only Degenerate (application/x-x509-ca-ra-cert)
# Creates a degenerate PKCS#7 certificate only in ruby (SCEP application/x-x509-ca-ra-cert)
# Inspiration: https://github.com/AppBlade/TestHub/blob/master/app/controllers/scep_controller.rb#L92-L112
#
# Tested Ruby 2.2.0 OSX 10.10, OpenSSL 1.0.1l
require 'openssl'
cert = OpenSSL::X509::Certificate.new File.read('some_cert.crt')
# Fails ruby 2.2, OpenSSL 1.0.1l!!
p7certs = OpenSSL::PKCS7.new
p7certs.type = 'signed'
p7certs.certificates = [cert, cert, ..., cert] # Obviously you would use different certs
der = p7certs.to_der
OpenSSL::PKCS7.new(der) # Fail!
# Working equivalent
include OpenSSL::ASN1
degenerate = Sequence.new([
OpenSSL::ASN1::ObjectId.new('1.2.840.113549.1.7.2'),
ASN1Data.new([
Sequence.new([
OpenSSL::ASN1::Integer.new(1),
OpenSSL::ASN1::Set.new([
]),
Sequence.new([
OpenSSL::ASN1::ObjectId.new('1.2.840.113549.1.7.1')
]),
ASN1Data.new([
decode(cert.to_der), # OpenSSL::PKCS7.certificates[0]
decode(cert.to_der), # OpenSSL::PKCS7.certificates[1],
# ...
decode(cert.to_der) # OpenSSL::PKCS7.certificates[n-1]
], 0, :CONTEXT_SPECIFIC),
ASN1Data.new([
], 1, :CONTEXT_SPECIFIC),
OpenSSL::ASN1::Set.new([
])
])
], 0, :CONTEXT_SPECIFIC)
])
der = degenerate.to_der
decoded_p7certs = OpenSSL::PKCS7.new(der)
puts decoded_p7certs.certificates
@darconeous
Copy link

Thanks for sharing this!

@sebo
Copy link

sebo commented Mar 23, 2016

Thanks for sharing! Awesome!

@cthornton
Copy link
Author

Note: it seems like OpenSSL::PKCS7.new(der) line has issues, I think with OSX enrollment. I think you'll need to manually build the entire pkcs7 wrapper as shown in this code here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment