Module: Sigstore::Internal::X509

Defined in:
lib/sigstore/internal/x509.rb

Defined Under Namespace

Classes: Certificate, Extension

Class Method Summary collapse

Class Method Details

.validate_chain(trust_roots, leaf, time) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/sigstore/internal/x509.rb', line 28

def self.validate_chain(trust_roots, leaf, time)
  cert_factory = java.security.cert.CertificateFactory.getInstance("X.509")
  cert_factory.generateCertificate(java.io.ByteArrayInputStream.new(leaf.to_der.to_java_bytes))
  target = leaf.openssl.to_java

  trust_anchors = Set.new
  intermediate_certs = []
  trust_roots.each do |chain|
    root = chain.last

    trust_anchors << java.security.cert.TrustAnchor.new(root.openssl.to_java, nil)
    chain[..-2].each do |cert|
      intermediate_certs << cert.openssl.to_java
    end
  end

  cert_store_parameters = java.security.cert.CollectionCertStoreParameters.new(intermediate_certs)
  cert_store = java.security.cert.CertStore.getInstance("Collection", cert_store_parameters)

  cert_selector = java.security.cert.X509CertSelector.new
  cert_selector.setCertificate(target)

  pkix_builder_parameters = java.security.cert.PKIXBuilderParameters.new(trust_anchors, cert_selector)
  pkix_builder_parameters.setDate(time) if time
  pkix_builder_parameters.setRevocationEnabled(false)
  pkix_builder_parameters.addCertStore(cert_store)

  cert_path_builder = java.security.cert.CertPathBuilder.getInstance("PKIX")
  cert_path_result = cert_path_builder.build(pkix_builder_parameters)
  chain = cert_path_result.cert_path.getCertificates.map do |cert|
    der = String.from_java_bytes(cert.getEncoded).b
    Certificate.read(der)
  end
  chain.shift # remove the cert itself
  chain << Certificate.read(
    String.from_java_bytes(cert_path_result.get_trust_anchor.getTrustedCert.getEncoded).b
  )
  [chain, nil]
end