/* * Check for a valid certificate pair */ private void checkPair() throws CertificateException { /* if either of pair is missing, return w/o error */ if (forward == null || reverse == null) { return; } /* * If both elements of the pair are present, check that they * are a valid pair. */ X500Principal fwSubject = forward.getSubjectX500Principal(); X500Principal fwIssuer = forward.getIssuerX500Principal(); X500Principal rvSubject = reverse.getSubjectX500Principal(); X500Principal rvIssuer = reverse.getIssuerX500Principal(); if (!fwIssuer.equals(rvSubject) || !rvIssuer.equals(fwSubject)) { throw new CertificateException( "subject and issuer names in " + "forward and reverse certificates do not match"); } /* check signatures unless key parameters are missing */ try { PublicKey pk = reverse.getPublicKey(); if (!(pk instanceof DSAPublicKey) || ((DSAPublicKey) pk).getParams() != null) { forward.verify(pk); } pk = forward.getPublicKey(); if (!(pk instanceof DSAPublicKey) || ((DSAPublicKey) pk).getParams() != null) { reverse.verify(pk); } } catch (GeneralSecurityException e) { throw new CertificateException("invalid signature: " + e.getMessage()); } }
protected PropertyDataObject generate( Collection<X509Certificate> certs, BaseCertRefsData certRefsData, QualifyingProperty prop) throws PropertyDataGenerationException { if (null == certs) { throw new PropertyDataGenerationException(prop, "certificates not provided"); } try { String digestAlgUri = this.algorithmsProvider.getDigestAlgorithmForReferenceProperties(); MessageDigest messageDigest = this.messageDigestProvider.getEngine(digestAlgUri); for (X509Certificate cert : certs) { // "DigestValue contains the base-64 encoded value of the digest // computed on the DER-encoded certificate." // The base-64 encoding is done by JAXB with the configured // adapter (Base64XmlAdapter). // For X509 certificates the encoded form return by getEncoded is DER. byte[] digestValue = messageDigest.digest(cert.getEncoded()); certRefsData.addCertRef( new CertRef( cert.getIssuerX500Principal().getName(), cert.getSerialNumber(), digestAlgUri, digestValue)); } return certRefsData; } catch (UnsupportedAlgorithmException ex) { throw new PropertyDataGenerationException(prop, ex.getMessage(), ex); } catch (CertificateEncodingException ex) { throw new PropertyDataGenerationException(prop, "cannot get encoded certificate", ex); } }
private List<DEREncodable> listPolicies(X509Certificate eec) throws AuthenticationException { byte[] encoded; try { encoded = getExtensionBytes(eec, OID_CERTIFICATE_POLICIES); } catch (IOException e) { LOG.warn( "Malformed policy extension {}: {}", eec.getIssuerX500Principal().getName(), e.getMessage()); return Collections.emptyList(); } if (encoded == null) { // has no Certificate Policies extension. return Collections.emptyList(); } Enumeration<DEREncodable> policySource = ASN1Sequence.getInstance(encoded).getObjects(); List<DEREncodable> policies = new ArrayList(); while (policySource.hasMoreElements()) { DEREncodable policy = policySource.nextElement(); if (!policy.equals(ANY_POLICY)) { policies.add(policy); } } return policies; }
public boolean match(Certificate cert) { if (!(cert instanceof X509Certificate)) { return false; } X509Certificate x509Cert = (X509Certificate) cert; if (form instanceof V2Form) { V2Form issuer = (V2Form) form; if (issuer.getBaseCertificateID() != null) { return issuer .getBaseCertificateID() .getSerial() .getValue() .equals(x509Cert.getSerialNumber()) && matchesDN( x509Cert.getIssuerX500Principal(), issuer.getBaseCertificateID().getIssuer()); } GeneralNames name = issuer.getIssuerName(); if (matchesDN(x509Cert.getSubjectX500Principal(), name)) { return true; } } else { GeneralNames name = (GeneralNames) form; if (matchesDN(x509Cert.getSubjectX500Principal(), name)) { return true; } } return false; }
/** * Handles server certificate validation. Flags for validity and certificate chain verification * decides this functions behavior. * * <p>Implements X509TrustManager. */ public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { try { Set<TrustAnchor> trust = new HashSet<TrustAnchor>(); // All CAs must in an *installed* CA path be valid as trust // anchors Enumeration<String> aliases = trust_store.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (trust_store.isCertificateEntry(alias)) { trust.add(new TrustAnchor((X509Certificate) trust_store.getCertificate(alias), null)); } } CertPathValidator cpv = CertPathValidator.getInstance("PKIX"); PKIXParameters param = new PKIXParameters(trust); param.setDate(new Date()); param.setRevocationEnabled(enable_revocation_test); List<X509Certificate> certchain = new ArrayList<X509Certificate>(); for (X509Certificate cert : chain) { if (!cert.getSubjectX500Principal().equals(cert.getIssuerX500Principal())) { certchain.add(cert); } } CertPath cp = CertificateFactory.getInstance("X.509").generateCertPath(certchain); cpv.validate(cp, param); } catch (GeneralSecurityException e) { if (!allow_invalidcert) { throw new CertificateException(e); } } }
public static void main(String[] args) throws Exception { // create the keys KeyPair pair = Utils.generateRSAKeyPair(); // create the input stream ByteArrayOutputStream bOut = new ByteArrayOutputStream(); if (outputFormat.equals(DER)) { bOut.write(X509V1CreateExample.generateV1Certificate(pair).getEncoded()); } else if (outputFormat.equals(PEM)) { PEMWriter pemWriter = new PEMWriter(new OutputStreamWriter(bOut)); pemWriter.writeObject(X509V1CreateExample.generateV1Certificate(pair)); pemWriter.close(); } bOut.close(); // Print the contents of bOut System.out.println(outputFormat.equals(DER) ? "DER-format:" : "PEM-format:"); System.out.println(Utils.toString(bOut.toByteArray())); InputStream in = new ByteArrayInputStream(bOut.toByteArray()); // create the certificate factory CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); // read the certificate X509Certificate x509Cert = (X509Certificate) fact.generateCertificate(in); System.out.println("issuer: " + x509Cert.getIssuerX500Principal()); }
/** * Take an array of X509 certificates and arrange them as a list of chains. Certificates of * unknown types and broken chains are add returned in failed list. */ public static ArrayList<List<X509Certificate>> getCertificateChains( Certificate[] c, ArrayList<Certificate> failed) { if (c == null) { return null; } final ArrayList<List<X509Certificate>> res = new ArrayList<List<X509Certificate>>(3); ArrayList<X509Certificate> chain = new ArrayList<X509Certificate>(3); int i = 0; while (i < c.length) { if (c[i] instanceof X509Certificate) { final X509Certificate cert = (X509Certificate) c[i++]; // TBD, can we use == and do we need to check uniqID? chain.add(cert); if (cert.getIssuerX500Principal().equals(cert.getSubjectX500Principal())) { res.add(chain); chain = new ArrayList<X509Certificate>(3); } } else { // Unsupported type if (!chain.isEmpty()) { failed.addAll(chain); chain.clear(); } failed.add(c[i++]); } } // Add remaining certs as failed failed.addAll(chain); return res; }
/** * Load an X509 Cert from a file and add it to the trusted set of certificates in the key store * * @return success * @since 0.8.2, moved from SSLEepGet in 0.9.9 */ public static boolean addCert(File file, String alias, KeyStore ks) { InputStream fis = null; try { fis = new FileInputStream(file); CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) cf.generateCertificate(fis); info( "Read X509 Certificate from " + file.getAbsolutePath() + " Issuer: " + cert.getIssuerX500Principal() + "; Valid From: " + cert.getNotBefore() + " To: " + cert.getNotAfter()); try { cert.checkValidity(); } catch (CertificateExpiredException cee) { error("Rejecting expired X509 Certificate: " + file.getAbsolutePath(), cee); return false; } catch (CertificateNotYetValidException cnyve) { error("Rejecting X509 Certificate not yet valid: " + file.getAbsolutePath(), cnyve); return false; } ks.setCertificateEntry(alias, cert); info("Now trusting X509 Certificate, Issuer: " + cert.getIssuerX500Principal()); } catch (GeneralSecurityException gse) { error("Error reading X509 Certificate: " + file.getAbsolutePath(), gse); return false; } catch (IOException ioe) { error("Error reading X509 Certificate: " + file.getAbsolutePath(), ioe); return false; } finally { try { if (fis != null) fis.close(); } catch (IOException foo) { } } return true; }
private static boolean isValidLink(X509Certificate parent, X509Certificate child) { if (!parent.getSubjectX500Principal().equals(child.getIssuerX500Principal())) { return false; } try { child.verify(parent.getPublicKey()); } catch (GeneralSecurityException gse) { return false; } return true; }
private String getCrlUrl(X509Certificate childCertificate) { URI crlUri = CrlTrustLinker.getCrlUri(childCertificate); if (null == crlUri) { LOG.warn("No CRL uri for: " + childCertificate.getIssuerX500Principal().toString()); return null; } try { return crlUri.toURL().toString(); } catch (MalformedURLException e) { LOG.warn("malformed URL: " + e.getMessage(), e); return null; } }
public static String prettyPrint(X509Certificate x509) { if (x509 == null) throw new IllegalArgumentException("x509 cannot be null"); return String.format( FORMAT, x509.getVersion(), x509.getSerialNumber(), x509.getSigAlgName(), x509.getIssuerX500Principal().getName(), x509.getNotBefore(), x509.getNotAfter(), x509.getSubjectX500Principal().getName(), x509.getPublicKey().getAlgorithm(), x509.getBasicConstraints(), x509.getSigAlgName()); }
/** * Liefert den Aussteller, insofern ermittelbar. * * @return der Aussteller. Wenn es sich um ein selbstsigniertes Zertifikat handelt, liefert die * Funktion NULL. * @throws Exception */ public Entry getIssuer() throws Exception { if (this.issuer != null || this.issuerChecked) return this.issuer; this.issuerChecked = true; X509Certificate x = this.getCertificate(); X500Principal issuer = x.getIssuerX500Principal(); // brauchmer gar nicht erst anfangen zu suchen if (issuer == null) return null; // selbstsigniert if (issuer.equals(x.getSubjectX500Principal())) return null; byte[] issuerSig = x.getExtensionValue(Extension.authorityKeyIdentifier.getId()); List<Entry> all = this.store.getEntries(); // wenn die Signatur des Ausstellers bekannt ist, suchen wir anhand // der. Das ist die zuverlaessigste Methode. if (issuerSig != null && issuerSig.length > 0) { for (Entry e : all) { if (CHECK_CA && !e.isCA()) continue; // OK, wir haben die Signatur des Ausstellers. Mal schauen, // ob wir sie im Keystore finden. byte[] test = e.getCertificate().getPublicKey().getEncoded(); if (Arrays.equals(issuerSig, test)) { this.issuer = e; return e; // gefunden } } } // Wir haben die Signatur nicht, stimmt vielleicht einen passenden DN? for (Entry e : all) { if (CHECK_CA && !e.isCA()) continue; X500Principal subject = e.getCertificate().getSubjectX500Principal(); if (subject.equals(issuer)) { this.issuer = e; return e; } } // nichts gefunden return null; }
private static boolean a(X509Certificate x509certificate, X509Certificate x509certificate1) { if (!x509certificate.getSubjectX500Principal().equals(x509certificate1.getIssuerX500Principal())) { return false; } try { x509certificate1.verify(x509certificate.getPublicKey()); } // Misplaced declaration of an exception variable catch (X509Certificate x509certificate) { return false; } return true; }
/** * Liefert alle Schluessel, die von diesem signiert wurden. * * @return Liste aller Schluessel, die von diesem signiert wurden. Die Funktion liefert nie NULL * sondern hoechstens eine leere Liste. * @throws Exception */ public List<Entry> getClients() throws Exception { if (this.clients != null) return this.clients; this.clients = new ArrayList<Entry>(); if (CHECK_CA && !this.isCA()) return this.clients; X509Certificate x = this.getCertificate(); byte[] sig = x.getPublicKey().getEncoded(); X500Principal self = x.getSubjectX500Principal(); // 2. Wir sind ein CA-Zertifikat, jetzt holen wir alle // Zertifikate, bei denen wir als CA eingetragen sind. List<Entry> all = this.store.getEntries(); for (Entry e : all) { X509Certificate c = e.getCertificate(); // sind wir selbst if (c.equals(x)) continue; // Checken, ob die Aussteller-Signatur angegeben ist byte[] issuerSig = x.getExtensionValue(Extension.authorityKeyIdentifier.getId()); if (issuerSig != null && issuerSig.length > 0) { // Issuer-Signatur angegeben. Mal checken, ob es unsere ist if (Arrays.equals(issuerSig, sig)) { // jepp, passt this.clients.add(e); continue; } } // Checken, ob der DN uebereinstimmt. X500Principal p = c.getIssuerX500Principal(); // passt, nehmen wir auch if (p != null && p.equals(self)) { this.clients.add(e); continue; } } Collections.sort(this.clients); return this.clients; }
private static void writeSignatureBlock( Signature signature, X509Certificate publicKey, OutputStream out) throws IOException, GeneralSecurityException { SignerInfo signerInfo = new SignerInfo( new X500Name(publicKey.getIssuerX500Principal().getName()), publicKey.getSerialNumber(), AlgorithmId.get("SHA1"), AlgorithmId.get("RSA"), signature.sign()); PKCS7 pkcs7 = new PKCS7( new AlgorithmId[] {AlgorithmId.get("SHA1")}, new ContentInfo(ContentInfo.DATA_OID, null), new X509Certificate[] {publicKey}, new SignerInfo[] {signerInfo}); pkcs7.encodeSignedData(out); }
/* * Construct an RecipientId. Added private function to support multiple versions of BC libraries. */ private RecipientId generateRecipientSelector(X509Certificate decryptCert) { RecipientId retVal = null; Class<RecipientId> loadClass = null; try { // support for bcmail-jdk15-146 loadClass = (Class<RecipientId>) getClass() .getClassLoader() .loadClass("org.bouncycastle.cms.jcajce.JceKeyTransRecipientId"); Constructor<RecipientId> constructor = loadClass.getConstructor(X509Certificate.class); retVal = constructor.newInstance(decryptCert); } catch (Throwable e) { if (LOGGER.isDebugEnabled()) { StringBuilder builder = new StringBuilder( "bcmail-jdk15-146 org.bouncycastle.cms.jcajce.JceKeyTransRecipientId class not found."); builder.append( "\r\n\tAttempt to fall back to bcmail-jdk15-140 org.bouncycastle.cms.RecipientId"); LOGGER.debug(builder.toString()); } } if (retVal == null) { try { // fall back to bcmail-jdk15-140 interfaces loadClass = (Class<RecipientId>) getClass().getClassLoader().loadClass("org.bouncycastle.cms.RecipientId"); retVal = loadClass.newInstance(); retVal.setSerialNumber(decryptCert.getSerialNumber()); retVal.setIssuer(decryptCert.getIssuerX500Principal().getEncoded()); } catch (Throwable e) { LOGGER.error( "Attempt to fall back to bcmail-jdk15-140 org.bouncycastle.cms.RecipientId failed.", e); } } return retVal; }
/* */ private boolean isWorthTrying( X509Certificate paramX509Certificate1, X509Certificate paramX509Certificate2) /* */ { /* 220 */ boolean bool = false; /* */ /* 222 */ if (debug != null) { /* 223 */ debug.println( "PKIXCertPathValidator.isWorthTrying() checking if this trusted cert is worth trying ..."); /* */ } /* */ /* 227 */ if (paramX509Certificate2 == null) { /* 228 */ return true; /* */ } /* */ /* 231 */ AdaptableX509CertSelector localAdaptableX509CertSelector = new AdaptableX509CertSelector(); /* */ /* 235 */ localAdaptableX509CertSelector.setSubject( paramX509Certificate2.getIssuerX500Principal()); /* */ /* 238 */ localAdaptableX509CertSelector.setValidityPeriod( paramX509Certificate2.getNotBefore(), paramX509Certificate2.getNotAfter()); /* */ try /* */ { /* 246 */ X509CertImpl localX509CertImpl = X509CertImpl.toImpl(paramX509Certificate2); /* 247 */ localAdaptableX509CertSelector.parseAuthorityKeyIdentifierExtension( localX509CertImpl.getAuthorityKeyIdentifierExtension()); /* */ /* 250 */ bool = localAdaptableX509CertSelector.match(paramX509Certificate1); /* */ } /* */ catch (Exception localException) /* */ { /* */ } /* 255 */ if (debug != null) { /* 256 */ if (bool) /* 257 */ debug.println("YES - try this trustedCert"); /* */ else { /* 259 */ debug.println("NO - don't try this trustedCert"); /* */ } /* */ } /* */ /* 263 */ return bool; /* */ }
/** * Checks certification path by IssuerX500Principal keyed in CAroot<br> * <br> * Risale il certification path attraverso IssuerX500Principal chiave in CAroot * * @return true: if certification path is valid */ public boolean getPathValid() { isPathValid = true; X509Certificate certChild = cert; X509Certificate certParent = null; while (!certChild.getIssuerDN().equals(certChild.getSubjectDN())) { // finche' la CA non è autofirmata try { certParent = CAroot.getCACertificate(certChild.getIssuerX500Principal()); } catch (GeneralSecurityException ex) { // la CA non è presente nella root isPathValid = false; return isPathValid; } certChild = certParent; } ; return isPathValid; }
/** * Fetches complete CRLs according to RFC 3280. * * @param dp The distribution point for which the complete CRL * @param cert The <code>X509Certificate</code> or {@link * org.bouncycastle.x509.X509AttributeCertificate} for which the CRL should be searched. * @param currentDate The date for which the delta CRLs must be valid. * @param paramsPKIX The extended PKIX parameters. * @return A <code>Set</code> of <code>X509CRL</code>s with complete CRLs. * @throws AnnotatedException if an exception occurs while picking the CRLs or no CRLs are found. */ protected static Set getCompleteCRLs( DistributionPoint dp, Object cert, Date currentDate, ExtendedPKIXParameters paramsPKIX) throws AnnotatedException { X509CRLStoreSelector crlselect = new X509CRLStoreSelector(); try { Set issuers = new HashSet(); if (cert instanceof X509AttributeCertificate) { issuers.add(((X509AttributeCertificate) cert).getIssuer().getPrincipals()[0]); } else { issuers.add(getEncodedIssuerPrincipal(cert)); } CertPathValidatorUtilities.getCRLIssuersFromDistributionPoint( dp, issuers, crlselect, paramsPKIX); } catch (AnnotatedException e) { throw new AnnotatedException("Could not get issuer information from distribution point.", e); } if (cert instanceof X509Certificate) { crlselect.setCertificateChecking((X509Certificate) cert); } else if (cert instanceof X509AttributeCertificate) { crlselect.setAttrCertificateChecking((X509AttributeCertificate) cert); } crlselect.setCompleteCRLEnabled(true); Set crls = CRL_UTIL.findCRLs(crlselect, paramsPKIX, currentDate); if (crls.isEmpty()) { if (cert instanceof X509AttributeCertificate) { X509AttributeCertificate aCert = (X509AttributeCertificate) cert; throw new AnnotatedException( "No CRLs found for issuer \"" + aCert.getIssuer().getPrincipals()[0] + "\""); } else { X509Certificate xCert = (X509Certificate) cert; throw new AnnotatedException( "No CRLs found for issuer \"" + xCert.getIssuerX500Principal() + "\""); } } return crls; }
/** * Create the Master Certificate for the GridTalk. * * @param certFile The file that contains the Certificate. * @return the UID of the created certificate. */ private Long createMasterCertificate(File certFile) throws Throwable { Long certUID = null; X509Certificate cert = GridCertUtilities.loadX509Certificate(certFile.getAbsolutePath()); ICertificateManagerObj mgr = ServiceLookupHelper.getCertificateManager(); // retrieve existing master cert Certificate existCert = mgr.findCertificateByIDAndName(_ctx.getGridNodeID().intValue(), _ctx.getMasterCertName()); // revoke Logger.log( "[ConnectionSetupRequestDelegate.createMasterCertificate] Revoking cert " + existCert.getUId()); mgr.revokeCertificateByUId((Long) existCert.getKey()); // insert new cert mgr.insertCertificate(_ctx.getGridNodeID(), _ctx.getMasterCertName(), cert); /*NSL20051115 Somehow this method still returns the revoked cert... so alternative is to * use issuername & serialnumber to retrieve -- guarantee to be unique Certificate newCert = mgr.findCertificateByIDAndName( _ctx.getGridNodeID().intValue(), _ctx.getMasterCertName()); */ String issuerName = GridCertUtilities.writeIssuerNameToString(cert.getIssuerX500Principal()); String serialNum = GridCertUtilities.writeByteArrayToString(cert.getSerialNumber().toByteArray()); Certificate newCert = mgr.findCertificateByIssureAndSerialNum(issuerName, serialNum); certUID = (Long) newCert.getKey(); Logger.log("[ConnectionSetupRequestDelegate.createMasterCertificate] New cert UID=" + certUID); // update private key mgr.updatePrivateKeyByCertificate(existCert.getPrivateKey(), newCert.getCertificate()); // update IsMaster mgr.updateMasterAndPartnerByUId(certUID, true, false); return certUID; }
/** * Find the issuer certificates of a given certificate. * * @param cert The certificate for which an issuer should be found. * @param pkixParams * @return A <code>Collection</code> object containing the issuer <code>X509Certificate</code>s. * Never <code>null</code>. * @throws AnnotatedException if an error occurs. */ protected static Collection findIssuerCerts( X509Certificate cert, ExtendedPKIXBuilderParameters pkixParams) throws AnnotatedException { X509CertStoreSelector certSelect = new X509CertStoreSelector(); Set certs = new HashSet(); try { certSelect.setSubject(cert.getIssuerX500Principal().getEncoded()); } catch (IOException ex) { throw new AnnotatedException( "Subject criteria for certificate selector to find issuer certificate could not be set.", ex); } Iterator iter; try { List matches = new ArrayList(); matches.addAll( CertPathValidatorUtilities.findCertificates(certSelect, pkixParams.getCertStores())); matches.addAll( CertPathValidatorUtilities.findCertificates(certSelect, pkixParams.getStores())); matches.addAll( CertPathValidatorUtilities.findCertificates( certSelect, pkixParams.getAdditionalStores())); iter = matches.iterator(); } catch (AnnotatedException e) { throw new AnnotatedException("Issuer certificate cannot be searched.", e); } X509Certificate issuer = null; while (iter.hasNext()) { issuer = (X509Certificate) iter.next(); // issuer cannot be verified because possible DSA inheritance // parameters are missing certs.add(issuer); } return certs; }
private void storeCertificateInCache(X509Certificate certificate, String key, boolean validated) { // Store in the cache if (certificate != null && xkmsClientCache != null) { XKMSCacheToken cacheToken = new XKMSCacheToken(certificate); cacheToken.setXkmsValidated(validated); // Store using a custom key (if any) if (key != null) { xkmsClientCache.put(key, cacheToken); } // Store it using IssuerSerial as well String issuerSerialKey = getKeyForIssuerSerial( certificate.getIssuerX500Principal().getName(), certificate.getSerialNumber()); if (!issuerSerialKey.equals(key)) { xkmsClientCache.put(issuerSerialKey, cacheToken); } // Store it using the Subject DN as well String subjectDNKey = certificate.getSubjectX500Principal().getName(); if (!subjectDNKey.equals(key)) { xkmsClientCache.put(subjectDNKey, cacheToken); } } }
void start() throws KeyStoreException, NoSuchAlgorithmException, IOException, UnsupportedCallbackException, UnrecoverableKeyException, InvalidKeyException, SignatureException { if (Configuration.DEBUG) log.entering(this.getClass().getName(), "start"); // $NON-NLS-1$ // 1. get the key entry and certificate chain associated to alias Key privateKey = getAliasPrivateKey(); Certificate[] chain = store.getCertificateChain(alias); // 2. get alias's DN and public key to use in the CSR X509Certificate bottomCertificate = (X509Certificate) chain[0]; X500Principal aliasName = bottomCertificate.getIssuerX500Principal(); PublicKey publicKey = bottomCertificate.getPublicKey(); // 3. generate the CSR setSignatureAlgorithmParam(_sigAlgorithm, privateKey); byte[] derBytes = getCSR(aliasName, publicKey, (PrivateKey) privateKey); // 4. encode it in base-64 and write it to outStream String encoded = Base64.encode(derBytes, 0, derBytes.length, true); PrintWriter writer = new PrintWriter(outStream, true); writer.println("-----BEGIN NEW CERTIFICATE REQUEST-----"); // $NON-NLS-1$ writer.println(encoded); writer.println("-----END NEW CERTIFICATE REQUEST-----"); // $NON-NLS-1$ if (verbose) { if (!systemOut) System.out.println( Messages.getFormattedString( "CertReqCmd.27", //$NON-NLS-1$ _certReqFileName)); System.out.println(Messages.getString("CertReqCmd.28")); // $NON-NLS-1$ } writer.close(); if (Configuration.DEBUG) log.exiting(this.getClass().getName(), "start"); // $NON-NLS-1$ }
/** * Reads the issuer field from the certificate. * * @return Issuer DN as an RDN sequence. */ public RDNSequence readIssuer() { return readX500Principal(certificate.getIssuerX500Principal()); }
/** @param certs */ private List sortCerts(List certs) { if (certs.size() < 2) { return certs; } X500Principal issuer = ((X509Certificate) certs.get(0)).getIssuerX500Principal(); boolean okay = true; for (int i = 1; i != certs.size(); i++) { X509Certificate cert = (X509Certificate) certs.get(i); if (issuer.equals(cert.getSubjectX500Principal())) { issuer = ((X509Certificate) certs.get(i)).getIssuerX500Principal(); } else { okay = false; break; } } if (okay) { return certs; } // find end-entity cert List retList = new ArrayList(certs.size()); List orig = new ArrayList(certs); for (int i = 0; i < certs.size(); i++) { X509Certificate cert = (X509Certificate) certs.get(i); boolean found = false; X500Principal subject = cert.getSubjectX500Principal(); for (int j = 0; j != certs.size(); j++) { X509Certificate c = (X509Certificate) certs.get(j); if (c.getIssuerX500Principal().equals(subject)) { found = true; break; } } if (!found) { retList.add(cert); certs.remove(i); } } // can only have one end entity cert - something's wrong, give up. if (retList.size() > 1) { return orig; } for (int i = 0; i != retList.size(); i++) { issuer = ((X509Certificate) retList.get(i)).getIssuerX500Principal(); for (int j = 0; j < certs.size(); j++) { X509Certificate c = (X509Certificate) certs.get(j); if (issuer.equals(c.getSubjectX500Principal())) { retList.add(c); certs.remove(j); break; } } } // make sure all certificates are accounted for. if (certs.size() > 0) { return orig; } return retList; }
/** * Reads the issuer field from the certificate. * * @return List of type/value attributes. */ public Attributes readIssuer() { return readX500Principal(certificate.getIssuerX500Principal()); }
protected static X500Principal getEncodedIssuerPrincipal(X509Certificate cert) { return cert.getIssuerX500Principal(); }
X509Certificate[] engineValidate(X509Certificate[] chain, Collection otherCerts, Object parameter) throws CertificateException { if ((chain == null) || (chain.length == 0)) { throw new CertificateException("null or zero-length certificate chain"); } if (TRY_VALIDATOR) { // check that chain is in correct order and check if chain contains // trust anchor X500Principal prevIssuer = null; for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; X500Principal dn = cert.getSubjectX500Principal(); if (i != 0 && !dn.equals(prevIssuer)) { // chain is not ordered correctly, call builder instead return doBuild(chain, otherCerts); } // Check if chain[i] is already trusted. It may be inside // trustedCerts, or has the same dn and public key as a cert // inside trustedCerts. The latter happens when a CA has // updated its cert with a stronger signature algorithm in JRE // but the weak one is still in circulation. if (trustedCerts.contains(cert) || // trusted cert (trustedSubjects.containsKey(dn) && // replacing ... trustedSubjects .get(dn) .contains( // ... weak cert cert.getPublicKey()))) { if (i == 0) { return new X509Certificate[] {chain[0]}; } // Remove and call validator on partial chain [0 .. i-1] X509Certificate[] newChain = new X509Certificate[i]; System.arraycopy(chain, 0, newChain, 0, i); return doValidate(newChain); } prevIssuer = cert.getIssuerX500Principal(); } // apparently issued by trust anchor? X509Certificate last = chain[chain.length - 1]; X500Principal issuer = last.getIssuerX500Principal(); X500Principal subject = last.getSubjectX500Principal(); if (trustedSubjects.containsKey(issuer) && isSignatureValid(trustedSubjects.get(issuer), last)) { return doValidate(chain); } // don't fallback to builder if called from plugin/webstart if (plugin) { // Validate chain even if no trust anchor is found. This // allows plugin/webstart to make sure the chain is // otherwise valid if (chain.length > 1) { X509Certificate[] newChain = new X509Certificate[chain.length - 1]; System.arraycopy(chain, 0, newChain, 0, newChain.length); // temporarily set last cert as sole trust anchor PKIXBuilderParameters params = (PKIXBuilderParameters) parameterTemplate.clone(); try { params.setTrustAnchors( Collections.singleton(new TrustAnchor(chain[chain.length - 1], null))); } catch (InvalidAlgorithmParameterException iape) { // should never occur, but ... throw new CertificateException(iape); } doValidate(newChain, params); } // if the rest of the chain is valid, throw exception // indicating no trust anchor was found throw new ValidatorException(ValidatorException.T_NO_TRUST_ANCHOR); } // otherwise, fall back to builder } return doBuild(chain, otherCerts); }
@Override protected Collection<X509CRL> getCRLs(final X509Certificate cert) { return Collections.singleton(this.crlIssuerMap.get(cert.getIssuerX500Principal())); }
/** * @param chnlId * @param xmlStr * @param chnlStr * @return */ public String processXMLForChnls(String chnlId, String xmlStr, final String chnlStr) { if ("106".equals(chnlId) || "102".equals(chnlId)) { try { xmlStr = URLEncoder.encode(xmlStr.trim(), "UTF-8"); } catch (UnsupportedEncodingException e) { } xmlStr = "xml=".concat(xmlStr); } else if ("103".equals(chnlId) && !"Route1_CONT".equals(chnlStr)) { xmlStr = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<soap:Header>" + "<SOAP-SEC:Signature xmlns:SOAP-SEC=\"http://schemas.xmlsoap.org/soap/security/2000-12\">" + "</SOAP-SEC:Signature>" + "</soap:Header>".concat(xmlStr).concat("</soap:Envelope>"); try { // Create a DOM XMLSignatureFactory that will be used to // generate the enveloped signature. XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); Reference ref = fac.newReference( "#Body", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList( fac.newTransform( "http://www.w3.org/2001/10/xml-exc-c14n#", (TransformParameterSpec) null)), null, null); // Create the SignedInfo. SignedInfo si = fac.newSignedInfo( fac.newCanonicalizationMethod( CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref)); // Load the KeyStore and get the signing key and // certificate. KeyStore ks = KeyStore.getInstance("JKS"); String certFileNm = ""; // commonConfigHelper.getConfigMap().get( // "ROUTE1_CERTIFICATE_JSK"); String pwd = ""; // commonConfigHelper.getConfigMap().get( // "ROUTE1_CERTIFICATE_PASSWORD"); String aliasNm = ""; // commonConfigHelper.getConfigMap().get( // "ROUTE1_CERTIFICATE_ALIAS"); ks.load(new FileInputStream(certFileNm), pwd.toCharArray()); KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(aliasNm, new KeyStore.PasswordProtection(pwd.toCharArray())); X509Certificate cert = (X509Certificate) keyEntry.getCertificate(); // Create the KeyInfo containing the X509Data. KeyInfoFactory kif = fac.getKeyInfoFactory(); List x509Content = new ArrayList(); // x509Content.add(cert.getSubjectX500Principal().getName()); x509Content.add(cert.getIssuerX500Principal().getName()); X509Data xd = kif.newX509Data(x509Content); KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd)); // Instantiate the document to be signed. // Document doc = xmlUtil.getDocumentFromString(xmlStr); Document doc = null; // Create a DOMSignContext and specify the RSA PrivateKey // and // location of the resulting XMLSignature's parent element. DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), doc.getDocumentElement()); // Create the XMLSignature, but don't sign it yet. XMLSignature signature = fac.newXMLSignature(si, ki); // Marshal, generate, and sign the enveloped signature. signature.sign(dsc); // Output the resulting document. xmlStr = xmlUtil.convertXMLDocToString(doc); } catch (Exception e) { } } return xmlStr; }