Class Certificate

java.lang.Object
com.codename1.backend.security.pki.Certificate

public final class Certificate extends Object

An X.509 v3 certificate, read from DER or PEM.

Certificate cert = Certificate.fromPem(pem);
cert.getSubject().get("CN");          // "api.example.com"
cert.getDnsNames();                   // ["api.example.com", "*.example.com"]
cert.isValidAt(System.currentTimeMillis());

Reading checks the structure, not the trust: a certificate is only as good as the chain CertificateValidator builds for it.

  • Field Summary

    Fields
    Modifier and Type
    Field
    Description
    static final String
    The extended key usage of a TLS client certificate.
    static final int
    keyUsage bit: cRLSign.
    static final int
    keyUsage bit: digitalSignature.
    static final int
    keyUsage bit: keyAgreement.
    static final int
    keyUsage bit: keyCertSign.
    static final int
    keyUsage bit: keyEncipherment.
    static final String
    The extended key usage of a TLS server certificate.
  • Method Summary

    Modifier and Type
    Method
    Description
    decode(byte[] der)
    Reads a certificate from its DER.
    boolean
    equals(Object other)
    Two certificates are equal when their DER is.
    fetchChain(String host, int port, int timeoutMillis)
    The chain host presents on port, leaf first, after a verified TLS handshake against the default roots: the input a pinning check compares against, or an expiry monitor reads.
    The first CERTIFICATE block of pem.
    The OIDs of the extensions marked critical.
    The DNS names of the subject alternative name extension.
    The e-mail addresses of the subject alternative name extension.
    byte[]
    The DER this certificate was read from.
    The extended key usage OIDs (SERVER_AUTH, CLIENT_AUTH...), or null when the certificate has no such extension and so allows every purpose.
    The IP addresses of the subject alternative name extension, IPv4 dotted and IPv6 as eight uncompressed hex groups.
    Who signed this certificate.
    int
    The first byte of keyUsage (DIGITAL_SIGNATURE, KEY_CERT_SIGN...), or -1 when the certificate has no key usage extension and so allows every use.
    long
    The end of the validity period, in milliseconds since the epoch.
    long
    The start of the validity period, in milliseconds since the epoch.
    int
    The basic constraints path length, or -1 when it has none.
    byte[]
    The subject's public key, as SubjectPublicKeyInfo DER: what Crypto.verify and Crypto.ecdh take.
    The serial number as lower case hex, without leading zeros.
    The Crypto algorithm the issuer signed with (RS256, PS256, ES384...).
    Whom this certificate names.
    The URIs of the subject alternative name extension.
    int
    1, 2 or 3.
    int
    Returns a hash code value for the object.
    boolean
    Whether the basic constraints extension says this is a CA.
    boolean
    True when the subject and the issuer are the same name: a root, or a self-issued certificate.
    boolean
    isSignedBy(byte[] issuerPublicKey)
    Whether issuerPublicKey signed this certificate.
    boolean
    isValidAt(long millis)
    True when millis is inside the validity period, both ends included.
    Every CERTIFICATE block of pem, in order, as a full-chain file holds them: the leaf first, then its issuers.
    boolean
    Whether this certificate is for host: a DNS name, matched against the subject alternative names with a wildcard allowed for the leftmost label only, or an IP literal matched against the IP addresses.
    selfSigned(DistinguishedName subject, byte[] privateKey, int days)
    A self-signed X.509 v3 certificate for privateKey: issuer and subject are both subject, valid from now for days days, with a random 128-bit serial number and no extensions.
    The certificate as one PEM block.
    The subject, the issuer and the serial number, for a log line.

    Methods inherited from class Object

    clone, finalize, getClass, notify, notifyAll, wait, wait, wait
  • Field Details

    • SERVER_AUTH

      public static final String SERVER_AUTH
      The extended key usage of a TLS server certificate.
      See Also:
    • CLIENT_AUTH

      public static final String CLIENT_AUTH
      The extended key usage of a TLS client certificate.
      See Also:
    • DIGITAL_SIGNATURE

      public static final int DIGITAL_SIGNATURE
      keyUsage bit: digitalSignature.
      See Also:
    • KEY_ENCIPHERMENT

      public static final int KEY_ENCIPHERMENT
      keyUsage bit: keyEncipherment.
      See Also:
    • KEY_AGREEMENT

      public static final int KEY_AGREEMENT
      keyUsage bit: keyAgreement.
      See Also:
    • KEY_CERT_SIGN

      public static final int KEY_CERT_SIGN
      keyUsage bit: keyCertSign.
      See Also:
    • CRL_SIGN

      public static final int CRL_SIGN
      keyUsage bit: cRLSign.
      See Also:
  • Method Details

    • selfSigned

      public static Certificate selfSigned(DistinguishedName subject, byte[] privateKey, int days) throws IOException
      A self-signed X.509 v3 certificate for privateKey: issuer and subject are both subject, valid from now for days days, with a random 128-bit serial number and no extensions. For tests, a development TLS endpoint, or an identity a peer pins by its key rather than its issuer.
      Parameters:
      privateKey - a PKCS#8 key, RSA, P-256 or P-384, carrying its public key as every key Crypto generates and openssl writes does
      days - how long it is valid, at least 1
      Throws:
      IOException
    • fetchChain

      public static List<Certificate> fetchChain(String host, int port, int timeoutMillis) throws IOException

      The chain host presents on port, leaf first, after a verified TLS handshake against the default roots: the input a pinning check compares against, or an expiry monitor reads.

      List<Certificate> chain = Certificate.fetchChain("api.example.com", 443, 5000);
      byte[] spkiHash = Crypto.sha256(chain.get(0).getPublicKey());
      
      Throws:
      IOException - when the connection or the handshake fails, which includes a chain the default roots do not vouch for
    • decode

      public static Certificate decode(byte[] der) throws IOException
      Reads a certificate from its DER.
      Throws:
      IOException
    • fromPem

      public static Certificate fromPem(String pem) throws IOException
      The first CERTIFICATE block of pem.
      Throws:
      IOException
    • listFromPem

      public static List<Certificate> listFromPem(String pem) throws IOException
      Every CERTIFICATE block of pem, in order, as a full-chain file holds them: the leaf first, then its issuers.
      Throws:
      IOException
    • getEncoded

      public byte[] getEncoded()
      The DER this certificate was read from.
    • toPem

      public String toPem()
      The certificate as one PEM block.
    • getVersion

      public int getVersion()
      1, 2 or 3.
    • getSerialNumber

      public String getSerialNumber()
      The serial number as lower case hex, without leading zeros.
    • getIssuer

      public DistinguishedName getIssuer()
      Who signed this certificate.
    • getSubject

      public DistinguishedName getSubject()
      Whom this certificate names.
    • getNotBefore

      public long getNotBefore()
      The start of the validity period, in milliseconds since the epoch.
    • getNotAfter

      public long getNotAfter()
      The end of the validity period, in milliseconds since the epoch.
    • isValidAt

      public boolean isValidAt(long millis)
      True when millis is inside the validity period, both ends included.
    • getPublicKey

      public byte[] getPublicKey()
      The subject's public key, as SubjectPublicKeyInfo DER: what Crypto.verify and Crypto.ecdh take.
    • getSignatureAlgorithm

      public String getSignatureAlgorithm() throws IOException
      The Crypto algorithm the issuer signed with (RS256, PS256, ES384...).
      Throws:
      CertificateException - when the algorithm is outside the profile
      IOException
    • isCertificateAuthority

      public boolean isCertificateAuthority()
      Whether the basic constraints extension says this is a CA.
    • getPathLength

      public int getPathLength()
      The basic constraints path length, or -1 when it has none.
    • getKeyUsage

      public int getKeyUsage()
      The first byte of keyUsage (DIGITAL_SIGNATURE, KEY_CERT_SIGN...), or -1 when the certificate has no key usage extension and so allows every use.
    • getExtendedKeyUsage

      public List<String> getExtendedKeyUsage()
      The extended key usage OIDs (SERVER_AUTH, CLIENT_AUTH...), or null when the certificate has no such extension and so allows every purpose.
    • getDnsNames

      public List<String> getDnsNames()
      The DNS names of the subject alternative name extension.
    • getIpAddresses

      public List<String> getIpAddresses()
      The IP addresses of the subject alternative name extension, IPv4 dotted and IPv6 as eight uncompressed hex groups.
    • getEmailAddresses

      public List<String> getEmailAddresses()
      The e-mail addresses of the subject alternative name extension.
    • getUris

      public List<String> getUris()
      The URIs of the subject alternative name extension.
    • getCriticalExtensions

      public List<String> getCriticalExtensions()
      The OIDs of the extensions marked critical.
    • isSelfIssued

      public boolean isSelfIssued()
      True when the subject and the issuer are the same name: a root, or a self-issued certificate.
    • isSignedBy

      public boolean isSignedBy(byte[] issuerPublicKey) throws IOException
      Whether issuerPublicKey signed this certificate.
      Returns:
      false when the signature does not verify
      Throws:
      IOException - when the algorithm is outside the profile or the key is not of the kind it uses
    • matchesHost

      public boolean matchesHost(String host)
      Whether this certificate is for host: a DNS name, matched against the subject alternative names with a wildcard allowed for the leftmost label only, or an IP literal matched against the IP addresses. The common name is not consulted, as RFC 9525 and every browser require.
    • equals

      public boolean equals(Object other)
      Two certificates are equal when their DER is.
      Overrides:
      equals in class Object
    • hashCode

      public int hashCode()
      Description copied from class: Object
      Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable. The general contract of hashCode is: Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application. If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables. As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)
      Overrides:
      hashCode in class Object
    • toString

      public String toString()
      The subject, the issuer and the serial number, for a log line.
      Overrides:
      toString in class Object