static public X509Certificate duplicate ( X509Certificate cert ) { //log.info( "Duplicating cert={}.", cert ); X500Principal prince = cert . getSubjectX500Principal ( ) ; log . info ( "Principal={}." , prince . getName ( ) ) ; KeyPairGenerator kpg ; try { kpg = KeyPairGenerator . getInstance ( "RSA" ) ; } catch ( NoSuchAlgorithmException e1 ) { // TODO Auto-generated catch block throw new UnsupportedOperationException ( "OGTE TODO!" , e1 ) ; } KeyPair keyPair = kpg . generateKeyPair ( ) ; AlgorithmId alg ; try { alg = new AlgorithmId ( new ObjectIdentifier ( cert . getSigAlgOID ( ) ) ) ; } catch ( IOException e1 ) { // TODO Auto-generated catch block throw new UnsupportedOperationException ( "OGTE TODO!" , e1 ) ; } X509CertInfo info = new X509CertInfo ( ) ; try { info . set ( X509CertInfo . SUBJECT , new CertificateSubjectName ( new X500Name ( prince . getName ( ) ) ) ) ; info . set ( X509CertInfo . KEY , new CertificateX509Key ( keyPair . getPublic ( ) ) ) ; info . set ( X509CertInfo . VALIDITY , new CertificateValidity ( cert . getNotBefore ( ) , cert . getNotAfter ( ) ) ) ; info . set ( X509CertInfo . ISSUER , new CertificateIssuerName ( new X500Name ( prince . getName ( ) ) ) ) ; info . set ( X509CertInfo . ALGORITHM_ID , new CertificateAlgorithmId ( alg ) ) ; info . set ( X509CertInfo . SERIAL_NUMBER , new CertificateSerialNumber ( cert . getSerialNumber ( ) ) ) ; info . set ( X509CertInfo . VERSION , new CertificateVersion ( cert . getVersion ( ) - 1 ) ) ; //info.set( x509CertInfo.EXTENSIONS, cert.get) } catch ( CertificateException | IOException e ) { // TODO Auto-generated catch block throw new UnsupportedOperationException ( "OGTE TODO!" , e ) ; } log . info ( "Cert info={}." , info ) ; X509CertImpl newCert = new X509CertImpl ( info ) ; try { newCert . sign ( keyPair . getPrivate ( ) , alg . getName ( ) ) ; } catch ( InvalidKeyException | CertificateException | NoSuchAlgorithmException | NoSuchProviderException | SignatureException e ) { // TODO Auto-generated catch block throw new UnsupportedOperationException ( "OGTE TODO!" , e ) ; } log . info ( "Returning new cert={}." , newCert ) ; return newCert ; }
Create a self - signed certificate that duplicates as many of the given cert s fields as possible .