private X509Certificate createSelfSignedCert ( X500Name dn , String sigName , AlgorithmIdentifier sigAlgID , KeyPair keyPair ) throws Exception { final V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator ( ) ; certGen . setSerialNumber ( new ASN1Integer ( BigInteger . valueOf ( 1 ) ) ) ; certGen . setIssuer ( dn ) ; certGen . setSubject ( dn ) ; certGen . setStartDate ( new Time ( new Date ( System . currentTimeMillis ( ) - 1000L ) ) ) ; final Calendar c = Calendar . getInstance ( ) ; c . setTime ( new Date ( ) ) ; c . add ( Calendar . YEAR , 1 ) ; certGen . setEndDate ( new Time ( c . getTime ( ) ) ) ; certGen . setSignature ( sigAlgID ) ; certGen . setSubjectPublicKeyInfo ( SubjectPublicKeyInfo . getInstance ( keyPair . getPublic ( ) . getEncoded ( ) ) ) ; Signature sig = Signature . getInstance ( sigName ) ; sig . initSign ( keyPair . getPrivate ( ) ) ; sig . update ( certGen . generateTBSCertificate ( ) . getEncoded ( ASN1Encoding . DER ) ) ; TBSCertificate tbsCert = certGen . generateTBSCertificate ( ) ; ASN1EncodableVector v = new ASN1EncodableVector ( ) ; v . add ( tbsCert ) ; v . add ( sigAlgID ) ; v . add ( new DERBitString ( sig . sign ( ) ) ) ; final X509Certificate cert = ( X509Certificate ) CertificateFactory . getInstance ( "X.509" ) . generateCertificate ( new ByteArrayInputStream ( new DERSequence ( v ) . getEncoded ( ASN1Encoding . DER ) ) ) ; // check the certificate - this will confirm the encoded sig algorithm ID is correct. cert . verify ( keyPair . getPublic ( ) ) ; return cert ; }
Generate a self - signed certificate for dn using the provided signature algorithm and key pair .