private X509Certificate createCASignedCert ( PublicKey publicKey , X509Certificate certificateAuthorityCert , PrivateKey certificateAuthorityPrivateKey , PublicKey certificateAuthorityPublicKey , String domain , String [ ] subjectAlternativeNameDomains , String [ ] subjectAlternativeNameIps ) throws Exception { // signers name X500Name issuer = new X509CertificateHolder ( certificateAuthorityCert . getEncoded ( ) ) . getSubject ( ) ; // subjects name - the same as we are self signed. X500Name subject = new X500Name ( "CN=" + domain + ", O=MockServer, L=London, ST=England, C=UK" ) ; // serial BigInteger serial = BigInteger . valueOf ( new Random ( ) . nextInt ( Integer . MAX_VALUE ) ) ; // create the certificate - version 3 X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder ( issuer , serial , NOT_BEFORE , NOT_AFTER , subject , publicKey ) ; builder . addExtension ( Extension . subjectKeyIdentifier , false , createSubjectKeyIdentifier ( publicKey ) ) ; builder . addExtension ( Extension . basicConstraints , false , new BasicConstraints ( false ) ) ; // subject alternative name List < ASN1Encodable > subjectAlternativeNames = new ArrayList < ASN1Encodable > ( ) ; if ( subjectAlternativeNameDomains != null ) { subjectAlternativeNames . add ( new GeneralName ( GeneralName . dNSName , domain ) ) ; for ( String subjectAlternativeNameDomain : subjectAlternativeNameDomains ) { subjectAlternativeNames . add ( new GeneralName ( GeneralName . dNSName , subjectAlternativeNameDomain ) ) ; } } if ( subjectAlternativeNameIps != null ) { for ( String subjectAlternativeNameIp : subjectAlternativeNameIps ) { if ( IPAddress . isValidIPv6WithNetmask ( subjectAlternativeNameIp ) || IPAddress . isValidIPv6 ( subjectAlternativeNameIp ) || IPAddress . isValidIPv4WithNetmask ( subjectAlternativeNameIp ) || IPAddress . isValidIPv4 ( subjectAlternativeNameIp ) ) { subjectAlternativeNames . add ( new GeneralName ( GeneralName . iPAddress , subjectAlternativeNameIp ) ) ; } } } if ( subjectAlternativeNames . size ( ) > 0 ) { DERSequence subjectAlternativeNamesExtension = new DERSequence ( subjectAlternativeNames . toArray ( new ASN1Encodable [ subjectAlternativeNames . size ( ) ] ) ) ; builder . addExtension ( Extension . subjectAlternativeName , false , subjectAlternativeNamesExtension ) ; } X509Certificate cert = signCertificate ( builder , certificateAuthorityPrivateKey ) ; cert . checkValidity ( new Date ( ) ) ; cert . verify ( certificateAuthorityPublicKey ) ; return cert ; }
Create a server certificate for the given domain and subject alternative names signed by the given Certificate Authority .