How to cast ASN1::DEROctetStrng to ASN1::ASN1Sequence using Ruby?

148 views Asked by At

I am trying to generate a self signed certificate into pem format. Below is the piece of code that is supposed to do it.

require 'openssl'
require 'r509'

rsa_key = OpenSSL::PKey::RSA.new(1024)
public_key = rsa_key.public_key

subject = "CN=test_host, OU=test_ou, O=test_o, DC=test_dc, DC=test_com"

cert = OpenSSL::X509::Certificate.new
cert.subject = cert.issuer = OpenSSL::X509::Name.parse(subject)
cert.not_before = Time.now
cert.not_after = Time.now + 365 * 24 * 60 * 60
cert.public_key = public_key
cert.serial = 0x0
cert.version = 2

ef = OpenSSL::X509::ExtensionFactory.new
ef.subject_certificate = cert
ef.issuer_certificate = cert

cert.add_extension ef.create_extension("authorityKeyIdentifier", "keyid:always")
cert.add_extension ef.create_extension("keyUsage", "digitalSignature,keyEncipherment", true)
cert.add_extension ef.create_extension("subjectAltName", "DNS:test_host")
cert.add_extension(ef.create_extension("certificatePolicies","1.3.6.1.4.1.41519.1.1"))
cert.sign rsa_key, OpenSSL::Digest::SHA256.new

cert.to_pem
File.write("test_self_cert.pem", cert.to_pem.to_s)

I ran it on pry and everything worked fine. It generated the certificate but when I opened it on Portecle to verify the extensions, Certificate policies was throwing the following error: java.lang.ClassCastException: org.bouncycastle.asn1.DEROctetString cannot be cast to org.bouncycastle.asn1.ASN1Sequence. Below I attached the screenshot for reference. I am stuck right now and appreciate any kind of direction on this.

certificate policies error

0

There are 0 answers