Class X509Helper


  • public class X509Helper
    extends java.lang.Object
    X509Helper is the class for simplifying the creation of public/private key pair and X509 certificates. It supports the following functionalities:
    • Generate the public/private key pair.
    • Generate the self-signed X509 certificate that is based on the public key, and is signed by the private key.
    • Persist the X509 certificate into pem-formated file.
    • Persist the private key which is passphrase encoded, into pem-formated file. X509Helper will generate a random string as passphrase if the passphrase is not set.
    • Generate CSR (certificate signing request), that is based on the public key, and is signed by the private key. The CSR is saved into a pem-format file.
    • Import the signed X509 certificate that is in the pem-formated file.
    • Import the private key that is in the pem-format file.

    The following X509 certificate fields are supported:

    • Common Name (CN): X509Heloper automatically fetches the fully qualified domain name (FQDN) of the computer. It could be set by the user of X509Helper.
    • Expiration days: the days that the X509 certificate will expire from now. The default value is 365 days.
    • Country Name (C): optional.
    • State Name (ST): optional.
    • Locality Name (L): optional.
    • Organization Name (O): optional.
    • Organization Unit Name (OU): optional.

    One main usage of X509Helper is to generate a self-sign server certificate with private key in pem-format files. Those certificate and the private key pem-format files could be used to setup SSL/TLS port of the application. generateSelfSignedCertificateinPem will perform all necessary steps to generate a private key in pem-formated file and a X509 certificate in pem-formated file.

    Another usage of X509Helper is to generate a CSR in pem-format files. The CSR would be sent to a CA to be signed. The CA will return a X509 certificate based on the CSR. generate CSR will perform all necessary steps to generate a CSR in pem-formated file.

    Since:
    1.0
    • Constructor Summary

      Constructors 
      Constructor Description
      X509Helper()
      Constructor
    • Method Summary

      All Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      void clear()
      Clear public/private key pair, certificate and passphrase for private key file.
      void clearCertificate()
      Clear the public/private key pair, the certificate, and the passphrase for private key file.
      void generateCSR​(java.lang.String CSRFileFullPathName)
      Generate CSR and save theCSR in pem file.
      void generateKeyPair()
      Generate public/private key pair.
      void generateSelfSignedCertificate()
      Generate self-signed certificate.
      void generateSelfSignedCertificateinPem​(java.lang.String privateKeyFileFullPathName, java.lang.String certificateFileFullPathName)
      Generate self-signed certificate and persist the private key and certificate to pem files.
      java.security.cert.X509Certificate getCertificate()
      Get certificate.
      java.lang.String getCN()
      Get common name of certificate.
      java.lang.String getCountry()
      Get country of certificate.
      java.lang.String getECCurve()
      Get EC Curve of the Public/Private key pair.
      java.lang.Integer getExpirationDays()
      Get certificate expiration in days.
      java.lang.String getKeypairAlgorithm()
      Get algorithm of the Public/Private key pair.
      java.lang.Integer getKeysize()
      Get key size of the Public/Private key pair.
      java.lang.String getLocality()
      Get locality of certificate.
      java.lang.String getOrganization()
      Get organization of certificate.
      java.lang.String getOrganizationalUnit()
      Get organization unit of certificate.
      java.lang.String getPassphrase()
      Get passphrase for private key pem file.
      java.security.PrivateKey getPrivateKey()
      Get private key of Certificate.
      java.security.PublicKey getPublicKey()
      Get public key of Certificate.
      java.lang.String getSignatureAlgorithm()
      Get algorithm of the signature.
      java.lang.String getState()
      Get state of certificate.
      void importPrivateKeyAndCertificateFromPem​(java.lang.String privateKeyFileFullPathName, java.lang.String certificateFileFullPathName)
      Import the private key and certificate from pem-format files.
      void savePrivateKeyAndCertificateToPem​(java.lang.String privateKeyFileFullPathName, java.lang.String certificateFileFullPathName)
      Save the private key and certificate to pem-format files.
      void setCN​(java.lang.String cn)
      Set common name of certificate.
      void setCountry​(java.lang.String country)
      Set country of certificate.
      void setECCurve​(java.lang.String ecCurve)
      Set EC Curve of the Public/Private key pair.
      void setExpirationDays​(java.lang.Integer days)
      Set certificate expiration in days.
      void setKeypairAlgorithm​(java.lang.String keypairAlgorithm)
      Set algorithm of the Public/Private key pair.
      void setKeySize​(java.lang.Integer keySize)
      Set key size of the Public/Private key pair.
      void setLocality​(java.lang.String locality)
      Set locality of certificate.
      void setOrganization​(java.lang.String organization)
      Set organization of certificate.
      void setOrganizationalUnit​(java.lang.String ou)
      Set organization unit of certificate.
      void setPassphrase​(java.lang.String passphrase)
      Set passphrase.
      void setSignatureAlgorithm​(java.lang.String signatureAlgorithm)
      Set algorithm of the signature. setKeypairAlgorithm must be called before this method.
      void setState​(java.lang.String state)
      Set state of certificate.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Constructor Detail

      • X509Helper

        public X509Helper()
        Constructor
    • Method Detail

      • getCN

        public java.lang.String getCN()
        Get common name of certificate.

        The FQDN will be used as default name if it is not supplied.

        Returns:
        common name of certificate
      • setCN

        public void setCN​(java.lang.String cn)
        Set common name of certificate.
        Parameters:
        cn - common name to set
      • getOrganizationalUnit

        public java.lang.String getOrganizationalUnit()
        Get organization unit of certificate.
        Returns:
        organization unit
      • setOrganizationalUnit

        public void setOrganizationalUnit​(java.lang.String ou)
        Set organization unit of certificate.

        Optional field.

        Parameters:
        ou - organization unit
      • getOrganization

        public java.lang.String getOrganization()
        Get organization of certificate.
        Returns:
        organization
      • setOrganization

        public void setOrganization​(java.lang.String organization)
        Set organization of certificate.

        Optional field.

        Parameters:
        organization - Organization
      • getLocality

        public java.lang.String getLocality()
        Get locality of certificate.
        Returns:
        locality
      • setLocality

        public void setLocality​(java.lang.String locality)
        Set locality of certificate.

        Optional field.

        Parameters:
        locality - Locality
      • getState

        public java.lang.String getState()
        Get state of certificate.
        Returns:
        state
      • setState

        public void setState​(java.lang.String state)
        Set state of certificate.

        Optional field.

        Parameters:
        state - State
      • getCountry

        public java.lang.String getCountry()
        Get country of certificate.
        Returns:
        country
      • setCountry

        public void setCountry​(java.lang.String country)
        Set country of certificate.

        Optional field.

        Parameters:
        country - Country
      • getExpirationDays

        public java.lang.Integer getExpirationDays()
        Get certificate expiration in days.

        default value is 365 days.

        Returns:
        certificate expiration in days
      • setExpirationDays

        public void setExpirationDays​(java.lang.Integer days)
        Set certificate expiration in days.
        Parameters:
        days - days to expire
      • getKeysize

        public java.lang.Integer getKeysize()
        Get key size of the Public/Private key pair.

        default and minimum value is 2048.

        Returns:
        key size of the Public/Private key pair
      • setKeySize

        public void setKeySize​(java.lang.Integer keySize)
        Set key size of the Public/Private key pair.

        setKeypairAlgorithm must be called before this method. If the value is 0, 2048 will be used.

        Parameters:
        keySize - size of the Public/Private key pair
      • getKeypairAlgorithm

        public java.lang.String getKeypairAlgorithm()
        Get algorithm of the Public/Private key pair.

        default is "EC".

        Returns:
        algorithm of the Public/Private key pair
      • setKeypairAlgorithm

        public void setKeypairAlgorithm​(java.lang.String keypairAlgorithm)
        Set algorithm of the Public/Private key pair.

        The supported ones are "EC" and "RSA".

        If the algorithm is "EC", set the ECCurve to "sect521r1", and set the signature algorithm to "SHA384withECDSA".

        If the algorithm is "RSA", set the Keysize to 2048, , and set the signature algorithm to "SHA384withRSA".

        Set to default algorithm, "RSA", if keypairAlgorithm is null or empty string.

        Parameters:
        keypairAlgorithm - of the Public/Private key pair
      • getECCurve

        public java.lang.String getECCurve()
        Get EC Curve of the Public/Private key pair.

        default is "sect571r1".

        Returns:
        EC Curve of the Public/Private key pair
      • setECCurve

        public void setECCurve​(java.lang.String ecCurve)
        Set EC Curve of the Public/Private key pair.

        setKeypairAlgorithm("EC") must be called before this method.

        Set to default EC Curve, "sect571r1", if ecCurve is null or empty string.

        Parameters:
        ecCurve - Curve of the Public/Private key pair
      • getSignatureAlgorithm

        public java.lang.String getSignatureAlgorithm()
        Get algorithm of the signature.
        Returns:
        algorithm of the signature
      • setSignatureAlgorithm

        public void setSignatureAlgorithm​(java.lang.String signatureAlgorithm)
        Set algorithm of the signature. setKeypairAlgorithm must be called before this method. If the algorithm of Key Pair is "EC", the supported signature algorithms are
        • "SHA384withECDSA", as the default.
        • "SHA256withECDSA"

        If the algorithm of Key Pair is "RSA", the supported signature algorithms are

        • "SHA384withRSA", as the default.
        • "SHA256withRSA"
        Set to default algorithm, "SHA384withECDSA" for "EC", and "SHA384withRSA" for non-EC, if signatureAlgorithm is null or empty string.
        Parameters:
        signatureAlgorithm - of the signature
      • getPrivateKey

        public java.security.PrivateKey getPrivateKey()
        Get private key of Certificate.
        Returns:
        private key
      • getPublicKey

        public java.security.PublicKey getPublicKey()
        Get public key of Certificate.
        Returns:
        public key
      • getCertificate

        public java.security.cert.X509Certificate getCertificate()
        Get certificate.
        Returns:
        certificate
      • clearCertificate

        public void clearCertificate()
        Clear the public/private key pair, the certificate, and the passphrase for private key file.
      • clear

        public void clear()
        Clear public/private key pair, certificate and passphrase for private key file.

        Reset the keypair algorithm to "EC", the ECCurve to "sect571r1", the keysize to 2048, the signature algorith to "SHA384withECDSA".

      • generateKeyPair

        public void generateKeyPair()
                             throws java.security.NoSuchAlgorithmException,
                                    java.security.NoSuchProviderException,
                                    java.security.InvalidParameterException,
                                    java.security.InvalidAlgorithmParameterException
        Generate public/private key pair.
        Throws:
        java.security.NoSuchAlgorithmException - encryption algorithm is not supported.
        java.security.NoSuchProviderException - provider "BC" is not supported.
        java.security.InvalidAlgorithmParameterException - invalid EC curve is used.
        java.security.InvalidParameterException - invalid algorithm parameters (e.g. invalid RSA keysize)
      • generateSelfSignedCertificate

        public void generateSelfSignedCertificate()
                                           throws org.bouncycastle.operator.OperatorCreationException,
                                                  java.security.cert.CertificateException,
                                                  java.security.NoSuchAlgorithmException,
                                                  java.security.NoSuchProviderException,
                                                  java.security.InvalidAlgorithmParameterException,
                                                  org.bouncycastle.cert.CertIOException
        Generate self-signed certificate.

        If the public/private key pair exists, a self signed certificate based on the public key is generated and signed by the private key. Otherwise, a new pair of public/private key is generated and the certificate is generated based on that new key pair.

        Throws:
        org.bouncycastle.operator.OperatorCreationException - fail to create the signer from the.
        java.security.cert.CertificateException - the validation of the public/private key pair failed, or the certificate is failed to be built from the public/privatekey pair.
        java.security.NoSuchAlgorithmException - the encryption algorithm is not supported.
        java.security.NoSuchProviderException - provider "BC" is not supported.
        java.security.InvalidAlgorithmParameterException - invalid EC curve is used.
        org.bouncycastle.cert.CertIOException - add subject alternative name extension failed.
      • savePrivateKeyAndCertificateToPem

        public void savePrivateKeyAndCertificateToPem​(java.lang.String privateKeyFileFullPathName,
                                                      java.lang.String certificateFileFullPathName)
                                               throws java.io.IOException,
                                                      java.security.cert.CertificateException
        Save the private key and certificate to pem-format files.

        If the passphrase for the private key file is not set, a random byte string will be generated to be used as the passphrase.

        Parameters:
        privateKeyFileFullPathName - filename of private key
        certificateFileFullPathName - file name of certificate
        Throws:
        java.io.IOException - fail to save the certificate or private key to the pem file.
        java.security.cert.CertificateException - the certificate does not exist or it failed to get the encode of the certificate.
      • generateSelfSignedCertificateinPem

        public void generateSelfSignedCertificateinPem​(java.lang.String privateKeyFileFullPathName,
                                                       java.lang.String certificateFileFullPathName)
                                                throws org.bouncycastle.operator.OperatorCreationException,
                                                       java.security.cert.CertificateException,
                                                       java.io.IOException,
                                                       java.security.NoSuchAlgorithmException,
                                                       java.security.NoSuchProviderException,
                                                       java.security.InvalidAlgorithmParameterException
        Generate self-signed certificate and persist the private key and certificate to pem files.

        If the public/private key pair exists, a self signed certificate based on the public key is generated and signed by the private key. Otherwise, a new pair of public/private key is generated and the certificate is generated based on that new key pair.

        Parameters:
        privateKeyFileFullPathName - file name of private key
        certificateFileFullPathName - file name of certificate
        Throws:
        java.io.IOException - fail to save the certificate or private key to pem file.
        org.bouncycastle.operator.OperatorCreationException - fail to create the signer from the private key.
        java.security.cert.CertificateException - the validation of the public/private key pair failed, or the certificate is failed to be built from the public/privatekey pair.
        java.security.NoSuchAlgorithmException - the encryption algorithm is not supported.
        java.security.NoSuchProviderException - provider "BC" is not supported.
        java.security.InvalidAlgorithmParameterException - invalid EC curve is used.
      • getPassphrase

        public java.lang.String getPassphrase()
        Get passphrase for private key pem file.

        If the passphrase is not set, a random byte string will be generated to be used as the passphrase.

        Returns:
        passphrase
      • setPassphrase

        public void setPassphrase​(java.lang.String passphrase)
        Set passphrase.
        Parameters:
        passphrase - passphrase for private key file
      • generateCSR

        public void generateCSR​(java.lang.String CSRFileFullPathName)
                         throws org.bouncycastle.operator.OperatorCreationException,
                                java.io.IOException,
                                java.security.NoSuchAlgorithmException,
                                java.security.NoSuchProviderException,
                                java.security.InvalidAlgorithmParameterException
        Generate CSR and save theCSR in pem file.

        If the public/private key pair exists, a CSR is generated based on the key pair. Otherwise, a new pair of public/private key is generated and the CSR is generated based on that new key pair.

        Parameters:
        CSRFileFullPathName - file name of CSR
        Throws:
        org.bouncycastle.operator.OperatorCreationException - fail to create the signer from the the private key.
        java.io.IOException - fail to save the CSR to the pem file.
        java.security.NoSuchAlgorithmException - the encryption algorithm is not supported.
        java.security.NoSuchProviderException - provider "BC" is not supported.
        java.security.InvalidAlgorithmParameterException - invalid EC curve is used.
      • importPrivateKeyAndCertificateFromPem

        public void importPrivateKeyAndCertificateFromPem​(java.lang.String privateKeyFileFullPathName,
                                                          java.lang.String certificateFileFullPathName)
                                                   throws java.security.cert.CertificateException,
                                                          java.io.IOException,
                                                          org.bouncycastle.pkcs.PKCSException,
                                                          org.bouncycastle.operator.OperatorCreationException
        Import the private key and certificate from pem-format files.

        If the private key file is protected by a passphrase, pass it in via setPassphrase(String)

        Parameters:
        privateKeyFileFullPathName - file name of private key
        certificateFileFullPathName - file name of certificate
        Throws:
        java.security.cert.CertificateException - fail to build the certificate from the certificate file.
        java.io.IOException - fail to read the certificate and/or the private key pem files.
        org.bouncycastle.operator.OperatorCreationException - fail to decrypt the encrypted PKCS8#8 private key file.
        org.bouncycastle.pkcs.PKCSException - fail to decrypt the encrypted PKCS8#8 private key file.