List of usage examples for org.bouncycastle.asn1.x509 Certificate getTBSCertificate
public TBSCertificate getTBSCertificate()
From source file:net.sf.keystore_explorer.crypto.csr.pkcs10.Pkcs10Util.java
License:Open Source License
/** * Create a PKCS #10 certificate signing request (CSR) using the supplied * certificate, private key and signature algorithm. * * @param cert//from w ww .j ava 2 s . c o m * The certificate * @param privateKey * The private key * @param signatureType * Signature * @param challenge * Challenge, optional, pass null if not required * @param unstructuredName * An optional company name, pass null if not required * @param useExtensions * Use extensions from cert for extensionRequest attribute? * @throws CryptoException * If there was a problem generating the CSR * @return The CSR */ public static PKCS10CertificationRequest generateCsr(X509Certificate cert, PrivateKey privateKey, SignatureType signatureType, String challenge, String unstructuredName, boolean useExtensions, Provider provider) throws CryptoException { try { JcaPKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder( cert.getSubjectX500Principal(), cert.getPublicKey()); // add challenge attribute if (challenge != null) { // PKCS#9 2.0: SHOULD use UTF8String encoding csrBuilder.addAttribute(pkcs_9_at_challengePassword, new DERUTF8String(challenge)); } if (unstructuredName != null) { csrBuilder.addAttribute(pkcs_9_at_unstructuredName, new DERUTF8String(unstructuredName)); } if (useExtensions) { // add extensionRequest attribute with all extensions from the certificate Certificate certificate = Certificate.getInstance(cert.getEncoded()); Extensions extensions = certificate.getTBSCertificate().getExtensions(); if (extensions != null) { csrBuilder.addAttribute(pkcs_9_at_extensionRequest, extensions.toASN1Primitive()); } } // fall back to bouncy castle provider if given provider does not support the requested algorithm if (provider != null && provider.getService("Signature", signatureType.jce()) == null) { provider = new BouncyCastleProvider(); } ContentSigner contentSigner = null; if (provider == null) { contentSigner = new JcaContentSignerBuilder(signatureType.jce()).build(privateKey); } else { contentSigner = new JcaContentSignerBuilder(signatureType.jce()).setProvider(provider) .build(privateKey); } PKCS10CertificationRequest csr = csrBuilder.build(contentSigner); if (!verifyCsr(csr)) { throw new CryptoException(res.getString("NoVerifyGenPkcs10Csr.exception.message")); } return csr; } catch (CertificateEncodingException e) { throw new CryptoException(res.getString("NoGeneratePkcs10Csr.exception.message"), e); } catch (OperatorCreationException e) { throw new CryptoException(res.getString("NoGeneratePkcs10Csr.exception.message"), e); } }
From source file:net.wstech2.me.httpsclient.CertificateValidatorUtils.java
License:Apache License
/** * /*from ww w.ja v a 2s . com*/ * 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:net.wstech2.me.httpsclient.CertificateValidatorUtils.java
License:Apache License
/** * Retrieves the list of alternative DNS names for this certificate, if any. * // w w w . j a va2 s . c o m * @param cert * The certificate from which the issuer name is to the * extracted. * @return A list with all alternative DNS names included in the * certificate. * @throws IOException */ public static List extractSubjectAlternativeNameList(org.bouncycastle.asn1.x509.Certificate cert) throws IOException { List dnsNames = new ArrayList(); dnsNames.add(CertificateValidatorUtils.extractCommonName(cert, true)); Extension subjectAlternativeName = cert.getTBSCertificate().getExtensions() .getExtension(Extension.subjectAlternativeName); if (subjectAlternativeName == null) { return dnsNames; } ASN1OctetString oct = subjectAlternativeName.getExtnValue(); ASN1InputStream extIn = new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())); GeneralNames gn = GeneralNames.getInstance(extIn.readObject()); extIn.close(); ASN1Sequence sq = (ASN1Sequence) gn.toASN1Primitive(); for (int i = 0; i != sq.size(); i++) { GeneralName n = GeneralName.getInstance(sq.getObjectAt(i)); dnsNames.add(n.getName().toString()); } return dnsNames; }
From source file:net.wstech2.me.httpsclient.CertificateValidatorUtils.java
License:Apache License
private static Boolean isHostAunthenticationCertificate(Certificate cert) throws IOException { Extension extKeyUsageExtension = cert.getTBSCertificate().getExtensions() .getExtension(Extension.extendedKeyUsage); if (extKeyUsageExtension == null) { return Boolean.FALSE; }// ww w. j a va 2 s .c om ASN1OctetString oct = extKeyUsageExtension.getExtnValue(); ASN1InputStream extIn = new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())); ExtendedKeyUsage extKeyUsages = ExtendedKeyUsage.getInstance(extIn.readObject()); extIn.close(); KeyPurposeId[] keyPurposeIds = extKeyUsages.getUsages(); for (int i = 0; i < keyPurposeIds.length; i++) { if (keyPurposeIds[i].equals(KeyPurposeId.id_kp_serverAuth)) { return Boolean.TRUE; } } return Boolean.FALSE; }
From source file:net.wstech2.me.httpsclient.CertificateValidatorUtils.java
License:Apache License
/** * Validates the certificate signature (hash). * //from w ww.j a v a 2 s. c om * @param cert * The certificate to be validated. * @param issuerCert * the issuer (normally a C.A.) certificate corresponding to the * key used to sign the certificate indicated at the previous * parameter. * * @param errors * a list to be filled - if needed - with errors detected during * the validation process. See * {@link CertificateValidationException#setErrors(List)}. * * @return True if the certificate signature is valid. False otherwise. * @throws IOException * @throws InvalidCipherTextException * @throws CertException * @throws OperatorCreationException * */ public static boolean verifySignature(org.bouncycastle.asn1.x509.Certificate cert, org.bouncycastle.asn1.x509.Certificate issuerCert, List errors) throws OperatorCreationException, CertException, IOException { boolean retval = false; if (!CertificateValidatorUtils.isAlgIdEqual(cert.getTBSCertificate().getSignature(), cert.getSignatureAlgorithm())) { throw new CertException("signature invalid - algorithm identifier mismatch"); } ContentVerifierProvider verifierProvider = new BcRSAContentVerifierProviderBuilder( new DefaultDigestAlgorithmIdentifierFinder()).build( PublicKeyFactory.createKey(issuerCert.getTBSCertificate().getSubjectPublicKeyInfo())); ContentVerifier verifier; try { verifier = verifierProvider.get((cert.getTBSCertificate().getSignature())); OutputStream sOut = verifier.getOutputStream(); DEROutputStream dOut = new DEROutputStream(sOut); dOut.writeObject(cert.getTBSCertificate()); sOut.close(); } catch (Exception e) { throw new CertException("unable to process signature: " + e.getMessage(), e); } retval = verifier.verify(cert.getSignature().getBytes()); if (retval == false) { String error = "Invalid certificate signature for [[" + extractCommonName(cert, true) + "]] validated against the Signer Certificate [[" + extractCommonName(issuerCert, true) + "]]."; HttpsConnectionUtils.logError(error); errors.add(error); } return retval; }
From source file:org.kse.gui.actions.GenerateCsrAction.java
License:Open Source License
/** * Do action./*from www . ja v a 2 s .co m*/ */ @Override protected void doAction() { File csrFile = null; FileOutputStream fos = null; try { KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory(); KeyStoreState currentState = history.getCurrentState(); Provider provider = history.getExplicitProvider(); String alias = kseFrame.getSelectedEntryAlias(); Password password = getEntryPassword(alias, currentState); if (password == null) { return; } KeyStore keyStore = currentState.getKeyStore(); PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray()); String keyPairAlg = privateKey.getAlgorithm(); KeyPairType keyPairType = KeyPairUtil.getKeyPairType(privateKey); if (keyPairType == null) { throw new CryptoException(MessageFormat .format(res.getString("GenerateCsrAction.NoCsrForKeyPairAlg.message"), keyPairAlg)); } // determine dir of current keystore as proposal for CSR file location String path = CurrentDirectory.get().getAbsolutePath(); File keyStoreFile = history.getFile(); if (keyStoreFile != null) { path = keyStoreFile.getAbsoluteFile().getParent(); } X509Certificate firstCertInChain = X509CertUtil .orderX509CertChain(X509CertUtil.convertCertificates(keyStore.getCertificateChain(alias)))[0]; X500Principal subjectDN = firstCertInChain.getSubjectX500Principal(); DGenerateCsr dGenerateCsr = new DGenerateCsr(frame, alias, subjectDN, privateKey, keyPairType, path); dGenerateCsr.setLocationRelativeTo(frame); dGenerateCsr.setVisible(true); if (!dGenerateCsr.generateSelected()) { return; } csrFile = dGenerateCsr.getCsrFile(); subjectDN = dGenerateCsr.getSubjectDN(); CsrType format = dGenerateCsr.getFormat(); SignatureType signatureType = dGenerateCsr.getSignatureType(); String challenge = dGenerateCsr.getChallenge(); String unstructuredName = dGenerateCsr.getUnstructuredName(); boolean useCertificateExtensions = dGenerateCsr.isAddExtensionsWanted(); PublicKey publicKey = firstCertInChain.getPublicKey(); // add extensionRequest attribute with all extensions from the certificate Extensions extensions = null; if (useCertificateExtensions) { Certificate certificate = Certificate.getInstance(firstCertInChain.getEncoded()); extensions = certificate.getTBSCertificate().getExtensions(); } fos = new FileOutputStream(csrFile); if (format == CsrType.PKCS10) { String csr = Pkcs10Util.getCsrEncodedDerPem(Pkcs10Util.generateCsr(subjectDN, publicKey, privateKey, signatureType, challenge, unstructuredName, extensions, provider)); fos.write(csr.getBytes()); } else { SpkacSubject subject = new SpkacSubject( X500NameUtils.x500PrincipalToX500Name(firstCertInChain.getSubjectX500Principal())); // TODO handle other providers (PKCS11 etc) Spkac spkac = new Spkac(challenge, signatureType, subject, publicKey, privateKey); spkac.output(fos); } JOptionPane.showMessageDialog(frame, res.getString("GenerateCsrAction.CsrGenerationSuccessful.message"), res.getString("GenerateCsrAction.GenerateCsr.Title"), JOptionPane.INFORMATION_MESSAGE); } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(frame, MessageFormat.format(res.getString("GenerateCsrAction.NoWriteFile.message"), csrFile), res.getString("GenerateCsrAction.GenerateCsr.Title"), JOptionPane.WARNING_MESSAGE); } catch (Exception ex) { DError.displayError(frame, ex); } finally { IOUtils.closeQuietly(fos); } }
From source file:org.xipki.ca.qa.impl.X509CertprofileQAImpl.java
License:Open Source License
@Override public ValidationResult checkCert(final byte[] certBytes, final X509IssuerInfo issuerInfo, final X500Name requestedSubject, final SubjectPublicKeyInfo requestedPublicKey, final Extensions requestedExtensions) { ParamChecker.assertNotNull("certBytes", certBytes); ParamChecker.assertNotNull("issuerInfo", issuerInfo); ParamChecker.assertNotNull("requestedSubject", requestedSubject); ParamChecker.assertNotNull("requestedPublicKey", requestedPublicKey); List<ValidationIssue> resultIssues = new LinkedList<ValidationIssue>(); Certificate bcCert; X509Certificate cert;//from w w w .ja v a2 s . c o m // certificate encoding { ValidationIssue issue = new ValidationIssue("X509.ENCODING", "certificate encoding"); resultIssues.add(issue); try { bcCert = Certificate.getInstance(certBytes); cert = X509Util.parseCert(certBytes); } catch (CertificateException | IOException e) { issue.setFailureMessage("certificate is not corrected encoded"); return new ValidationResult(resultIssues); } } // syntax version { ValidationIssue issue = new ValidationIssue("X509.VERSION", "certificate version"); resultIssues.add(issue); int versionNumber = cert.getVersion(); if (versionNumber != version.getVersion()) { issue.setFailureMessage("is '" + versionNumber + "' but expected '" + version.getVersion() + "'"); } } // signatureAlgorithm if (CollectionUtil.isNotEmpty(signatureAlgorithms)) { ValidationIssue issue = new ValidationIssue("X509.SIGALG", "signature algorithm"); resultIssues.add(issue); AlgorithmIdentifier sigAlgId = bcCert.getSignatureAlgorithm(); AlgorithmIdentifier tbsSigAlgId = bcCert.getTBSCertificate().getSignature(); if (tbsSigAlgId.equals(sigAlgId) == false) { issue.setFailureMessage("Certificate.tbsCertificate.signature != Certificate.signatureAlgorithm"); } else { try { String sigAlgo = AlgorithmUtil.getSignatureAlgoName(sigAlgId); if (signatureAlgorithms.contains(sigAlgo) == false) { issue.setFailureMessage("signatureAlgorithm '" + sigAlgo + "' is not allowed"); } } catch (NoSuchAlgorithmException e) { issue.setFailureMessage("unsupported signature algorithm " + sigAlgId.getAlgorithm().getId()); } } } // notBefore if (notBeforeMidnight) { ValidationIssue issue = new ValidationIssue("X509.NOTBEFORE", "not before midnight"); resultIssues.add(issue); Calendar c = Calendar.getInstance(UTC); c.setTime(cert.getNotBefore()); int hourOfDay = c.get(Calendar.HOUR_OF_DAY); int minute = c.get(Calendar.MINUTE); int second = c.get(Calendar.SECOND); if (hourOfDay != 0 || minute != 0 || second != 0) { issue.setFailureMessage(" '" + cert.getNotBefore() + "' is not midnight time (UTC)"); } } // validity { ValidationIssue issue = new ValidationIssue("X509.VALIDITY", "cert validity"); resultIssues.add(issue); Date expectedNotAfter = validity.add(cert.getNotBefore()); if (Math.abs(expectedNotAfter.getTime() - cert.getNotAfter().getTime()) > 60 * SECOND) { issue.setFailureMessage("cert validity is not within " + validity.toString()); } } // public key { SubjectPublicKeyInfo publicKey = bcCert.getSubjectPublicKeyInfo(); if (keyAlgorithms != null) { ValidationIssue issue = new ValidationIssue("X509.PUBKEY.SYN", "whether public key is permitted"); resultIssues.add(issue); try { checkPublicKey(publicKey); } catch (BadCertTemplateException e) { issue.setFailureMessage(e.getMessage()); } } ValidationIssue issue = new ValidationIssue("X509.PUBKEY.REQ", "whether public key matches the request one"); resultIssues.add(issue); SubjectPublicKeyInfo c14nRequestedPublicKey; try { c14nRequestedPublicKey = X509Util.toRfc3279Style(requestedPublicKey); if (c14nRequestedPublicKey.equals(publicKey) == false) { issue.setFailureMessage("public key in the certificate does not equal the requested one"); } } catch (InvalidKeySpecException e) { issue.setFailureMessage("public key in request is invalid"); } } // Signature { ValidationIssue issue = new ValidationIssue("X509.SIG", "whether certificate is signed by CA"); resultIssues.add(issue); try { cert.verify(issuerInfo.getCert().getPublicKey(), "BC"); } catch (Exception e) { issue.setFailureMessage("invalid signature"); } } // issuer { ValidationIssue issue = new ValidationIssue("X509.ISSUER", "certificate issuer"); resultIssues.add(issue); if (cert.getIssuerX500Principal().equals(issuerInfo.getCert().getSubjectX500Principal()) == false) { issue.setFailureMessage("issue in certificate does not equal the subject of CA certificate"); } } // subject X500Name subject = bcCert.getTBSCertificate().getSubject(); resultIssues.addAll(checkSubject(subject, requestedSubject)); // extensions resultIssues.addAll(checkExtensions(bcCert, cert, issuerInfo, requestedExtensions)); return new ValidationResult(resultIssues); }
From source file:org.xipki.ca.qa.impl.X509CertprofileQAImpl.java
License:Open Source License
private List<ValidationIssue> checkExtensions(final Certificate bcCert, final X509Certificate cert, final X509IssuerInfo issuerInfo, final Extensions requestExtensions) { List<ValidationIssue> result = new LinkedList<>(); // detect the list of extension types in certificate Set<ASN1ObjectIdentifier> presentExtenionTypes = getExensionTypes(bcCert, issuerInfo, requestExtensions); Extensions extensions = bcCert.getTBSCertificate().getExtensions(); ASN1ObjectIdentifier[] oids = extensions.getExtensionOIDs(); if (oids == null) { ValidationIssue issue = new ValidationIssue("X509.EXT.GEN", "extension general"); result.add(issue);// ww w . ja v a2s . co m issue.setFailureMessage("no extension is present"); return result; } List<ASN1ObjectIdentifier> certExtTypes = Arrays.asList(oids); for (ASN1ObjectIdentifier extType : presentExtenionTypes) { if (certExtTypes.contains(extType) == false) { ValidationIssue issue = createExtensionIssue(extType); result.add(issue); issue.setFailureMessage("extension is absent but is required"); } } for (ASN1ObjectIdentifier oid : certExtTypes) { ValidationIssue issue = createExtensionIssue(oid); result.add(issue); if (presentExtenionTypes.contains(oid) == false) { issue.setFailureMessage("extension is present but is not permitted"); continue; } Extension ext = extensions.getExtension(oid); StringBuilder failureMsg = new StringBuilder(); ExtensionControl extControl = extensionControls.get(oid); if (extControl.isCritical() != ext.isCritical()) { failureMsg.append( "critical is '" + ext.isCritical() + "' but expected '" + extControl.isCritical() + "'"); failureMsg.append("; "); } byte[] extensionValue = ext.getExtnValue().getOctets(); try { if (Extension.authorityKeyIdentifier.equals(oid)) { // AuthorityKeyIdentifier checkExtensionIssuerKeyIdentifier(failureMsg, extensionValue, issuerInfo); } else if (Extension.subjectKeyIdentifier.equals(oid)) { // SubjectKeyIdentifier checkExtensionSubjectKeyIdentifier(failureMsg, extensionValue, bcCert.getSubjectPublicKeyInfo()); } else if (Extension.keyUsage.equals(oid)) { // KeyUsage checkExtensionKeyUsage(failureMsg, extensionValue, cert.getKeyUsage(), requestExtensions, extControl); } else if (Extension.certificatePolicies.equals(oid)) { // CertificatePolicies checkExtensionCertificatePolicies(failureMsg, extensionValue, requestExtensions, extControl); } else if (Extension.policyMappings.equals(oid)) { // Policy Mappings checkExtensionPolicyMappings(failureMsg, extensionValue, requestExtensions, extControl); } else if (Extension.subjectAlternativeName.equals(oid)) { // SubjectAltName checkExtensionSubjectAltName(failureMsg, extensionValue, requestExtensions, extControl); } else if (Extension.issuerAlternativeName.equals(oid)) { // IssuerAltName checkExtensionIssuerAltNames(failureMsg, extensionValue, issuerInfo); } else if (Extension.basicConstraints.equals(oid)) { // Basic Constraints checkExtensionBasicConstraints(failureMsg, extensionValue); } else if (Extension.nameConstraints.equals(oid)) { // Name Constraints checkExtensionNameConstraints(failureMsg, extensionValue, extensions, extControl); } else if (Extension.policyConstraints.equals(oid)) { // PolicyConstrains checkExtensionPolicyConstraints(failureMsg, extensionValue, requestExtensions, extControl); } else if (Extension.extendedKeyUsage.equals(oid)) { // ExtendedKeyUsage checkExtensionExtendedKeyUsage(failureMsg, extensionValue, requestExtensions, extControl); } else if (Extension.cRLDistributionPoints.equals(oid)) { // CRL Distribution Points checkExtensionCrlDistributionPoints(failureMsg, extensionValue, issuerInfo); continue; } else if (Extension.inhibitAnyPolicy.equals(oid)) { // Inhibit anyPolicy checkExtensionInhibitAnyPolicy(failureMsg, extensionValue, extensions, extControl); } else if (Extension.freshestCRL.equals(oid)) { // Freshest CRL checkExtensionDeltaCrlDistributionPoints(failureMsg, extensionValue, issuerInfo); } else if (Extension.authorityInfoAccess.equals(oid)) { // Authority Information Access checkExtensionAuthorityInfoAccess(failureMsg, extensionValue, issuerInfo); } else if (Extension.subjectInfoAccess.equals(oid)) { // SubjectInfoAccess checkExtensionSubjectInfoAccess(failureMsg, extensionValue, requestExtensions, extControl); } else if (ObjectIdentifiers.id_extension_admission.equals(oid)) { // Admission checkExtensionAdmission(failureMsg, extensionValue, requestExtensions, extControl); } else if (ObjectIdentifiers.id_extension_pkix_ocsp_nocheck.equals(oid)) { // ocsp-nocheck checkExtensionOcspNocheck(failureMsg, extensionValue); } else { byte[] expected = getExpectedExtValue(oid, requestExtensions, extControl); if (Arrays.equals(expected, extensionValue) == false) { failureMsg.append("extension valus is '" + hex(extensionValue) + "' but expected '" + (expected == null ? "not present" : hex(expected)) + "'"); failureMsg.append("; "); } } if (failureMsg.length() > 0) { issue.setFailureMessage(failureMsg.toString()); } } catch (IllegalArgumentException | ClassCastException | ArrayIndexOutOfBoundsException e) { LOG.debug("extension value does not have correct syntax", e); issue.setFailureMessage("extension value does not have correct syntax"); } } return result; }
From source file:org.xipki.ca.qa.impl.X509CertprofileQAImpl.java
License:Open Source License
private Set<ASN1ObjectIdentifier> getExensionTypes(final Certificate cert, final X509IssuerInfo issuerInfo, final Extensions requestedExtensions) { Set<ASN1ObjectIdentifier> types = new HashSet<>(); // profile required extension types for (ASN1ObjectIdentifier oid : extensionControls.keySet()) { if (extensionControls.get(oid).isRequired()) { types.add(oid);// ww w .j a v a 2 s.c o m } } Set<ASN1ObjectIdentifier> wantedExtensionTypes = new HashSet<>(); if (requestedExtensions != null) { Extension reqExtension = requestedExtensions .getExtension(ObjectIdentifiers.id_xipki_ext_cmpRequestExtensions); if (reqExtension != null) { ExtensionExistence ee = ExtensionExistence.getInstance(reqExtension.getParsedValue()); types.addAll(ee.getNeedExtensions()); wantedExtensionTypes.addAll(ee.getWantExtensions()); } } if (CollectionUtil.isEmpty(wantedExtensionTypes)) { return types; } // wanted extension types // Authority key identifier ASN1ObjectIdentifier type = Extension.authorityKeyIdentifier; if (wantedExtensionTypes.contains(type)) { types.add(type); } // Subject key identifier type = Extension.subjectKeyIdentifier; if (wantedExtensionTypes.contains(type)) { types.add(type); } // KeyUsage type = Extension.keyUsage; if (wantedExtensionTypes.contains(type)) { boolean required = false; if (requestedExtensions.getExtension(type) != null) { required = true; } if (required == false) { Set<KeyUsageControl> requiredKeyusage = getKeyusage(true); if (CollectionUtil.isNotEmpty(requiredKeyusage)) { required = true; } } if (required) { types.add(type); } } // CertificatePolicies type = Extension.certificatePolicies; if (wantedExtensionTypes.contains(type)) { if (certificatePolicies != null) { types.add(type); } } // Policy Mappings type = Extension.policyMappings; if (wantedExtensionTypes.contains(type)) { if (policyMappings != null) { types.add(type); } } // SubjectAltNames type = Extension.subjectAlternativeName; if (wantedExtensionTypes.contains(type)) { if (requestedExtensions.getExtension(type) != null) { types.add(type); } } // IssuerAltName type = Extension.issuerAlternativeName; if (wantedExtensionTypes.contains(type)) { if (cert.getTBSCertificate().getExtensions().getExtension(Extension.subjectAlternativeName) != null) { types.add(type); } } // BasicConstraints type = Extension.basicConstraints; if (wantedExtensionTypes.contains(type)) { types.add(type); } // Name Constraints type = Extension.nameConstraints; if (wantedExtensionTypes.contains(type)) { if (nameConstraints != null) { types.add(type); } } // PolicyConstrains type = Extension.policyConstraints; if (wantedExtensionTypes.contains(type)) { if (policyConstraints != null) { types.add(type); } } // ExtendedKeyUsage type = Extension.extendedKeyUsage; if (wantedExtensionTypes.contains(type)) { boolean required = false; if (requestedExtensions.getExtension(type) != null) { required = true; } if (required == false) { Set<ExtKeyUsageControl> requiredExtKeyusage = getExtKeyusage(true); if (CollectionUtil.isNotEmpty(requiredExtKeyusage)) { required = true; } } if (required) { types.add(type); } } // CRLDistributionPoints type = Extension.cRLDistributionPoints; if (wantedExtensionTypes.contains(type)) { if (issuerInfo.getCrlURLs() != null) { types.add(type); } } // Inhibit anyPolicy type = Extension.inhibitAnyPolicy; if (wantedExtensionTypes.contains(type)) { if (inhibitAnyPolicy != null) { types.add(type); } } // FreshestCRL type = Extension.freshestCRL; if (wantedExtensionTypes.contains(type)) { if (issuerInfo.getDeltaCrlURLs() != null) { types.add(type); } } // AuthorityInfoAccess type = Extension.authorityInfoAccess; if (wantedExtensionTypes.contains(type)) { if (issuerInfo.getOcspURLs() != null) { types.add(type); } } // SubjectInfoAccess type = Extension.subjectInfoAccess; if (wantedExtensionTypes.contains(type)) { if (requestedExtensions.getExtension(type) != null) { types.add(type); } } // Admission type = ObjectIdentifiers.id_extension_admission; if (wantedExtensionTypes.contains(type)) { if (admission != null) { types.add(type); } } // ocsp-nocheck type = ObjectIdentifiers.id_extension_pkix_ocsp_nocheck; if (wantedExtensionTypes.contains(type)) { types.add(type); } wantedExtensionTypes.removeAll(types); for (ASN1ObjectIdentifier oid : wantedExtensionTypes) { if (requestedExtensions.getExtension(oid) != null) { if (constantExtensions.containsKey(oid)) { types.add(oid); } } } return types; }
From source file:org.xipki.dbtool.CaCertStoreDbImporter.java
License:Open Source License
private int[] do_import_cert(final PreparedStatement ps_cert, final PreparedStatement ps_rawcert, final String certsZipFile, final int minId, final File processLogFile, final int totalProcessedSum) throws IOException, JAXBException, DataAccessException, CertificateException { ZipFile zipFile = new ZipFile(new File(baseDir, certsZipFile)); ZipEntry certsXmlEntry = zipFile.getEntry("certs.xml"); CertsType certs;/*w ww. j a va 2s . c o m*/ try { @SuppressWarnings("unchecked") JAXBElement<CertsType> rootElement = (JAXBElement<CertsType>) unmarshaller .unmarshal(zipFile.getInputStream(certsXmlEntry)); certs = rootElement.getValue(); } catch (JAXBException e) { try { zipFile.close(); } catch (Exception e2) { } throw XMLUtil.convert(e); } disableAutoCommit(); try { List<CertType> list = certs.getCert(); final int size = list.size(); final int n = 100; int numProcessed = 0; int numEntriesInBatch = 0; int lastSuccessfulCertId = 0; for (int i = 0; i < size; i++) { CertType cert = list.get(i); int id = cert.getId(); lastSuccessfulCertId = id; if (id < minId) { continue; } int certArt = cert.getArt() == null ? 1 : cert.getArt(); numEntriesInBatch++; String filename = cert.getCertFile(); // rawcert ZipEntry certZipEnty = zipFile.getEntry(filename); // rawcert byte[] encodedCert = IoUtil.read(zipFile.getInputStream(certZipEnty)); Certificate c; try { c = Certificate.getInstance(encodedCert); } catch (Exception e) { LOG.error("could not parse certificate in file {}", filename); LOG.debug("could not parse certificate in file " + filename, e); if (e instanceof CertificateException) { throw (CertificateException) e; } else { throw new CertificateException(e.getMessage(), e); } } byte[] encodedKey = c.getSubjectPublicKeyInfo().getPublicKeyData().getBytes(); String hexSha1FpCert = HashCalculator.hexHash(HashAlgoType.SHA1, encodedCert); // cert try { int idx = 1; ps_cert.setInt(idx++, id); ps_cert.setInt(idx++, certArt); ps_cert.setLong(idx++, cert.getLastUpdate()); ps_cert.setLong(idx++, c.getSerialNumber().getPositiveValue().longValue()); ps_cert.setString(idx++, X509Util.getRFC4519Name(c.getSubject())); ps_cert.setLong(idx++, c.getTBSCertificate().getStartDate().getDate().getTime() / 1000); ps_cert.setLong(idx++, c.getTBSCertificate().getEndDate().getDate().getTime() / 1000); setBoolean(ps_cert, idx++, cert.isRevoked()); setInt(ps_cert, idx++, cert.getRevReason()); setLong(ps_cert, idx++, cert.getRevTime()); setLong(ps_cert, idx++, cert.getRevInvTime()); setInt(ps_cert, idx++, cert.getProfileId()); setInt(ps_cert, idx++, cert.getCaId()); setInt(ps_cert, idx++, cert.getRequestorId()); setInt(ps_cert, idx++, cert.getUserId()); ps_cert.setString(idx++, HashCalculator.hexHash(HashAlgoType.SHA1, encodedKey)); String sha1FpSubject = X509Util.sha1sum_canonicalized_name(c.getSubject()); ps_cert.setString(idx++, sha1FpSubject); Extension extension = c.getTBSCertificate().getExtensions() .getExtension(Extension.basicConstraints); boolean ee = true; if (extension != null) { ASN1Encodable asn1 = extension.getParsedValue(); try { ee = BasicConstraints.getInstance(asn1).isCA() == false; } catch (Exception e) { } } ps_cert.setInt(idx++, ee ? 1 : 0); ps_cert.addBatch(); } catch (SQLException e) { throw translate(SQL_ADD_CERT, e); } try { int idx = 1; ps_rawcert.setInt(idx++, cert.getId()); ps_rawcert.setString(idx++, hexSha1FpCert); ps_rawcert.setString(idx++, Base64.toBase64String(encodedCert)); ps_rawcert.addBatch(); } catch (SQLException e) { throw translate(SQL_ADD_RAWCERT, e); } if (numEntriesInBatch > 0 && (numEntriesInBatch % n == 0 || i == size - 1)) { String sql = null; try { sql = SQL_ADD_CERT; ps_cert.executeBatch(); sql = SQL_ADD_RAWCERT; ps_rawcert.executeBatch(); sql = null; commit("(commit import cert to CA)"); } catch (SQLException e) { rollback(); throw translate(sql, e); } catch (DataAccessException e) { rollback(); throw e; } numProcessed += numEntriesInBatch; numEntriesInBatch = 0; echoToFile((totalProcessedSum + numProcessed) + ":" + lastSuccessfulCertId, processLogFile); } } return new int[] { numProcessed, lastSuccessfulCertId }; } finally { try { recoverAutoCommit(); } catch (DataAccessException e) { } zipFile.close(); } }