List of usage examples for org.bouncycastle.asn1.x509 Certificate getEncoded
public byte[] getEncoded() throws IOException
From source file:net.wstech2.me.httpsclient.CertificateValidatorUtils.java
License:Apache License
/** * /*from w w w .j av a2 s .c o m*/ * Inspected and display various informations from the Certificate passed as * parameter. Keys are presented in HEX values and ASN1 structures dumped * using ASN1Dump.dumpAsString. * * This method is intended for debug purposes only. * * * @param cert * The X509CertificateStructure to be inspected. * */ public static void dumpCertificateInfo(org.bouncycastle.asn1.x509.Certificate cert) { boolean valid = false; TBSCertificate tbs = cert.getTBSCertificate(); RSAEngine engine = new RSAEngine(); SHA1Digest digest = new SHA1Digest(); GenericSigner signer = new GenericSigner((engine), digest); RSAPublicKey signingKey; try { signingKey = RSAPublicKey.getInstance(cert.getSubjectPublicKeyInfo().parsePublicKey()); HttpsConnectionUtils.logDebug("Public Key:[[" + cert.getSubjectPublicKeyInfo().parsePublicKey() + "]]"); RSAKeyParameters keySpec = new RSAKeyParameters(false, signingKey.getModulus(), signingKey.getPublicExponent()); signer.init(false, keySpec); HttpsConnectionUtils.logDebug("TBS DER object:[[" + tbs.getEncoded("DER") + "]]"); signer.update(tbs.getEncoded(), 0, tbs.getEncoded().length); valid = signer.verifySignature(cert.getSignature().getBytes()); HttpsConnectionUtils.logDebug("signer.verifySignature:[[" + valid + "]]"); SHA1Digest d2 = new SHA1Digest(); d2.update(tbs.getEncoded("DER"), 0, tbs.getEncoded("DER").length); byte[] hash = new byte[d2.getDigestSize()]; d2.doFinal(hash, 0); HttpsConnectionUtils.logDebug("tbs.getDEREncoded() HASH:[[" + new String(Hex.encode(hash)) + "]]"); DEROctetString asn1Hash = new DEROctetString(hash); HttpsConnectionUtils.logDebug( "ASN1 DEROctetString hash:[[" + new String(Hex.encode(asn1Hash.getEncoded("DER"))) + "]]"); d2 = new SHA1Digest(); d2.update(cert.getEncoded(), 0, cert.getEncoded().length); hash = new byte[d2.getDigestSize()]; d2.doFinal(hash, 0); HttpsConnectionUtils.logDebug("cert.getEncoded() HASH:[[" + new String(Hex.encode(hash)) + "]]"); byte[] signature = cert.getSignature().getBytes(); HttpsConnectionUtils .logDebug("cert.getSignature().getBytes():[[" + new String(Hex.encode(signature)) + "]]"); PKCS1Encoding engine2 = new PKCS1Encoding(new RSAEngine()); engine2.init(false, keySpec); byte[] decryptedHash = engine2.processBlock(signature, 0, signature.length); HttpsConnectionUtils.logDebug("decryptedHash:[[" + new String(Hex.encode(decryptedHash)) + "]]"); ASN1Object o = ASN1Primitive.fromByteArray(decryptedHash); HttpsConnectionUtils.logDebug( "decryptedHash.getDEREncoded():[[" + new String(Hex.encode(o.getEncoded("DER"))) + "]]"); HttpsConnectionUtils.logDebug( "ASN1Dump.dumpAsString(decryptedHash,true):[[" + ASN1Dump.dumpAsString(o, true) + "]]"); HttpsConnectionUtils.logDebug("engine.getInputBlockSize():[[" + engine2.getInputBlockSize() + "]]"); HttpsConnectionUtils.logDebug("engine.getOutputBlockSize():[[" + engine2.getOutputBlockSize() + "]]"); ASN1Sequence asn1SignSeq = (ASN1Sequence) ASN1Sequence.fromByteArray(decryptedHash); HttpsConnectionUtils .logDebug("Signature ASN1 Sequence:[[" + ASN1Dump.dumpAsString(asn1SignSeq, true) + "]]"); AlgorithmIdentifier algorithm = AlgorithmIdentifier.getInstance(asn1SignSeq.getObjectAt(0)); HttpsConnectionUtils.logDebug("AlgorithmIdentifier:[[" + ASN1Dump.dumpAsString(algorithm, true) + "]]"); DEROctetString signedHash = (DEROctetString) DEROctetString.getInstance(asn1SignSeq.getObjectAt(1)); HttpsConnectionUtils.logDebug("signedHash:[[" + ASN1Dump.dumpAsString(signedHash, true) + "]]"); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.codice.ddf.security.ocsp.checker.OcspChecker.java
License:Open Source License
/** * Returns an {@link X509CertificateHolder} containing the issuer of the given {@param name}. * Search is performed in the given {@param truststore}. * * @param name - the {@link X500Name} of the issuer. * @param truststore - the {@link KeyStore} to check. * @return {@link X509CertificateHolder} of the certificate with the given {@param name}. * @throws OcspCheckerException if the {@param name} cannot be found in the {@param truststore}. */// w w w. j av a 2s.com private X509CertificateHolder getCertFromTruststoreWithX500Name(X500Name name, KeyStore truststore) throws OcspCheckerException { Enumeration<String> aliases; try { aliases = truststore.aliases(); } catch (KeyStoreException e) { throw new OcspCheckerException("Problem getting aliases from truststore." + NOT_VERIFIED_MSG, e); } while (aliases.hasMoreElements()) { String currentAlias = aliases.nextElement(); try { java.security.cert.Certificate currentCert = truststore.getCertificate(currentAlias); X509CertificateHolder currentCertHolder = new X509CertificateHolder(currentCert.getEncoded()); X500Name currentName = currentCertHolder.getSubject(); if (name.equals(currentName)) { return currentCertHolder; } } catch (CertificateEncodingException | IOException | KeyStoreException e) { LOGGER.debug("Problem loading truststore certificate." + CONTINUING_MSG, e); } } throw new OcspCheckerException( String.format("Could not find cert matching X500Name of %s.", name) + NOT_VERIFIED_MSG); }
From source file:org.jboss.capedwarf.appidentity.CertificateGenerator.java
License:Open Source License
private X509Certificate convertToJavaCertificate(Certificate certificate) throws CertificateException, IOException { InputStream is = new ByteArrayInputStream(certificate.getEncoded()); try {//from ww w. j a v a 2 s . c om return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(is); } finally { is.close(); } }
From source file:org.jruby.ext.openssl.x509store.X509AuxCertificate.java
License:LGPL
public X509AuxCertificate(Certificate wrap) throws IOException, CertificateException { super();/*from w ww.j av a 2 s .c o m*/ CertificateFactory cf = CertificateFactory.getInstance("X.509"); ByteArrayInputStream bis = new ByteArrayInputStream(wrap.getEncoded()); this.wrap = (X509Certificate) cf.generateCertificate(bis); this.aux = null; }
From source file:org.opendaylight.capwap.dtls.DtlsUtils.java
License:Open Source License
static String fingerprint(org.bouncycastle.asn1.x509.Certificate c) throws IOException { byte[] der = c.getEncoded(); byte[] sha1 = sha256DigestOf(der); byte[] hexBytes = Hex.encode(sha1); String hex = new String(hexBytes, "ASCII").toUpperCase(); StringBuffer fp = new StringBuffer(); int i = 0;/* ww w . java 2s . c o m*/ fp.append(hex.substring(i, i + 2)); while ((i += 2) < hex.length()) { fp.append(':'); fp.append(hex.substring(i, i + 2)); } return fp.toString(); }
From source file:org.opendaylight.snbi.southplugin.CertificateMgmt.java
License:Open Source License
public static X509Certificate signCSR(CertificationRequest inputCSR, PrivateKey caPrivate, KeyPair pair) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException, IOException, OperatorCreationException, CertException { PKCS10CertificationRequest pk10Holder = new PKCS10CertificationRequest(inputCSR); X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE); // builder.addRDN(BCStyle.C, defaults.get("COUNTRY")); // builder.addRDN(BCStyle.O, defaults.get("ORGANIZATION")); //builder.addRDN(BCStyle.ST, defaults.get("STATE")); // builder.addRDN(BCStyle.T, defaults.get("TITLE")); builder.addRDN(BCStyle.CN, inputCSR.getSignature()); Calendar now = Calendar.getInstance(); Date notBefore = now.getTime(); now.add(Calendar.YEAR, 3);//from w w w. ja va 2s. c om Date notAfter = now.getTime(); BigInteger serial = BigInteger.valueOf(System.currentTimeMillis()); X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(builder.build(), serial, notBefore, notAfter, builder.build(), pair.getPublic()); ContentSigner sigGen = new JcaContentSignerBuilder( CertManagerConstants.CERT_ALGORITHM.SHA1withRSA.toString()).setProvider(CertManagerConstants.BC) .build(pair.getPrivate()); X509CertificateHolder holder = certGen.build(sigGen); Certificate eeX509CertificateStructure = holder.toASN1Structure(); CertificateFactory cf = null; try { cf = CertificateFactory.getInstance(CertManagerConstants.CERT_TYPE.X509.toString(), CertManagerConstants.BC); } catch (CertificateException e) { e.printStackTrace(); } // Read Certificate InputStream is1 = new ByteArrayInputStream(eeX509CertificateStructure.getEncoded()); X509Certificate theCert = null; try { theCert = (X509Certificate) cf.generateCertificate(is1); } catch (CertificateException e) { e.printStackTrace(); } is1.close(); return theCert; }
From source file:org.signserver.module.pdfsigner.PDFSignerUnitTest.java
License:Open Source License
/** * Tests that our assumption that an increase of n bytes in a certificate * does not lead to more than an increase of n bytes in the PKCS#7 structure. * * This should never fail unless we upgrade BouncyCastle and the behavior * changes.//w w w .j a v a 2 s . c o m */ public void test14EstimatedP7Size_increaseCertSize() throws Exception { final int somethingLargeEnough = 31000; KeyPair issuerKeyPair = CryptoUtils.generateRSA(1024); KeyPair signerKeyPair = CryptoUtils.generateRSA(1024); PrivateKey signerPrivKey = signerKeyPair.getPrivate(); byte[] extensionBytes = new byte[0]; int referenceIssuerCertSize; int referenceSize; int actualP7Size; // Create initial certificates Certificate issuerCert = converter.getCertificate(new CertBuilder() .setIssuerPrivateKey(issuerKeyPair.getPrivate()).setSubjectPublicKey(issuerKeyPair.getPublic()) .setSubject("CN=Issuer1").setIssuer("CN=Issuer1") .addExtension( new CertExt(new ASN1ObjectIdentifier("1.2.3.4"), false, new DERBitString(extensionBytes))) .build()); referenceIssuerCertSize = issuerCert.getEncoded().length; Certificate signerCert = converter.getCertificate(new CertBuilder() .setIssuerPrivateKey(issuerKeyPair.getPrivate()).setSubjectPublicKey(signerKeyPair.getPublic()) .setSubject("CN=Signer").setIssuer("CN=Issuer1").build()); // We will only variate the issuer certificate size // so the other parameters are not important for this test CRL[] crlList = new CRL[0]; MockedTSAClient tsc = new MockedTSAClient(1234); byte[] ocsp = "OOOOOOOO".getBytes(); // Test 1: First test is the reference test Certificate[] certChain = new Certificate[] { signerCert, issuerCert }; actualP7Size = getActualP7Size(signerPrivKey, somethingLargeEnough, certChain, crlList, ocsp, tsc); referenceSize = actualP7Size; LOG.debug("referenceSize: " + actualP7Size); LOG.debug("referenceIssuerCertSize: " + referenceIssuerCertSize); // Test 2: Increase the size of the certificate with 1 byte and test // that the final P7 does not increases with more than 1 byte extensionBytes = new byte[1]; issuerCert = converter.getCertificate(new CertBuilder().setIssuerPrivateKey(issuerKeyPair.getPrivate()) .setSubjectPublicKey(issuerKeyPair.getPublic()).setSubject("CN=Issuer1").setIssuer("CN=Issuer1") .addExtension( new CertExt(new ASN1ObjectIdentifier("1.2.3.4"), false, new DERBitString(extensionBytes))) .build()); certChain = new Certificate[] { signerCert, issuerCert }; if (issuerCert.getEncoded().length != referenceIssuerCertSize + 1) { throw new Exception("The test should have increased the certificate size by 1 byte"); } actualP7Size = getActualP7Size(signerPrivKey, somethingLargeEnough, certChain, crlList, ocsp, tsc); assertEquals("new size 1 byte larger", referenceSize + 1, actualP7Size); // Test 2: Increase the size of the certificate with 37 bytes and test // that the final P7 does not increases with more than 37 bytes extensionBytes = new byte[37]; issuerCert = converter.getCertificate(new CertBuilder().setIssuerPrivateKey(issuerKeyPair.getPrivate()) .setSubjectPublicKey(issuerKeyPair.getPublic()).setSubject("CN=Issuer1").setIssuer("CN=Issuer1") .addExtension( new CertExt(new ASN1ObjectIdentifier("1.2.3.4"), false, new DERBitString(extensionBytes))) .build()); certChain = new Certificate[] { signerCert, issuerCert }; if (issuerCert.getEncoded().length != referenceIssuerCertSize + 37) { throw new Exception("The test should have increased the certificate size by 37 bytes but was: " + issuerCert.getEncoded().length); } actualP7Size = getActualP7Size(signerPrivKey, somethingLargeEnough, certChain, crlList, ocsp, tsc); assertEquals("new size 37 bytes larger", referenceSize + 37, actualP7Size); // Test 2: Increase the size of the certificate with at least 10000 bytes and test // that the final P7 does not increases more than the certificate // (it turned out that increasing the certificate with 10000 bytes actually made it even larger, // however that is not important in this case) extensionBytes = new byte[10000]; issuerCert = converter.getCertificate(new CertBuilder().setIssuerPrivateKey(issuerKeyPair.getPrivate()) .setSubjectPublicKey(issuerKeyPair.getPublic()).setSubject("CN=Issuer1").setIssuer("CN=Issuer1") .addExtension( new CertExt(new ASN1ObjectIdentifier("1.2.3.4"), false, new DERBitString(extensionBytes))) .build()); certChain = new Certificate[] { signerCert, issuerCert }; int certIncrease = issuerCert.getEncoded().length - referenceIssuerCertSize; LOG.debug("increased certificate size with: " + certIncrease); if (certIncrease < 10000) { throw new Exception("The test should have increased the certificate with at least 10000 bytes but was: " + issuerCert.getEncoded().length); } actualP7Size = getActualP7Size(signerPrivKey, somethingLargeEnough, certChain, crlList, ocsp, tsc); assertEquals("new larger size", referenceSize + certIncrease, actualP7Size); referenceSize = actualP7Size; // Test 3: Increase the size of the certificate with at least 30123 bytes and test // that the final P7 does not increases more than the certificate extensionBytes = new byte[30123]; issuerCert = converter.getCertificate(new CertBuilder().setIssuerPrivateKey(issuerKeyPair.getPrivate()) .setSubjectPublicKey(issuerKeyPair.getPublic()).setSubject("CN=Issuer1").setIssuer("CN=Issuer1") .addExtension( new CertExt(new ASN1ObjectIdentifier("1.2.3.4"), false, new DERBitString(extensionBytes))) .build()); certChain = new Certificate[] { signerCert, issuerCert }; certIncrease = issuerCert.getEncoded().length - referenceIssuerCertSize; LOG.debug("increased certificate size with: " + certIncrease); if (certIncrease < 30123) { throw new Exception("The test should have increased the certificate with at least 30123 bytes but was: " + issuerCert.getEncoded().length); } actualP7Size = getActualP7Size(signerPrivKey, somethingLargeEnough, certChain, crlList, ocsp, tsc); // It turns out that the P7 might use less size than the increase in the certificate assertTrue("new larger size", referenceSize + certIncrease >= actualP7Size); //referenceSize = actualP7Size; }
From source file:org.xipki.ca.client.shell.loadtest.CALoadTestRevoke.java
License:Open Source License
public CALoadTestRevoke(final CAClient caClient, final Certificate caCert, final DataSourceWrapper caDataSource, final int maxCerts, final int n) throws Exception { ParamChecker.assertNotNull("caClient", caClient); ParamChecker.assertNotNull("caCert", caCert); ParamChecker.assertNotNull("caDataSource", caDataSource); if (n < 1) { throw new IllegalArgumentException("non-positive n " + n + " is not allowed"); }//from w w w . ja v a2s .c om this.n = n; this.caClient = caClient; this.caDataSource = caDataSource; this.caSubject = caCert.getSubject(); this.maxCerts = maxCerts; if (caCert.getIssuer().equals(caCert.getSubject())) { this.excludeSerials.add(caCert.getSerialNumber().getPositiveValue().longValue()); } String sha1Fp = SecurityUtil.sha1sum(caCert.getEncoded()); String sql = "SELECT ID FROM CS_CA WHERE FP_CERT='" + sha1Fp + "'"; Statement stmt = caDataSource.getConnection().createStatement(); try { ResultSet rs = stmt.executeQuery(sql); if (rs.next()) { caInfoId = rs.getInt("ID"); } else { throw new Exception("CA Certificate and database configuration does not match"); } rs.close(); sql = "SELECT MIN(SERIAL) FROM CERT WHERE REVOKED=0 AND CA_ID=" + caInfoId; rs = stmt.executeQuery(sql); rs.next(); minSerial = rs.getLong(1); nextStartSerial = minSerial; sql = "SELECT MAX(SERIAL) FROM CERT WHERE REVOKED=0 AND CA_ID=" + caInfoId; rs = stmt.executeQuery(sql); rs.next(); maxSerial = rs.getLong(1); } finally { caDataSource.releaseResources(stmt, null); } }
From source file:org.xipki.ca.server.impl.X509CA.java
License:Open Source License
private X509CertificateInfo intern_generateCertificate(final boolean requestedByRA, final RequestorInfo requestor, final String certprofileLocalName, final String user, X500Name requestedSubject, SubjectPublicKeyInfo publicKeyInfo, Date notBefore, Date notAfter, final org.bouncycastle.asn1.x509.Extensions extensions, final boolean keyUpdate) throws OperationException { if (caInfo.getRevocationInfo() != null) { throw new OperationException(ErrorCode.NOT_PERMITTED, "CA is revoked"); }/* www. j av a2 s. co m*/ IdentifiedX509Certprofile certprofile = getX509Certprofile(certprofileLocalName); if (certprofile == null) { throw new OperationException(ErrorCode.UNKNOWN_CERT_PROFILE, "unknown cert profile " + certprofileLocalName); } ConcurrentContentSigner signer = caInfo.getSigner(certprofile.getSignatureAlgorithms()); if (signer == null) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "CA does not support any signature algorithm restricted by the cert profile"); } final String certprofileName = certprofile.getName(); if (certprofile.getVersion() != X509CertVersion.V3) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "unknown cert version " + certprofile); } if (certprofile.isOnlyForRA() && requestedByRA == false) { throw new OperationException(ErrorCode.INSUFFICIENT_PERMISSION, "profile " + certprofileName + " not applied to non-RA"); } requestedSubject = removeEmptyRDNs(requestedSubject); if (certprofile.isSerialNumberInReqPermitted() == false) { RDN[] rdns = requestedSubject.getRDNs(ObjectIdentifiers.DN_SN); if (rdns != null && rdns.length > 0) { throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "subjectDN SerialNumber in request is not permitted"); } } notBefore = certprofile.getNotBefore(notBefore); if (notBefore == null) { notBefore = new Date(); } if (certprofile.hasMidnightNotBefore()) { notBefore = setToMidnight(notBefore, certprofile.getTimezone()); } if (notBefore.before(caInfo.getNotBefore())) { notBefore = caInfo.getNotBefore(); if (certprofile.hasMidnightNotBefore()) { notBefore = setToMidnight(new Date(notBefore.getTime() + DAY), certprofile.getTimezone()); } } long t = caInfo.getNoNewCertificateAfter(); if (notBefore.getTime() > t) { throw new OperationException(ErrorCode.NOT_PERMITTED, "CA is not permitted to issue certifate after " + new Date(t)); } try { publicKeyInfo = X509Util.toRfc3279Style(publicKeyInfo); } catch (InvalidKeySpecException e) { throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "invalid SubjectPublicKeyInfo"); } // public key try { publicKeyInfo = certprofile.checkPublicKey(publicKeyInfo); } catch (BadCertTemplateException e) { throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, e.getMessage()); } Date gSMC_KFirstNotBefore = null; if (certprofile.getSpecialCertprofileBehavior() == SpecialX509CertprofileBehavior.gematik_gSMC_K) { gSMC_KFirstNotBefore = notBefore; RDN[] cnRDNs = requestedSubject.getRDNs(ObjectIdentifiers.DN_CN); if (cnRDNs != null && cnRDNs.length > 0) { String requestedCN = X509Util.rdnValueToString(cnRDNs[0].getFirst().getValue()); Long gsmckFirstNotBeforeInSecond = certstore.getNotBeforeOfFirstCertStartsWithCN(requestedCN, certprofileName); if (gsmckFirstNotBeforeInSecond != null) { gSMC_KFirstNotBefore = new Date(gsmckFirstNotBeforeInSecond * MS_PER_SECOND); } // append the commonName with '-' + yyyyMMdd SimpleDateFormat dateF = new SimpleDateFormat("yyyyMMdd"); dateF.setTimeZone(new SimpleTimeZone(0, "Z")); String yyyyMMdd = dateF.format(gSMC_KFirstNotBefore); String suffix = "-" + yyyyMMdd; // append the -yyyyMMdd to the commonName RDN[] rdns = requestedSubject.getRDNs(); for (int i = 0; i < rdns.length; i++) { if (ObjectIdentifiers.DN_CN.equals(rdns[i].getFirst().getType())) { rdns[i] = new RDN(ObjectIdentifiers.DN_CN, new DERUTF8String(requestedCN + suffix)); } } requestedSubject = new X500Name(rdns); } } // end if // subject SubjectInfo subjectInfo; try { subjectInfo = certprofile.getSubject(requestedSubject); } catch (CertprofileException e) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "exception in cert profile " + certprofileName); } catch (BadCertTemplateException e) { throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, e.getMessage()); } X500Name grantedSubject = subjectInfo.getGrantedSubject(); // make sure that the grantedSubject does not equal the CA's subject if (grantedSubject.equals(caInfo.getPublicCAInfo().getX500Subject())) { throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate with the same subject as CA is not allowed"); } DuplicationMode keyMode = caInfo.getDuplicateKeyMode(); if (keyMode == DuplicationMode.PERMITTED && certprofile.isDuplicateKeyPermitted() == false) { keyMode = DuplicationMode.FORBIDDEN_WITHIN_PROFILE; } DuplicationMode subjectMode = caInfo.getDuplicateSubjectMode(); if (subjectMode == DuplicationMode.PERMITTED && certprofile.isDuplicateSubjectPermitted() == false) { subjectMode = DuplicationMode.FORBIDDEN_WITHIN_PROFILE; } String sha1FpSubject = X509Util.sha1sum_canonicalized_name(grantedSubject); String grandtedSubjectText = X509Util.getRFC4519Name(grantedSubject); byte[] subjectPublicKeyData = publicKeyInfo.getPublicKeyData().getBytes(); String sha1FpPublicKey = SecurityUtil.sha1sum(subjectPublicKeyData); if (keyUpdate) { CertStatus certStatus = certstore.getCertStatusForSubject(caInfo.getCertificate(), grantedSubject); if (certStatus == CertStatus.Revoked) { throw new OperationException(ErrorCode.CERT_REVOKED); } else if (certStatus == CertStatus.Unknown) { throw new OperationException(ErrorCode.UNKNOWN_CERT); } } else { // try to get certificate with the same subject, key and certificate profile SubjectKeyProfileBundle bundle = certstore.getLatestCert(caInfo.getCertificate(), sha1FpSubject, sha1FpPublicKey, certprofileName); if (bundle != null) { /* * If there exists a certificate whose public key, subject and profile match the request, * returns the certificate if it is not revoked, otherwise OperationException with * ErrorCode CERT_REVOKED will be thrown */ if (bundle.isRevoked()) { throw new OperationException(ErrorCode.CERT_REVOKED); } else { X509CertWithDBCertId issuedCert = certstore.getCertForId(bundle.getCertId()); if (issuedCert == null) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "could not find certificate in table RAWCERT for CERT_ID " + bundle.getCertId()); } else { X509CertificateInfo certInfo; try { certInfo = new X509CertificateInfo(issuedCert, caInfo.getCertificate(), subjectPublicKeyData, certprofileName); } catch (CertificateEncodingException e) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "could not construct CertificateInfo: " + e.getMessage()); } certInfo.setAlreadyIssued(true); return certInfo; } } } // end if(bundle) if (keyMode != DuplicationMode.PERMITTED) { if (keyMode == DuplicationMode.FORBIDDEN) { if (certstore.isCertForKeyIssued(caInfo.getCertificate(), sha1FpPublicKey)) { throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate for the given public key already issued"); } } else if (keyMode == DuplicationMode.FORBIDDEN_WITHIN_PROFILE) { if (certstore.isCertForKeyIssued(caInfo.getCertificate(), sha1FpPublicKey, certprofileName)) { throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate for the given public key and profile " + certprofileName + " already issued"); } } else { throw new RuntimeException("should not reach here, unknown key DuplicationMode " + keyMode); } } // end if(keyMode) if (subjectMode != DuplicationMode.PERMITTED) { final boolean incSerial = certprofile.incSerialNumberIfSubjectExists(); final boolean certIssued; if (subjectMode == DuplicationMode.FORBIDDEN) { certIssued = certstore.isCertForSubjectIssued(caInfo.getCertificate(), sha1FpSubject); if (certIssued && incSerial == false) { throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate for the given subject " + grandtedSubjectText + " already issued"); } } else if (subjectMode == DuplicationMode.FORBIDDEN_WITHIN_PROFILE) { certIssued = certstore.isCertForSubjectIssued(caInfo.getCertificate(), sha1FpSubject, certprofileName); if (certIssued && incSerial == false) { throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate for the given subject " + grandtedSubjectText + " and profile " + certprofileName + " already issued"); } } else { throw new RuntimeException("should not reach here, unknown subject DuplicationMode " + keyMode); } // end if(subjectMode) if (certIssued) { String latestSN; try { Object[] objs = incSerialNumber(certprofile, grantedSubject, null); latestSN = certstore.getLatestSN((X500Name) objs[0]); } catch (BadFormatException e) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "BadFormatException: " + e.getMessage()); } boolean foundUniqueSubject = false; // maximal 100 tries for (int i = 0; i < 100; i++) { try { Object[] objs = incSerialNumber(certprofile, grantedSubject, latestSN); grantedSubject = (X500Name) objs[0]; latestSN = (String) objs[1]; } catch (BadFormatException e) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "BadFormatException: " + e.getMessage()); } foundUniqueSubject = (certstore.certIssuedForSubject(caInfo.getCertificate(), X509Util.sha1sum_canonicalized_name(grantedSubject)) == false); if (foundUniqueSubject) { break; } } if (foundUniqueSubject == false) { throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate for the given subject " + grandtedSubjectText + " and profile " + certprofileName + " already issued, and could not create new unique serial number"); } } // end if(certIssued) } } // end if(subjectMode != DuplicationMode.PERMITTED) try { boolean addedCertInProcess = certstore.addCertInProcess(sha1FpPublicKey, sha1FpSubject); if (addedCertInProcess == false) { throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate with the given subject " + grandtedSubjectText + " and/or public key already in process"); } StringBuilder msgBuilder = new StringBuilder(); if (subjectInfo.getWarning() != null) { msgBuilder.append(", ").append(subjectInfo.getWarning()); } CertValidity validity = certprofile.getValidity(); if (validity == null) { validity = caInfo.getMaxValidity(); } else if (validity.compareTo(caInfo.getMaxValidity()) > 0) { validity = caInfo.getMaxValidity(); } Date maxNotAfter = validity.add(notBefore); Date origMaxNotAfter = maxNotAfter; if (certprofile.getSpecialCertprofileBehavior() == SpecialX509CertprofileBehavior.gematik_gSMC_K) { String s = certprofile.getParameter(SpecialX509CertprofileBehavior.PARAMETER_MAXLIFTIME); long maxLifetimeInDays = Long.parseLong(s); Date maxLifetime = new Date( gSMC_KFirstNotBefore.getTime() + maxLifetimeInDays * DAY - MS_PER_SECOND); if (maxNotAfter.after(maxLifetime)) { maxNotAfter = maxLifetime; } } if (notAfter != null) { if (notAfter.after(maxNotAfter)) { notAfter = maxNotAfter; msgBuilder.append(", NotAfter modified"); } } else { notAfter = maxNotAfter; } if (notAfter.after(caInfo.getNotAfter())) { ValidityMode mode = caInfo.getValidityMode(); if (mode == ValidityMode.CUTOFF) { notAfter = caInfo.getNotAfter(); } else if (mode == ValidityMode.STRICT) { throw new OperationException(ErrorCode.NOT_PERMITTED, "notAfter outside of CA's validity is not permitted"); } else if (mode == ValidityMode.LAX) { // permitted } else { throw new RuntimeException("should not reach here, unknown CA ValidityMode " + mode); } // end if(mode) } // end if(notAfter) if (certprofile.hasMidnightNotBefore() && maxNotAfter.equals(origMaxNotAfter) == false) { Calendar c = Calendar.getInstance(certprofile.getTimezone()); c.setTime(new Date(notAfter.getTime() - DAY)); c.set(Calendar.HOUR_OF_DAY, 23); c.set(Calendar.MINUTE, 59); c.set(Calendar.SECOND, 59); c.set(Calendar.MILLISECOND, 0); notAfter = c.getTime(); } try { RdnUpperBounds.checkUpperBounds(grantedSubject); } catch (BadCertTemplateException e) { throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, e.getMessage()); } X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( caInfo.getPublicCAInfo().getX500Subject(), caInfo.nextSerial(), notBefore, notAfter, grantedSubject, publicKeyInfo); X509CertificateInfo ret; try { X509CrlSignerEntryWrapper crlSigner = getCrlSigner(); X509Certificate crlSignerCert = crlSigner == null ? null : crlSigner.getCert(); ExtensionValues extensionTuples = certprofile.getExtensions(requestedSubject, extensions, publicKeyInfo, caInfo.getPublicCAInfo(), crlSignerCert); if (extensionTuples != null) { for (ASN1ObjectIdentifier extensionType : extensionTuples.getExtensionTypes()) { ExtensionValue extValue = extensionTuples.getExtensionValue(extensionType); certBuilder.addExtension(extensionType, extValue.isCritical(), extValue.getValue()); } } ContentSigner contentSigner; try { contentSigner = signer.borrowContentSigner(); } catch (NoIdleSignerException e) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "NoIdleSignerException: " + e.getMessage()); } Certificate bcCert; try { bcCert = certBuilder.build(contentSigner).toASN1Structure(); } finally { signer.returnContentSigner(contentSigner); } byte[] encodedCert = bcCert.getEncoded(); X509Certificate cert = (X509Certificate) cf .engineGenerateCertificate(new ByteArrayInputStream(encodedCert)); if (verifySignature(cert) == false) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "could not verify the signature of generated certificate"); } X509CertWithDBCertId certWithMeta = new X509CertWithDBCertId(cert, encodedCert); ret = new X509CertificateInfo(certWithMeta, caInfo.getCertificate(), subjectPublicKeyData, certprofileName); ret.setUser(user); ret.setRequestor(requestor); if (intern_publishCertificate(ret) == 1) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "could not save certificate"); } } catch (BadCertTemplateException e) { throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, e.getMessage()); } catch (Throwable t2) { final String message = "could not generate certificate"; if (LOG.isErrorEnabled()) { LOG.error(LogUtil.buildExceptionLogFormat(message), t2.getClass().getName(), t2.getMessage()); } LOG.debug(message, t2); throw new OperationException(ErrorCode.SYSTEM_FAILURE, t2.getClass().getName() + ": " + t2.getMessage()); } if (msgBuilder.length() > 2) { ret.setWarningMessage(msgBuilder.substring(2)); } return ret; } finally { try { certstore.delteCertInProcess(sha1FpPublicKey, sha1FpSubject); } catch (OperationException e) { } } }
From source file:org.xipki.ca.server.impl.X509SelfSignedCertBuilder.java
License:Open Source License
private static X509Certificate generateCertificate(final ConcurrentContentSigner signer, final IdentifiedX509Certprofile certprofile, final CertificationRequest p10Request, final long serialNumber, SubjectPublicKeyInfo publicKeyInfo, final List<String> cacertUris, final List<String> ocspUris, final List<String> crlUris, final List<String> deltaCrlUris) throws OperationException { try {/*from w w w . j a va2 s . c o m*/ publicKeyInfo = X509Util.toRfc3279Style(publicKeyInfo); } catch (InvalidKeySpecException e) { LOG.warn("SecurityUtil.toRfc3279Style", e); throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, e.getMessage()); } try { certprofile.checkPublicKey(publicKeyInfo); } catch (BadCertTemplateException e) { LOG.warn("certprofile.checkPublicKey", e); throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, e.getMessage()); } X500Name requestedSubject = p10Request.getCertificationRequestInfo().getSubject(); SubjectInfo subjectInfo; // subject try { subjectInfo = certprofile.getSubject(requestedSubject); } catch (CertprofileException e) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "exception in cert profile " + certprofile.getName()); } catch (BadCertTemplateException e) { LOG.warn("certprofile.getSubject", e); throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, e.getMessage()); } Date notBefore = certprofile.getNotBefore(null); if (notBefore == null) { notBefore = new Date(); } CertValidity validity = certprofile.getValidity(); if (validity == null) { throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "no validity specified in the profile " + certprofile.getName()); } Date notAfter = validity.add(notBefore); X500Name grantedSubject = subjectInfo.getGrantedSubject(); BigInteger _serialNumber = BigInteger.valueOf(serialNumber); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(grantedSubject, _serialNumber, notBefore, notAfter, grantedSubject, publicKeyInfo); PublicCAInfo publicCaInfo = new PublicCAInfo(grantedSubject, _serialNumber, null, null, cacertUris, ocspUris, crlUris, deltaCrlUris); Extensions extensions = null; ASN1Set attrs = p10Request.getCertificationRequestInfo().getAttributes(); for (int i = 0; i < attrs.size(); i++) { Attribute attr = Attribute.getInstance(attrs.getObjectAt(i)); if (PKCSObjectIdentifiers.pkcs_9_at_extensionRequest.equals(attr.getAttrType())) { extensions = Extensions.getInstance(attr.getAttributeValues()[0]); } } try { addExtensions(certBuilder, certprofile, requestedSubject, extensions, publicKeyInfo, publicCaInfo); ContentSigner contentSigner = signer.borrowContentSigner(); Certificate bcCert; try { bcCert = certBuilder.build(contentSigner).toASN1Structure(); } finally { signer.returnContentSigner(contentSigner); } byte[] encodedCert = bcCert.getEncoded(); CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC"); return (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(encodedCert)); } catch (BadCertTemplateException e) { throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, e.getMessage()); } catch (NoIdleSignerException | CertificateException | IOException | CertprofileException | NoSuchAlgorithmException | NoSuchProviderException e) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, e.getClass().getName() + ": " + e.getMessage()); } }