Skip to content

Instantly share code, notes, and snippets.

@alexishida
Created August 12, 2019 14:13
Show Gist options
  • Save alexishida/327781a248ef74c4577a86facab81a1a to your computer and use it in GitHub Desktop.
Save alexishida/327781a248ef74c4577a86facab81a1a to your computer and use it in GitHub Desktop.
Obter certificados ruby
class CertificadosServices
def pegar_certificado (cer)
cert = OpenSSL::X509::Certificate.new(cer)
certificado = Certificado.new
certificado.nome = cert.subject.to_s.split("CN=")[1].split(":")[0]
certificado.cpf_cnpj = pegar_cpf_cnpj_certificado(cert)
certificado.tipo_certificado = pegar_tipo_certificado(cert)
certificado.serial = cert.serial
certificado.validade = cert.not_after
certificado.revogado = false
certificado.certificado = cert
return certificado
end
def pegar_cpf_cnpj_certificado cert
othername = pegar_other_name(cert)
cpf_cnpj = ''
if othername.include?('2.16.76.1.3.1')
cpf_cnpj = othername['2.16.76.1.3.1'][8..18]
elsif othername.include?('2.16.76.1.3.3')
cpf_cnpj = othername['2.16.76.1.3.3']
if(cpf_cnpj.size == 14)
return cpf_cnpj
else
return ''
end
end
return cpf_cnpj
end
def pegar_tipo_certificado(cert)
othername = pegar_other_name(cert)
cpf_cnpj = pegar_cpf_cnpj_certificado (cert)
filial = cpf_cnpj[8..11]
if othername.include?('2.16.76.1.3.1')
return Certificado.tipo_certificados[:ecpf]
elsif (filial == "0001")
return Certificado.tipo_certificados[:ecnpjraiz]
elsif ( filial != "0001")
return Certificado.tipo_certificados[:ecnpj]
end
return Certificado.tipo_certificados[:invalido]
end
def pegar_other_name (cert)
begin
subject_alt_name = cert.extensions.find {|e| e.oid == "subjectAltName"}
asn_san = OpenSSL::ASN1.decode(subject_alt_name)
asn_san_sequence = OpenSSL::ASN1.decode(asn_san.value[1].value)
othername = Hash.new
for i in 0...asn_san_sequence.value.size
campo = asn_san_sequence.value[i]
if campo.tag == 1
othername['email'] = campo.value.to_s
else
othername[campo.value[0].value.to_s] = campo.value[1].value[0].value
end
end
rescue
return othername
end
return othername
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment