List of usage examples for java.security.cert X509Certificate getSubjectDN
public abstract Principal getSubjectDN();
From source file:org.ejbca.core.protocol.scep.ProtocolScepHttpTest.java
private void checkScepResponse(byte[] retMsg, String userDN, String _senderNonce, String _transId, boolean crlRep, String digestOid, boolean noca) throws CMSException, OperatorCreationException, NoSuchProviderException, CRLException, InvalidKeyException, NoSuchAlgorithmException, SignatureException, CertificateException { // Parse response message ////from w w w . j av a 2 s.c o m CMSSignedData s = new CMSSignedData(retMsg); // The signer, i.e. the CA, check it's the right CA SignerInformationStore signers = s.getSignerInfos(); @SuppressWarnings("unchecked") Collection<SignerInformation> col = signers.getSigners(); assertTrue(col.size() > 0); Iterator<SignerInformation> iter = col.iterator(); SignerInformation signerInfo = iter.next(); // Check that the message is signed with the correct digest alg assertEquals(signerInfo.getDigestAlgOID(), digestOid); SignerId sinfo = signerInfo.getSID(); // Check that the signer is the expected CA assertEquals(CertTools.stringToBCDNString(cacert.getIssuerDN().getName()), CertTools.stringToBCDNString(sinfo.getIssuer().toString())); // Verify the signature JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME); JcaSignerInfoVerifierBuilder jcaSignerInfoVerifierBuilder = new JcaSignerInfoVerifierBuilder( calculatorProviderBuilder.build()).setProvider(BouncyCastleProvider.PROVIDER_NAME); boolean ret = signerInfo.verify(jcaSignerInfoVerifierBuilder.build(cacert.getPublicKey())); assertTrue(ret); // Get authenticated attributes AttributeTable tab = signerInfo.getSignedAttributes(); // --Fail info Attribute attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_failInfo)); // No failInfo on this success message assertNull(attr); // --Message type attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_messageType)); assertNotNull(attr); ASN1Set values = attr.getAttrValues(); assertEquals(values.size(), 1); ASN1String str = DERPrintableString.getInstance((values.getObjectAt(0))); String messageType = str.getString(); assertEquals("3", messageType); // --Success status attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_pkiStatus)); assertNotNull(attr); values = attr.getAttrValues(); assertEquals(values.size(), 1); str = DERPrintableString.getInstance((values.getObjectAt(0))); assertEquals(ResponseStatus.SUCCESS.getStringValue(), str.getString()); // --SenderNonce attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_senderNonce)); assertNotNull(attr); values = attr.getAttrValues(); assertEquals(values.size(), 1); ASN1OctetString octstr = ASN1OctetString.getInstance(values.getObjectAt(0)); // SenderNonce is something the server came up with, but it should be 16 // chars assertTrue(octstr.getOctets().length == 16); // --Recipient Nonce attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_recipientNonce)); assertNotNull(attr); values = attr.getAttrValues(); assertEquals(values.size(), 1); octstr = ASN1OctetString.getInstance(values.getObjectAt(0)); // recipient nonce should be the same as we sent away as sender nonce assertEquals(_senderNonce, new String(Base64.encode(octstr.getOctets()))); // --Transaction ID attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_transId)); assertNotNull(attr); values = attr.getAttrValues(); assertEquals(values.size(), 1); str = DERPrintableString.getInstance((values.getObjectAt(0))); // transid should be the same as the one we sent assertEquals(_transId, str.getString()); // // Check different message types // if (messageType.equals("3")) { // First we extract the encrypted data from the CMS enveloped data // contained // within the CMS signed data final CMSProcessable sp = s.getSignedContent(); final byte[] content = (byte[]) sp.getContent(); final CMSEnvelopedData ed = new CMSEnvelopedData(content); final RecipientInformationStore recipients = ed.getRecipientInfos(); Store certstore; @SuppressWarnings("unchecked") Collection<RecipientInformation> c = recipients.getRecipients(); assertEquals(c.size(), 1); Iterator<RecipientInformation> riIterator = c.iterator(); byte[] decBytes = null; RecipientInformation recipient = riIterator.next(); JceKeyTransEnvelopedRecipient rec = new JceKeyTransEnvelopedRecipient(key1.getPrivate()); rec.setContentProvider(BouncyCastleProvider.PROVIDER_NAME); decBytes = recipient.getContent(rec); // This is yet another CMS signed data CMSSignedData sd = new CMSSignedData(decBytes); // Get certificates from the signed data certstore = sd.getCertificates(); if (crlRep) { // We got a reply with a requested CRL @SuppressWarnings("unchecked") final Collection<X509CRLHolder> crls = (Collection<X509CRLHolder>) sd.getCRLs().getMatches(null); assertEquals(crls.size(), 1); final Iterator<X509CRLHolder> it = crls.iterator(); // CRL is first (and only) final X509CRL retCrl = new JcaX509CRLConverter().getCRL(it.next()); log.info("Got CRL with DN: " + retCrl.getIssuerDN().getName()); // check the returned CRL assertEquals(CertTools.getSubjectDN(cacert), CertTools.getIssuerDN(retCrl)); retCrl.verify(cacert.getPublicKey()); } else { // We got a reply with a requested certificate @SuppressWarnings("unchecked") final Collection<X509CertificateHolder> certs = (Collection<X509CertificateHolder>) certstore .getMatches(null); // EJBCA returns the issued cert and the CA cert (cisco vpn // client requires that the ca cert is included) if (noca) { assertEquals(certs.size(), 1); } else { assertEquals(certs.size(), 2); } final Iterator<X509CertificateHolder> it = certs.iterator(); // Issued certificate must be first boolean verified = false; boolean gotcacert = false; JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter(); while (it.hasNext()) { X509Certificate retcert = jcaX509CertificateConverter.getCertificate(it.next()); log.info("Got cert with DN: " + retcert.getSubjectDN().getName()); // check the returned certificate String subjectdn = CertTools.stringToBCDNString(retcert.getSubjectDN().getName()); if (CertTools.stringToBCDNString(userDN).equals(subjectdn)) { // issued certificate assertEquals(CertTools.stringToBCDNString(userDN), subjectdn); assertEquals(CertTools.getSubjectDN(cacert), CertTools.getIssuerDN(retcert)); retcert.verify(cacert.getPublicKey()); assertTrue(checkKeys(key1.getPrivate(), retcert.getPublicKey())); verified = true; } else { // ca certificate assertEquals(CertTools.getSubjectDN(cacert), CertTools.getSubjectDN(retcert)); gotcacert = true; } } assertTrue(verified); if (noca) { assertFalse(gotcacert); } else { assertTrue(gotcacert); } } } }
From source file:org.wso2.carbon.security.keystore.KeyStoreAdmin.java
public String importCertToStore(String certData, String keyStoreName) throws SecurityConfigException { String alias = null;// w ww . j a va2 s. c o m try { if (keyStoreName == null) { throw new SecurityConfigException("Key Store name can't be null"); } KeyStoreManager keyMan = KeyStoreManager.getInstance(tenantId); KeyStore ks = keyMan.getKeyStore(keyStoreName); byte[] bytes = Base64.decode(certData); CertificateFactory factory = CertificateFactory.getInstance("X.509"); X509Certificate cert; try { cert = (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(bytes)); } catch (Exception e) { throw new SecurityConfigException("Invalid format of the provided certificate file", e); } if (ks.getCertificateAlias(cert) != null) { // We already have this certificate in the key store - ignore // adding it twice return null; } alias = cert.getSubjectDN().getName(); ks.setCertificateEntry(alias, cert); keyMan.updateKeyStore(keyStoreName, ks); return alias; } catch (SecurityConfigException e) { throw e; } catch (Exception e) { String msg = "Error when importing cert to keyStore"; log.error(msg, e); throw new SecurityConfigException(msg); } }
From source file:net.sf.jsignpdf.SignerLogic.java
/** * Signs a single file.// w ww . jav a 2 s . co m * * @return true when signing is finished succesfully, false otherwise */ public boolean signFile() { final String outFile = options.getOutFileX(); if (!validateInOutFiles(options.getInFile(), outFile)) { LOGGER.info(RES.get("console.skippingSigning")); return false; } boolean finished = false; Throwable tmpException = null; FileOutputStream fout = null; try { SSLInitializer.init(options); final PrivateKeyInfo pkInfo = KeyStoreUtils.getPkInfo(options); final PrivateKey key = pkInfo.getKey(); final Certificate[] chain = pkInfo.getChain(); if (ArrayUtils.isEmpty(chain)) { // the certificate was not found LOGGER.info(RES.get("console.certificateChainEmpty")); return false; } LOGGER.info(RES.get("console.createPdfReader", options.getInFile())); PdfReader reader; try { reader = new PdfReader(options.getInFile(), options.getPdfOwnerPwdStrX().getBytes()); } catch (Exception e) { try { reader = new PdfReader(options.getInFile(), new byte[0]); } catch (Exception e2) { // try to read without password reader = new PdfReader(options.getInFile()); } } LOGGER.info(RES.get("console.createOutPdf", outFile)); fout = new FileOutputStream(outFile); final HashAlgorithm hashAlgorithm = options.getHashAlgorithmX(); LOGGER.info(RES.get("console.createSignature")); char tmpPdfVersion = '\0'; // default version - the same as input if (reader.getPdfVersion() < hashAlgorithm.getPdfVersion()) { // this covers also problems with visible signatures (embedded // fonts) in PDF 1.2, because the minimal version // for hash algorithms is 1.3 (for SHA1) if (options.isAppendX()) { // if we are in append mode and version should be updated // then return false (not possible) LOGGER.info(RES.get("console.updateVersionNotPossibleInAppendMode")); return false; } tmpPdfVersion = hashAlgorithm.getPdfVersion(); LOGGER.info(RES.get("console.updateVersion", new String[] { String.valueOf(reader.getPdfVersion()), String.valueOf(tmpPdfVersion) })); } final PdfStamper stp = PdfStamper.createSignature(reader, fout, tmpPdfVersion, null, options.isAppendX()); if (!options.isAppendX()) { // we are not in append mode, let's remove existing signatures // (otherwise we're getting to troubles) final AcroFields acroFields = stp.getAcroFields(); @SuppressWarnings("unchecked") final List<String> sigNames = acroFields.getSignatureNames(); for (String sigName : sigNames) { acroFields.removeField(sigName); } } if (options.isAdvanced() && options.getPdfEncryption() != PDFEncryption.NONE) { LOGGER.info(RES.get("console.setEncryption")); final int tmpRight = options.getRightPrinting().getRight() | (options.isRightCopy() ? PdfWriter.ALLOW_COPY : 0) | (options.isRightAssembly() ? PdfWriter.ALLOW_ASSEMBLY : 0) | (options.isRightFillIn() ? PdfWriter.ALLOW_FILL_IN : 0) | (options.isRightScreanReaders() ? PdfWriter.ALLOW_SCREENREADERS : 0) | (options.isRightModifyAnnotations() ? PdfWriter.ALLOW_MODIFY_ANNOTATIONS : 0) | (options.isRightModifyContents() ? PdfWriter.ALLOW_MODIFY_CONTENTS : 0); switch (options.getPdfEncryption()) { case PASSWORD: stp.setEncryption(true, options.getPdfUserPwdStr(), options.getPdfOwnerPwdStrX(), tmpRight); break; case CERTIFICATE: final X509Certificate encCert = KeyStoreUtils .loadCertificate(options.getPdfEncryptionCertFile()); if (encCert == null) { LOGGER.error(RES.get("console.pdfEncError.wrongCertificateFile", StringUtils.defaultString(options.getPdfEncryptionCertFile()))); return false; } if (!KeyStoreUtils.isEncryptionSupported(encCert)) { LOGGER.error(RES.get("console.pdfEncError.cantUseCertificate", encCert.getSubjectDN().getName())); return false; } stp.setEncryption(new Certificate[] { encCert }, new int[] { tmpRight }, PdfWriter.ENCRYPTION_AES_128); break; default: LOGGER.error(RES.get("console.unsupportedEncryptionType")); return false; } } final PdfSignatureAppearance sap = stp.getSignatureAppearance(); sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); final String reason = options.getReason(); if (StringUtils.isNotEmpty(reason)) { LOGGER.info(RES.get("console.setReason", reason)); sap.setReason(reason); } final String location = options.getLocation(); if (StringUtils.isNotEmpty(location)) { LOGGER.info(RES.get("console.setLocation", location)); sap.setLocation(location); } final String contact = options.getContact(); if (StringUtils.isNotEmpty(contact)) { LOGGER.info(RES.get("console.setContact", contact)); sap.setContact(contact); } LOGGER.info(RES.get("console.setCertificationLevel")); sap.setCertificationLevel(options.getCertLevelX().getLevel()); if (options.isVisible()) { // visible signature is enabled LOGGER.info(RES.get("console.configureVisible")); LOGGER.info(RES.get("console.setAcro6Layers", Boolean.toString(options.isAcro6Layers()))); sap.setAcro6Layers(options.isAcro6Layers()); final String tmpImgPath = options.getImgPath(); if (tmpImgPath != null) { LOGGER.info(RES.get("console.createImage", tmpImgPath)); final Image img = Image.getInstance(tmpImgPath); LOGGER.info(RES.get("console.setSignatureGraphic")); sap.setSignatureGraphic(img); } final String tmpBgImgPath = options.getBgImgPath(); if (tmpBgImgPath != null) { LOGGER.info(RES.get("console.createImage", tmpBgImgPath)); final Image img = Image.getInstance(tmpBgImgPath); LOGGER.info(RES.get("console.setImage")); sap.setImage(img); } LOGGER.info(RES.get("console.setImageScale")); sap.setImageScale(options.getBgImgScale()); LOGGER.info(RES.get("console.setL2Text")); final String signer = PdfPKCS7.getSubjectFields((X509Certificate) chain[0]).getField("CN"); final String timestamp = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z") .format(sap.getSignDate().getTime()); if (options.getL2Text() != null) { final Map<String, String> replacements = new HashMap<String, String>(); replacements.put(L2TEXT_PLACEHOLDER_SIGNER, StringUtils.defaultString(signer)); replacements.put(L2TEXT_PLACEHOLDER_TIMESTAMP, timestamp); replacements.put(L2TEXT_PLACEHOLDER_LOCATION, StringUtils.defaultString(location)); replacements.put(L2TEXT_PLACEHOLDER_REASON, StringUtils.defaultString(reason)); replacements.put(L2TEXT_PLACEHOLDER_CONTACT, StringUtils.defaultString(contact)); final String l2text = StrSubstitutor.replace(options.getL2Text(), replacements); sap.setLayer2Text(l2text); } else { final StringBuilder buf = new StringBuilder(); buf.append(RES.get("default.l2text.signedBy")).append(" ").append(signer).append('\n'); buf.append(RES.get("default.l2text.date")).append(" ").append(timestamp); if (StringUtils.isNotEmpty(reason)) buf.append('\n').append(RES.get("default.l2text.reason")).append(" ").append(reason); if (StringUtils.isNotEmpty(location)) buf.append('\n').append(RES.get("default.l2text.location")).append(" ").append(location); sap.setLayer2Text(buf.toString()); } if (FontUtils.getL2BaseFont() != null) { sap.setLayer2Font(new Font(FontUtils.getL2BaseFont(), options.getL2TextFontSize())); } LOGGER.info(RES.get("console.setL4Text")); sap.setLayer4Text(options.getL4Text()); LOGGER.info(RES.get("console.setRender")); RenderMode renderMode = options.getRenderMode(); if (renderMode == RenderMode.GRAPHIC_AND_DESCRIPTION && sap.getSignatureGraphic() == null) { LOGGER.warn( "Render mode of visible signature is set to GRAPHIC_AND_DESCRIPTION, but no image is loaded. Fallback to DESCRIPTION_ONLY."); LOGGER.info(RES.get("console.renderModeFallback")); renderMode = RenderMode.DESCRIPTION_ONLY; } sap.setRender(renderMode.getRender()); LOGGER.info(RES.get("console.setVisibleSignature")); int page = options.getPage(); if (page < 1 || page > reader.getNumberOfPages()) { page = reader.getNumberOfPages(); } sap.setVisibleSignature(new Rectangle(options.getPositionLLX(), options.getPositionLLY(), options.getPositionURX(), options.getPositionURY()), page, null); } LOGGER.info(RES.get("console.processing")); final PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached")); if (!StringUtils.isEmpty(reason)) { dic.setReason(sap.getReason()); } if (!StringUtils.isEmpty(location)) { dic.setLocation(sap.getLocation()); } if (!StringUtils.isEmpty(contact)) { dic.setContact(sap.getContact()); } dic.setDate(new PdfDate(sap.getSignDate())); sap.setCryptoDictionary(dic); final Proxy tmpProxy = options.createProxy(); final CRLInfo crlInfo = new CRLInfo(options, chain); // CRLs are stored twice in PDF c.f. // PdfPKCS7.getAuthenticatedAttributeBytes final int contentEstimated = (int) (Constants.DEFVAL_SIG_SIZE + 2L * crlInfo.getByteCount()); final Map<PdfName, Integer> exc = new HashMap<PdfName, Integer>(); exc.put(PdfName.CONTENTS, new Integer(contentEstimated * 2 + 2)); sap.preClose(exc); PdfPKCS7 sgn = new PdfPKCS7(key, chain, crlInfo.getCrls(), hashAlgorithm.getAlgorithmName(), null, false); InputStream data = sap.getRangeStream(); final MessageDigest messageDigest = MessageDigest.getInstance(hashAlgorithm.getAlgorithmName()); byte buf[] = new byte[8192]; int n; while ((n = data.read(buf)) > 0) { messageDigest.update(buf, 0, n); } byte hash[] = messageDigest.digest(); Calendar cal = Calendar.getInstance(); byte[] ocsp = null; if (options.isOcspEnabledX() && chain.length >= 2) { LOGGER.info(RES.get("console.getOCSPURL")); String url = PdfPKCS7.getOCSPURL((X509Certificate) chain[0]); if (StringUtils.isEmpty(url)) { // get from options LOGGER.info(RES.get("console.noOCSPURL")); url = options.getOcspServerUrl(); } if (!StringUtils.isEmpty(url)) { LOGGER.info(RES.get("console.readingOCSP", url)); final OcspClientBouncyCastle ocspClient = new OcspClientBouncyCastle((X509Certificate) chain[0], (X509Certificate) chain[1], url); ocspClient.setProxy(tmpProxy); ocsp = ocspClient.getEncoded(); } } byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp); sgn.update(sh, 0, sh.length); TSAClientBouncyCastle tsc = null; if (options.isTimestampX() && !StringUtils.isEmpty(options.getTsaUrl())) { LOGGER.info(RES.get("console.creatingTsaClient")); if (options.getTsaServerAuthn() == ServerAuthentication.PASSWORD) { tsc = new TSAClientBouncyCastle(options.getTsaUrl(), StringUtils.defaultString(options.getTsaUser()), StringUtils.defaultString(options.getTsaPasswd())); } else { tsc = new TSAClientBouncyCastle(options.getTsaUrl()); } final String tsaHashAlg = options.getTsaHashAlgWithFallback(); LOGGER.info(RES.get("console.settingTsaHashAlg", tsaHashAlg)); tsc.setHashAlgorithm(tsaHashAlg); tsc.setProxy(tmpProxy); final String policyOid = options.getTsaPolicy(); if (StringUtils.isNotEmpty(policyOid)) { LOGGER.info(RES.get("console.settingTsaPolicy", policyOid)); tsc.setPolicy(policyOid); } } byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsc, ocsp); if (contentEstimated + 2 < encodedSig.length) { System.err.println( "SigSize - contentEstimated=" + contentEstimated + ", sigLen=" + encodedSig.length); throw new Exception("Not enough space"); } byte[] paddedSig = new byte[contentEstimated]; System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length); PdfDictionary dic2 = new PdfDictionary(); dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true)); LOGGER.info(RES.get("console.closeStream")); sap.close(dic2); fout.close(); fout = null; finished = true; } catch (Exception e) { LOGGER.error(RES.get("console.exception"), e); } catch (OutOfMemoryError e) { LOGGER.fatal(RES.get("console.memoryError"), e); } finally { if (fout != null) { try { fout.close(); } catch (Exception e) { e.printStackTrace(); } } LOGGER.info(RES.get("console.finished." + (finished ? "ok" : "error"))); options.fireSignerFinishedEvent(tmpException); } return finished; }
From source file:org.apache.juddi.v3.client.cryptor.DigSigUtil.java
/** * Verifies the signature on an enveloped digital signature on a UDDI * entity, such as a business, service, tmodel or binding template. * <br><Br>/*from ww w.j ava2 s . c o m*/ * It is expected that either the public key of the signing certificate * is included within the signature keyinfo section OR that sufficient * information is provided in the signature to reference a public key * located within the Trust Store provided<br><Br> Optionally, this * function also validate the signing certificate using the options * provided to the configuration map. * * @param obj an enveloped signed JAXB object * @param OutErrorMessage a human readable error message explaining the * reason for failure * @return true if the validation passes the signature validation test, * and optionally any certificate validation or trust chain validation * @throws IllegalArgumentException for null input */ public boolean verifySignedUddiEntity(Object obj, AtomicReference<String> OutErrorMessage) throws IllegalArgumentException { if (OutErrorMessage == null) { OutErrorMessage = new AtomicReference<String>(); OutErrorMessage.set(""); } if (obj == null) { throw new IllegalArgumentException("obj"); } try { DOMResult domResult = new DOMResult(); JAXB.marshal(obj, domResult); Document doc = ((Document) domResult.getNode()); Element docElement = doc.getDocumentElement(); //this is our signed node X509Certificate signingcert = getSigningCertificatePublicKey(docElement); if (signingcert != null) { logger.info( "verifying signature based on X509 public key " + signingcert.getSubjectDN().toString()); if (map.containsKey(CHECK_TIMESTAMPS) && Boolean.parseBoolean(map.getProperty(CHECK_TIMESTAMPS))) { signingcert.checkValidity(); } if (map.containsKey(CHECK_REVOCATION_STATUS_OCSP) && Boolean.parseBoolean(map.getProperty(CHECK_REVOCATION_STATUS_OCSP))) { logger.info("verifying revocation status via OSCP for X509 public key " + signingcert.getSubjectDN().toString()); X500Principal issuerX500Principal = signingcert.getIssuerX500Principal(); logger.info("certificate " + signingcert.getSubjectDN().toString() + " was issued by " + issuerX500Principal.getName() + ", attempting to retrieve certificate"); Security.setProperty("ocsp.enable", "false"); X509Certificate issuer = FindCertByDN(issuerX500Principal); if (issuer == null) { OutErrorMessage.set( "Unable to verify certificate status from OCSP because the issuer of the certificate is not in the trust store. " + OutErrorMessage.get()); //throw new CertificateException("unable to locate the issuers certificate in the trust store"); } else { RevocationStatus check = OCSP.check(signingcert, issuer); logger.info("certificate " + signingcert.getSubjectDN().toString() + " revocation status is " + check.getCertStatus().toString() + " reason " + check.getRevocationReason().toString()); if (check.getCertStatus() != RevocationStatus.CertStatus.GOOD) { OutErrorMessage .set("Certificate status is " + check.getCertStatus().toString() + " reason " + check.getRevocationReason().toString() + "." + OutErrorMessage.get()); //throw new CertificateException("Certificate status is " + check.getCertStatus().toString() + " reason " + check.getRevocationReason().toString()); } } } if (map.containsKey(CHECK_REVOCATION_STATUS_CRL) && Boolean.parseBoolean(map.getProperty(CHECK_REVOCATION_STATUS_CRL))) { logger.info("verifying revokation status via CRL for X509 public key " + signingcert.getSubjectDN().toString()); Security.setProperty("ocsp.enable", "false"); System.setProperty("com.sun.security.enableCRLDP", "true"); X509CertSelector targetConstraints = new X509CertSelector(); targetConstraints.setCertificate(signingcert); PKIXParameters params = new PKIXParameters(GetTrustStore()); params.setRevocationEnabled(true); CertPath certPath = cf.generateCertPath(Arrays.asList(signingcert)); CertPathValidator certPathValidator = CertPathValidator .getInstance(CertPathValidator.getDefaultType()); CertPathValidatorResult result = certPathValidator.validate(certPath, params); try { PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result; logger.info("revokation status via CRL PASSED for X509 public key " + signingcert.getSubjectDN().toString()); } catch (Exception ex) { OutErrorMessage.set("Certificate status is via CRL Failed: " + ex.getMessage() + "." + OutErrorMessage.get()); } } if (map.containsKey(CHECK_TRUST_CHAIN) && Boolean.parseBoolean(map.getProperty(CHECK_TRUST_CHAIN))) { logger.info("verifying trust chain X509 public key " + signingcert.getSubjectDN().toString()); try { PKIXParameters params = new PKIXParameters(GetTrustStore()); params.setRevocationEnabled(false); CertPath certPath = cf.generateCertPath(Arrays.asList(signingcert)); CertPathValidator certPathValidator = CertPathValidator .getInstance(CertPathValidator.getDefaultType()); CertPathValidatorResult result = certPathValidator.validate(certPath, params); PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result; TrustAnchor ta = pkixResult.getTrustAnchor(); X509Certificate cert = ta.getTrustedCert(); logger.info( "trust chain validated X509 public key " + signingcert.getSubjectDN().toString()); } catch (Exception ex) { OutErrorMessage.set("Certificate status Trust validation failed: " + ex.getMessage() + "." + OutErrorMessage.get()); } } boolean b = verifySignature(docElement, signingcert.getPublicKey(), OutErrorMessage); if ((OutErrorMessage.get() == null || OutErrorMessage.get().length() == 0) && b) { //no error message and its cryptographically valid return true; } return false; } //last chance validation logger.info( "signature did not have an embedded X509 public key. reverting to user specified certificate"); //cert wasn't included in the signature, revert to some other means KeyStore ks = KeyStore.getInstance(map.getProperty(SIGNATURE_KEYSTORE_FILETYPE)); URL url = Thread.currentThread().getContextClassLoader() .getResource(map.getProperty(SIGNATURE_KEYSTORE_FILE)); if (url == null) { try { url = new File(map.getProperty(SIGNATURE_KEYSTORE_FILE)).toURI().toURL(); } catch (Exception x) { } } if (url == null) { try { url = this.getClass().getClassLoader().getResource(map.getProperty(SIGNATURE_KEYSTORE_FILE)); } catch (Exception x) { } } if (url == null) { logger.error(""); OutErrorMessage.set("The signed entity is signed but does not have a certificate attached and" + "you didn't specify a keystore for me to look it up in. " + OutErrorMessage.get()); return false; } KeyStore.PrivateKeyEntry keyEntry = null; ks.load(url.openStream(), map.getProperty(SIGNATURE_KEYSTORE_FILE_PASSWORD).toCharArray()); if (map.getProperty(SIGNATURE_KEYSTORE_KEY_PASSWORD) == null) { keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(map.getProperty(SIGNATURE_KEYSTORE_KEY_ALIAS), new KeyStore.PasswordProtection( map.getProperty(SIGNATURE_KEYSTORE_FILE_PASSWORD).toCharArray())); } else { keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(map.getProperty(SIGNATURE_KEYSTORE_KEY_ALIAS), new KeyStore.PasswordProtection( map.getProperty(SIGNATURE_KEYSTORE_KEY_PASSWORD).toCharArray())); } Certificate origCert = keyEntry.getCertificate(); if (map.containsKey(CHECK_TIMESTAMPS)) { if (origCert.getPublicKey() instanceof X509Certificate) { X509Certificate x = (X509Certificate) origCert.getPublicKey(); x.checkValidity(); } } PublicKey validatingKey = origCert.getPublicKey(); return verifySignature(docElement, validatingKey, OutErrorMessage); } catch (Exception e) { //throw new RuntimeException(e); logger.error("Error caught validating signature", e); OutErrorMessage.set(e.getMessage()); return false; } }
From source file:com.tremolosecurity.idp.providers.OpenIDConnectIdP.java
private String buildKID(X509Certificate cert) { StringBuffer b = new StringBuffer(); b.append(cert.getSubjectDN().getName()).append('-').append(cert.getIssuerDN().getName()).append('-') .append(cert.getSerialNumber().toString()); return b.toString(); }
From source file:org.apache.juddi.v3.client.cryptor.DigSigUtil.java
private void signDOM(Node node, PrivateKey privateKey, Certificate origCert) { XMLSignatureFactory fac = initXMLSigFactory(); X509Certificate cert = (X509Certificate) origCert; // Create the KeyInfo containing the X509Data. KeyInfoFactory kif = fac.getKeyInfoFactory(); List<Object> x509Content = null;//new ArrayList<Object>(); List<X509Data> data = new ArrayList<X509Data>(); if (map.containsKey(SIGNATURE_OPTION_CERT_INCLUSION_SUBJECTDN)) { x509Content = new ArrayList<Object>(); x509Content.add(cert.getSubjectDN().getName()); // x509Content.add(cert); //x509Content.add(cert.getSubjectDN().getName()); X509Data xd = kif.newX509Data(x509Content); data.add(xd);//ww w .jav a 2s .c o m } // if (map.containsKey(SIGNATURE_OPTION_CERT_INCLUSION_X500_PRINICPAL)) { // } if (map.containsKey(SIGNATURE_OPTION_CERT_INCLUSION_BASE64)) { x509Content = new ArrayList<Object>(); x509Content.add(cert); //x509Content.add(cert.getSubjectX500Principal().getName()); X509Data xd = kif.newX509Data(x509Content); data.add(xd); } if (map.containsKey(SIGNATURE_OPTION_CERT_INCLUSION_SERIAL)) { x509Content = new ArrayList<Object>(); X509IssuerSerial issuer = kif.newX509IssuerSerial(cert.getIssuerX500Principal().getName(), cert.getSerialNumber()); x509Content.add(issuer); X509Data xd = kif.newX509Data(x509Content); data.add(xd); } // //x509Content.add(cert); KeyInfo ki = kif.newKeyInfo(data); // Create a DOMSignContext and specify the RSA PrivateKey and // location of the resulting XMLSignature's parent element. DOMSignContext dsc = new DOMSignContext(privateKey, node); dsc.putNamespacePrefix(XML_DIGSIG_NS, "ns2"); // Create the XMLSignature, but don't sign it yet. try { SignedInfo si = initSignedInfo(fac); XMLSignature signature = fac.newXMLSignature(si, ki); // Marshal, generate, and sign the enveloped signature. signature.sign(dsc); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.apache.hadoop.security.ssl.TestReloadingX509KeyManager.java
@Test public void testReloadWithPasswordfile() throws Exception { KeyPair keyPair = KeyStoreTestUtil.generateKeyPair(KEY_PAIR_ALGORITHM); X509Certificate cert1 = KeyStoreTestUtil.generateCertificate("CN=cert1", keyPair, 2, CERTIFICATE_ALGORITHM); String keyStoreLocation = Paths.get(BASE_DIR, "testKeystore.jks").toString(); KeyStoreTestUtil.createKeyStore(keyStoreLocation, KEYSTORE_PASSWORD, "cert1", keyPair.getPrivate(), cert1); String passwordFileLocation = Paths.get(BASE_DIR, "password_file").toString(); FileUtils.write(new File(passwordFileLocation), KEYSTORE_PASSWORD); ReloadingX509KeyManager keyManager = new ReloadingX509KeyManager("jks", keyStoreLocation, "wrong-password", passwordFileLocation, "wrong-password", 10, TimeUnit.MILLISECONDS); try {// w ww .j a v a2 s . c o m keyManager.init(); TimeUnit reloadTimeUnit = keyManager.getReloadTimeUnit(); long reloadInterval = keyManager.getReloadInterval(); X509Certificate[] certChain = keyManager.getCertificateChain("cert1"); assertNotNull("Certificate chain should not be null for alias cert1", certChain); assertEquals("Certificate chain should be 1", 1, certChain.length); assertEquals("DN for cert1 should be CN=cert1", cert1.getSubjectDN().getName(), certChain[0].getSubjectDN().getName()); // Wait a bit for the modification time to be different reloadTimeUnit.sleep(reloadInterval); TimeUnit.SECONDS.sleep(1); // Replace keystore with a new one with a different DN X509Certificate cert2 = KeyStoreTestUtil.generateCertificate("CN=cert2", keyPair, 2, CERTIFICATE_ALGORITHM); String newKeystorePassword = "password1"; KeyStoreTestUtil.createKeyStore(keyStoreLocation, newKeystorePassword, "cert2", keyPair.getPrivate(), cert2); FileUtils.write(new File(passwordFileLocation), newKeystorePassword); reloadTimeUnit.sleep(reloadInterval * 2); certChain = keyManager.getCertificateChain("cert1"); assertNull("Certificate chain for alias cert1 should be null", certChain); certChain = keyManager.getCertificateChain("cert2"); assertNotNull("Certificate chain should not be null for alias cert2", certChain); assertEquals("Certificate chain should be 1", 1, certChain.length); assertEquals("DN for cert2 should be CN=cert2", cert2.getSubjectDN().getName(), certChain[0].getSubjectDN().getName()); } finally { keyManager.stop(); } }
From source file:net.solarnetwork.node.setup.impl.DefaultKeystoreService.java
private void saveNodeCertificateChain(KeyStore keyStore, Key key, String keyPassword, X509Certificate nodeCert, X509Certificate[] chain) { if (keyPassword == null) { keyPassword = ""; }//w w w .ja va 2s .c o m X509Certificate caCert = getCACertificate(keyStore); if (chain.length < 1) { throw new CertificateException("No certificates avaialble"); } if (chain.length > 1) { // we have to trust the parents... the end of the chain must be our CA try { final int caIdx = chain.length - 1; if (caCert == null) { // if we don't have a CA cert yet, install that now log.info("Installing trusted CA certificate {}", chain[caIdx].getSubjectDN()); keyStore.setCertificateEntry(caAlias, chain[caIdx]); caCert = chain[caIdx]; } else { // verify CA is the same... maybe we shouldn't do this? if (!chain[caIdx].getSubjectDN().equals(caCert.getSubjectDN())) { throw new CertificateException("Chain CA " + chain[caIdx].getSubjectDN().getName() + " does not match expected " + caCert.getSubjectDN().getName()); } if (!chain[caIdx].getIssuerDN().equals(caCert.getIssuerDN())) { throw new CertificateException("Chain CA " + chain[caIdx].getIssuerDN().getName() + " does not match expected " + caCert.getIssuerDN().getName()); } } // install intermediate certs... for (int i = caIdx - 1, j = 1; i > 0; i--, j++) { String alias = caAlias + "sub" + j; log.info("Installing trusted intermediate certificate {}", chain[i].getSubjectDN()); keyStore.setCertificateEntry(alias, chain[i]); } } catch (KeyStoreException e) { throw new CertificateException("Error storing CA chain", e); } } else { // put CA at end of chain if (caCert == null) { throw new CertificateException("No CA certificate available"); } chain = new X509Certificate[] { chain[0], caCert }; } // the issuer must be our CA cert subject... if (!chain[0].getIssuerDN().equals(chain[1].getSubjectDN())) { throw new CertificateException("Issuer " + chain[0].getIssuerDN().getName() + " does not match expected " + chain[1].getSubjectDN().getName()); } // the subject must be our node's existing subject... if (!chain[0].getSubjectDN().equals(nodeCert.getSubjectDN())) { throw new CertificateException("Subject " + chain[0].getIssuerDN().getName() + " does not match expected " + nodeCert.getSubjectDN().getName()); } log.info("Installing node certificate {} reply {} issued by {}", chain[0].getSerialNumber(), chain[0].getSubjectDN().getName(), chain[0].getIssuerDN().getName()); try { keyStore.setKeyEntry(nodeAlias, key, keyPassword.toCharArray(), chain); } catch (KeyStoreException e) { throw new CertificateException("Error opening node certificate", e); } }
From source file:org.signserver.client.cli.validationservice.ValidateCertificateCommand.java
private int run() throws Exception { // read certificate X509Certificate cert = null; FileInputStream fis = new FileInputStream(certPath); try {/*from w w w.j av a2 s . co m*/ if (pemFlag) { Collection<?> certs = CertTools.getCertsFromPEM(fis); if (certs.iterator().hasNext()) { cert = (X509Certificate) certs.iterator().next(); } } else { byte[] data = new byte[fis.available()]; fis.read(data, 0, fis.available()); cert = (X509Certificate) CertTools.getCertfromByteArray(data); } } finally { fis.close(); } if (cert == null) { println("Error, Certificate in file " + certPath + " not read succesfully."); } println("\n\nValidating certificate with: "); println(" Subject : " + cert.getSubjectDN().toString()); println(" Issuer : " + cert.getIssuerDN().toString()); println(" Valid From : " + cert.getNotBefore()); println(" Valid To : " + cert.getNotAfter()); println("\n"); // validate final ValidateResponse vresp; switch (protocol) { case WEBSERVICES: // set up trust SSLSocketFactory sslf = null; if (trustStorePath != null) { sslf = WSClientUtil.genCustomSSLSocketFactory(null, null, trustStorePath, trustStorePwd); } vresp = runWS(sslf, cert); break; case HTTP: vresp = runHTTP(cert); break; default: throw new IllegalArgumentException("Unknown protocol: " + protocol.toString()); } ; // output result String certificatePurposes = vresp.getValidCertificatePurposes(); println("Valid Certificate Purposes:\n " + (certificatePurposes == null ? "" : certificatePurposes)); Validation validation = vresp.getValidation(); println("Certificate Status:\n " + validation.getStatus()); return getReturnValue(validation.getStatus()); }