/** * Validate the passed in certificate as being of the correct type to be used for time stamping. * To be valid it must have an ExtendedKeyUsage extension which has a key purpose identifier of * id-kp-timeStamping. * * @param cert the certificate of interest. * @throws TSPValidationException if the certicate fails on one of the check points. */ public static void validateCertificate(X509Certificate cert) throws TSPValidationException { if (cert.getVersion() != 3) { throw new IllegalArgumentException("Certificate must have an ExtendedKeyUsage extension."); } byte[] ext = cert.getExtensionValue(X509Extensions.ExtendedKeyUsage.getId()); if (ext == null) { throw new TSPValidationException("Certificate must have an ExtendedKeyUsage extension."); } if (!cert.getCriticalExtensionOIDs().contains(X509Extensions.ExtendedKeyUsage.getId())) { throw new TSPValidationException( "Certificate must have an ExtendedKeyUsage extension marked as critical."); } ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(ext)); try { aIn = new ASN1InputStream( new ByteArrayInputStream(((ASN1OctetString) aIn.readObject()).getOctets())); ExtendedKeyUsage extKey = ExtendedKeyUsage.getInstance(aIn.readObject()); if (!extKey.hasKeyPurposeId(KeyPurposeId.id_kp_timeStamping) || extKey.size() != 1) { throw new TSPValidationException("ExtendedKeyUsage not solely time stamping."); } } catch (IOException e) { throw new TSPValidationException("cannot process ExtendedKeyUsage extension"); } }
private String hostNameMessage(X509Certificate cert, String hostname) { StringBuffer si = new StringBuffer(); si.append(master.getString(R.string.mtm_hostname_mismatch, hostname)); si.append("\n\n"); try { Collection<List<?>> sans = cert.getSubjectAlternativeNames(); if (sans == null) { si.append(cert.getSubjectDN()); si.append("\n"); } else for (List<?> altName : sans) { Object name = altName.get(1); if (name instanceof String) { si.append("["); si.append((Integer) altName.get(0)); si.append("] "); si.append(name); si.append("\n"); } } } catch (CertificateParsingException e) { e.printStackTrace(); si.append("<Parsing error: "); si.append(e.getLocalizedMessage()); si.append(">\n"); } si.append("\n"); si.append(master.getString(R.string.mtm_connect_anyway)); si.append("\n\n"); si.append(master.getString(R.string.mtm_cert_details)); certDetails(si, cert); return si.toString(); }
private void validateWithExtendedKeyUsage() throws Exception { CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC"); X509Certificate rootCert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(extTrust)); X509Certificate interCert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(extCA)); X509Certificate finalCert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(extEE)); List list = new ArrayList(); list.add(rootCert); list.add(interCert); list.add(finalCert); CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters(list); CertStore store = CertStore.getInstance("Collection", ccsp, "BC"); Date validDate = new Date(rootCert.getNotBefore().getTime() + 60 * 60 * 1000); // validating path List certchain = new ArrayList(); certchain.add(finalCert); certchain.add(interCert); CertPath cp = CertificateFactory.getInstance("X.509", "BC").generateCertPath(certchain); Set trust = new HashSet(); trust.add(new TrustAnchor(rootCert, null)); CertPathValidator cpv = CertPathValidator.getInstance("PKIX", "BC"); PKIXParameters param = new PKIXParameters(trust); param.addCertStore(store); param.setDate(validDate); param.setRevocationEnabled(false); PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) cpv.validate(cp, param); }
public static X509Certificate makeCertificate( KeyPair subKP, String _subDN, KeyPair issKP, String _issDN, boolean _ca) throws GeneralSecurityException, IOException, OperatorCreationException { PublicKey subPub = subKP.getPublic(); PrivateKey issPriv = issKP.getPrivate(); PublicKey issPub = issKP.getPublic(); X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder( new X500Name(_issDN), allocateSerialNumber(), new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)), new X500Name(_subDN), subPub); JcaContentSignerBuilder contentSignerBuilder = makeContentSignerBuilder(issPub); v3CertGen.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyId(subPub)); v3CertGen.addExtension(Extension.authorityKeyIdentifier, false, createAuthorityKeyId(issPub)); v3CertGen.addExtension(Extension.basicConstraints, false, new BasicConstraints(_ca)); X509Certificate _cert = new JcaX509CertificateConverter() .setProvider("SC") .getCertificate(v3CertGen.build(contentSignerBuilder.build(issPriv))); _cert.checkValidity(new Date()); _cert.verify(issPub); return _cert; }
/** * 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; }
/** * Verify the email is signed by the given certificate. * * @param signedData * @param mailMsg * @return * @throws CMSException * @throws OperatorCreationException * @throws CertificateException */ @SuppressWarnings({"rawtypes"}) protected boolean isValid(CMSSignedData signedData, MailMessage mailMsg) throws OperatorCreationException, CMSException, CertificateException { boolean verify = false; SignerInformationStore signerStore = signedData.getSignerInfos(); Iterator<SignerInformation> it = signerStore.getSigners().iterator(); while (it.hasNext()) { SignerInformation signer = it.next(); org.bouncycastle.util.Store store = signedData.getCertificates(); @SuppressWarnings("unchecked") Collection certCollection = store.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder certHolder = (X509CertificateHolder) certIt.next(); X509Certificate certificate = new JcaX509CertificateConverter().setProvider(PROVIDER_NAME).getCertificate(certHolder); verify = signer.verify( new JcaSimpleSignerInfoVerifierBuilder() .setProvider(PROVIDER_NAME) .build(certificate)); mailMsg.setHasSignature(true); mailMsg.setSignaturePassed(verify); mailMsg.setNameOfPrincipal(certificate.getSubjectDN().getName()); } return verify; }
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; }
public DEPExportFormat exportDEP() { try { // prepare data structures for DEP export // DEP exports are grouped according to the used signature certificate (CURRENTLY NOT USED IN // THE DEMO) HashMap<String, List<ReceiptPackage>> certificateToReceiptMap = new HashMap<>(); for (ReceiptPackage receiptPackage : receiptPackages) { X509Certificate signingCertificate = receiptPackage.getSigningCertificate(); List<ReceiptPackage> receiptPackagesForSignatureCertificate = certificateToReceiptMap.get(signingCertificate.getSerialNumber() + ""); if (receiptPackagesForSignatureCertificate == null) { receiptPackagesForSignatureCertificate = new ArrayList<>(); certificateToReceiptMap.put( signingCertificate.getSerialNumber() + "", receiptPackagesForSignatureCertificate); } receiptPackagesForSignatureCertificate.add(receiptPackage); } // create data structure for export format DEPExportFormat depExportFormat = new DEPExportFormat(); DEPBelegDump[] belegDump = new DEPBelegDump[certificateToReceiptMap.keySet().size()]; // store receipts in export format int dumpIndex = 0; for (List<ReceiptPackage> signedReceipts : certificateToReceiptMap.values()) { belegDump[dumpIndex] = new DEPBelegDump(); depExportFormat.setBelegPackage(belegDump); List<String> receiptsInJWSCompactRepresentation = new ArrayList<>(); for (ReceiptPackage receiptPackage : signedReceipts) { receiptsInJWSCompactRepresentation.add(receiptPackage.getJwsCompactRepresentation()); } belegDump[dumpIndex].setBelegeDaten( receiptsInJWSCompactRepresentation.toArray( new String[receiptsInJWSCompactRepresentation.size()])); String base64EncodedSignatureCertificate = CashBoxUtils.base64Encode( signedReceipts.get(0).getSigningCertificate().getEncoded(), false); belegDump[dumpIndex].setSignatureCertificate(base64EncodedSignatureCertificate); List<X509Certificate> base64EncodedCertificateChain = signedReceipts.get(0).getCertificateChain(); String[] certificateChain = new String[base64EncodedCertificateChain.size()]; for (int i = 0; i < base64EncodedCertificateChain.size(); i++) { X509Certificate base64EncodedChainCertificate = base64EncodedCertificateChain.get(i); certificateChain[i] = CashBoxUtils.base64Encode(base64EncodedChainCertificate.getEncoded(), false); } belegDump[dumpIndex].setCertificateChain(certificateChain); dumpIndex++; } return depExportFormat; } catch (CertificateEncodingException e) { e.printStackTrace(); } return null; }
/** * Encode the CertPath using PKIPATH format. * * @return a byte array containing the binary encoding of the PkiPath object * @exception CertificateEncodingException if an exception occurs */ private byte[] encodePKIPATH() throws CertificateEncodingException { ListIterator<X509Certificate> li = certs.listIterator(certs.size()); try { DerOutputStream bytes = new DerOutputStream(); // encode certs in reverse order (trust anchor to target) // according to PkiPath format while (li.hasPrevious()) { X509Certificate cert = li.previous(); // check for duplicate cert if (certs.lastIndexOf(cert) != certs.indexOf(cert)) { throw new CertificateEncodingException("Duplicate Certificate"); } // get encoded certificates byte[] encoded = cert.getEncoded(); bytes.write(encoded); } // Wrap the data in a SEQUENCE DerOutputStream derout = new DerOutputStream(); derout.write(DerValue.tag_SequenceOf, bytes); return derout.toByteArray(); } catch (IOException ioe) { throw new CertificateEncodingException("IOException encoding " + "PkiPath data: " + ioe, ioe); } }
/* Cert creation engine */ private static synchronized X509Certificate createX509V3Certificate( PublicKey pubKey, PrivateKey privKey, int ttlMonths, String issuerDN, String subjectDN, long serial, String signAlgoritm) throws GeneralSecurityException { X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator(); certGenerator.reset(); certGenerator.setSerialNumber(java.math.BigInteger.valueOf(serial)); certGenerator.setIssuerDN(new org.bouncycastle.asn1.x509.X509Name(issuerDN)); certGenerator.setNotBefore(new java.util.Date(System.currentTimeMillis())); certGenerator.setNotAfter( new java.util.Date(System.currentTimeMillis() + ttlMonths * (1000L * 60 * 60 * 24 * 30))); certGenerator.setSubjectDN(new org.bouncycastle.asn1.x509.X509Name(subjectDN)); certGenerator.setPublicKey(pubKey); certGenerator.setSignatureAlgorithm(signAlgoritm); X509Certificate cert = certGenerator.generateX509Certificate(privKey, "BC", new java.security.SecureRandom()); cert.checkValidity(new java.util.Date()); cert.verify(pubKey); return cert; }
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()); }
@RequestMapping("to_login") public String ToLogin(HttpServletRequest request, ModelMap map) throws WebException { try { // X509Certificate[] clientCertChain = (X509Certificate[]) // request.getAttribute("javax.servlet.request.X509Certificate"); String certString = request.getHeader("client-cert"); if (StringUtils.isEmpty(certString)) { return LOGINPAGER; } certString = certString.replaceAll("\t", "\n"); X509Certificate clientCertChain = (X509Certificate) new PEMReader(new StringReader(certString), null, "SUN").readObject(); if (clientCertChain == null) { return LOGINPAGER; } else { Principal dn = clientCertChain.getSubjectDN(); X500Name x509Principal = (X500Name) dn; String uid = x509Principal.getGivenName(); if (StringUtils.isNotEmpty(uid)) { String[] uids = uid.split(","); map.put("accountName", uids[1]); map.put("memberName", uids[0]); } } return LOGINPAGER; } catch (Exception e) { throw new WebException("系统错误", e); } }
/** * @param certBuf * @return certificate chain * @throws CertificateException * @throws IOException */ public static X509Certificate[] readCertificateChain(byte[] certBuf) throws CertificateException, IOException { BufferedInputStream istream = new BufferedInputStream(new ByteArrayInputStream(certBuf)); CertificateFactory cf = CertificateFactory.getInstance("X.509"); ArrayList<Certificate> certs = new ArrayList<Certificate>(); while (istream.available() > 0) { Certificate cert = cf.generateCertificate(istream); // log.debug("found: " + cert); certs.add(cert); } istream.close(); X509Certificate[] chain = new X509Certificate[certs.size()]; Iterator<Certificate> i = certs.iterator(); int c = 0; while (i.hasNext()) { X509Certificate x509 = (X509Certificate) i.next(); chain[c++] = x509; try { x509.checkValidity(); log.debug("X509 certificate is valid"); } catch (CertificateExpiredException exp) { log.debug("X509 certificate is expired"); // nothing to be done here } catch (CertificateException ex) { throw new RuntimeException("certificate byte array is not valid", ex); } } return chain; }
/** @see de.willuhn.datasource.GenericObject#getAttribute(java.lang.String) */ public Object getAttribute(String arg0) throws RemoteException { if ("name".equals(arg0)) { String s = myCert.getSubject().getAttribute(Principal.COMMON_NAME); if (s == null || s.length() == 0) { s = this.cert.getSubjectDN().getName(); if (s != null && s.length() > 40) s = s.substring(0, 39) + "..."; return s; } return s; } if ("issuer".equals(arg0)) { String s = myCert.getIssuer().getAttribute(Principal.COMMON_NAME); if (s == null || s.length() == 0) s = myCert.getIssuer().getAttribute(Principal.ORGANIZATION); if (s == null || s.length() == 0) { s = this.cert.getIssuerDN().getName(); if (s != null && s.length() > 40) s = s.substring(0, 39) + "..."; } return s; } if ("serial".equals(arg0)) return cert.getSerialNumber().toString(); if ("organization".equals(arg0)) return myCert.getSubject().getAttribute(Principal.ORGANIZATION); if ("ou".equals(arg0)) return myCert.getSubject().getAttribute(Principal.ORGANIZATIONAL_UNIT); if ("datefrom".equals(arg0)) return cert.getNotBefore(); if ("dateto".equals(arg0)) return cert.getNotAfter(); return null; }
public void testSelfSignedCert() throws Exception { KeyPair keyPair = createKeyPair(1024, "secret"); // Certificate String email = "*****@*****.**"; String domain = "tigase.org"; String ou = "XMPP Service"; String o = "Tigase.org"; String l = "Cambourne"; String st = "Cambridgeshire"; String c = "UK"; // System.out.println("Creating self-signed certificate for issuer: " + domain); X509Certificate cert = createSelfSignedCertificate(email, domain, ou, o, l, st, c, keyPair); cert.checkValidity(); assertTrue("Checked certificate validty for today - valid", true); try { cert.checkValidity(new Date(System.currentTimeMillis() - (1000 * 3600 * 24))); fail("Checked certificate validty for yesterday - valid"); } catch (CertificateNotYetValidException e) { assertTrue("Checked certificate validty for yesterday - not valid", true); } cert.verify(keyPair.getPublic()); assertTrue("Verified certificate with public key - done", true); }
@Override protected HttpURLConnection openConnection(String path, String query) throws IOException { query = addDelegationTokenParam(query); final URL url = new URL("https", nnAddr.getHostName(), nnAddr.getPort(), path + '?' + query); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); // bypass hostname verification try { conn.setHostnameVerifier(new DummyHostnameVerifier()); conn.setRequestMethod("GET"); conn.connect(); } catch (IOException ioe) { throwIOExceptionFromConnection(conn, ioe); } // check cert expiration date final int warnDays = ExpWarnDays; if (warnDays > 0) { // make sure only check once ExpWarnDays = 0; long expTimeThreshold = warnDays * MM_SECONDS_PER_DAY + System.currentTimeMillis(); X509Certificate[] clientCerts = (X509Certificate[]) conn.getLocalCertificates(); if (clientCerts != null) { for (X509Certificate cert : clientCerts) { long expTime = cert.getNotAfter().getTime(); if (expTime < expTimeThreshold) { StringBuilder sb = new StringBuilder(); sb.append("\n Client certificate " + cert.getSubjectX500Principal().getName()); int dayOffSet = (int) ((expTime - System.currentTimeMillis()) / MM_SECONDS_PER_DAY); sb.append(" have " + dayOffSet + " days to expire"); LOG.warn(sb.toString()); } } } } return (HttpURLConnection) conn; }
/** * 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); } } }
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); } }
/** * Retrieves a list of all the alternate names of the specified certificates as a comma-separated * string. * * @param cert The certificate to retrieve alternate names for * @return A comma-separated list of alternate names */ protected String getAlternateNames(final X509Certificate cert) { final StringBuilder res = new StringBuilder(); try { if (cert.getSubjectAlternativeNames() == null) { return null; } for (List<?> entry : cert.getSubjectAlternativeNames()) { final int type = ((Integer) entry.get(0)).intValue(); // DNS or IP if (type == 2 || type == 7) { if (res.length() > 0) { res.append(", "); } res.append(entry.get(1)); } } } catch (CertificateParsingException ex) { // Do nothing } return res.toString(); }
public void testProtectedMessage() throws Exception { KeyPairGenerator kGen = KeyPairGenerator.getInstance("RSA", BC); kGen.initialize(512); KeyPair kp = kGen.generateKeyPair(); X509CertificateHolder cert = makeV3Certificate(kp, "CN=Test", kp, "CN=Test"); GeneralName sender = new GeneralName(new X500Name("CN=Sender")); GeneralName recipient = new GeneralName(new X500Name("CN=Recip")); ContentSigner signer = new JcaContentSignerBuilder("MD5WithRSAEncryption").setProvider(BC).build(kp.getPrivate()); ProtectedPKIMessage message = new ProtectedPKIMessageBuilder(sender, recipient) .setBody( new PKIBody( PKIBody.TYPE_INIT_REP, CertRepMessage.getInstance(new DERSequence(new DERSequence())))) .addCMPCertificate(cert) .build(signer); X509Certificate jcaCert = new JcaX509CertificateConverter() .setProvider(BC) .getCertificate(message.getCertificates()[0]); ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder().setProvider(BC).build(jcaCert.getPublicKey()); assertTrue(message.verify(verifierProvider)); assertEquals(sender, message.getHeader().getSender()); assertEquals(recipient, message.getHeader().getRecipient()); }
public static X509Certificate makeV1Certificate( KeyPair subKP, String _subDN, KeyPair issKP, String _issDN) throws GeneralSecurityException, IOException, OperatorCreationException { PublicKey subPub = subKP.getPublic(); PrivateKey issPriv = issKP.getPrivate(); PublicKey issPub = issKP.getPublic(); X509v1CertificateBuilder v1CertGen = new JcaX509v1CertificateBuilder( new X500Name(_issDN), allocateSerialNumber(), new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)), new X500Name(_subDN), subPub); JcaContentSignerBuilder contentSignerBuilder = makeContentSignerBuilder(issPub); X509Certificate _cert = new JcaX509CertificateConverter() .setProvider("SC") .getCertificate(v1CertGen.build(contentSignerBuilder.build(issPriv))); _cert.checkValidity(new Date()); _cert.verify(issPub); return _cert; }
private static X509Certificate makeCertificate( KeyPair subKP, String _subDN, KeyPair issKP, String _issDN) throws GeneralSecurityException, IOException { PublicKey subPub = subKP.getPublic(); PrivateKey issPriv = issKP.getPrivate(); PublicKey issPub = issKP.getPublic(); X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); v3CertGen.reset(); v3CertGen.setSerialNumber(BigInteger.valueOf(1)); v3CertGen.setIssuerDN(new X509Name(_issDN)); v3CertGen.setNotBefore(new Date(System.currentTimeMillis())); v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100))); v3CertGen.setSubjectDN(new X509Name(_subDN)); v3CertGen.setPublicKey(subPub); v3CertGen.setSignatureAlgorithm("SHA1WithRSA"); X509Certificate _cert = v3CertGen.generate(issPriv, "SunRsaSign"); _cert.checkValidity(new Date()); _cert.verify(issPub); return _cert; }
@Override public void authenticate( Set<Object> publicCredentials, Set<Object> privateCredentials, Set<Principal> identifiedPrincipals) throws AuthenticationException { String message = "no X.509 certificate chain"; boolean found = false; for (Object credential : publicCredentials) { if (isX509CertPath(credential)) { X509Certificate eec = CertPaths.getEndEntityCertificate((CertPath) credential); if (eec == null) { message = "X.509 chain contains no End-Entity Certificate"; } else { identifiedPrincipals.add(new GlobusPrincipal(eec.getSubjectX500Principal())); if (isPolicyPrincipalsEnabled) { listPolicies(eec) .stream() .map(PolicyInformation::getInstance) .map(PolicyInformation::getPolicyIdentifier) .map(DERObjectIdentifier::getId) .map(X509Plugin::asPrincipal) .filter(Objects::nonNull) .forEach(identifiedPrincipals::add); } found = true; } } } checkAuthentication(found, message); }
private SignatureData getFromXmlDigSigSignature( SignatureVerificationRequest signatureVerificationRequest, SignatureVerificationResponse response) throws ParserConfigurationException, SAXException, IOException, MarshalException, SignatureException { String signature = new String(Base64.decode(signatureVerificationRequest.getSignature())); InputStream is = new ByteArrayInputStream(signature.getBytes()); Document document = createDocument(is, true); XMLSignature xmlSignature = XMLSignatureFactory.getInstance().unmarshalXMLSignature(new DOMStructure(document)); List contentList = xmlSignature.getKeyInfo().getContent(); for (Object content : contentList) { if (content instanceof X509Data) { List certificateList = ((X509Data) content).getContent(); for (Object certificateObject : certificateList) { if (certificateObject instanceof X509Certificate) { X509Certificate cert = (X509Certificate) certificateObject; CertificateInfo ci = new CertificateInfo(); ci.setSubjectDn(cert.getSubjectDN().getName()); ci.setValidTo(simpleDateFormat.format(cert.getNotAfter())); response.getCertificateInfos().getCertificateInfo().add(ci); } } } } return createSignatureDataFromXmlDigSig(signature); }
/* * mini test */ public static void main(String[] args) throws Exception { final CAFactory caFactory = new CAFactory(); final X509Certificate caCert = caFactory.create("321lfn432oifno", 24, caFactory.createNewKeyPair()); caCert.checkValidity(); System.out.println(caCert.getSubjectDN().toString()); }
public void testAutoCredentialCreation() { AssertionCredentialsManager cm = null; try { cm = Utils.getAssertionCredentialsManager(); X509Certificate cert = cm.getIdPCertificate(); assertNotNull(cert); assertNotNull(cm.getIdPKey()); String expectedSub = Utils.CA_SUBJECT_PREFIX + ",CN=" + AssertionCredentialsManager.CERT_DN; assertEquals(expectedSub, cert.getSubjectDN().toString()); SAMLAssertion saml = cm.getAuthenticationAssertion(TEST_UID, TEST_FIRST_NAME, TEST_LAST_NAME, TEST_EMAIL); verifySAMLAssertion(saml, cm); String xml = SAMLUtils.samlAssertionToString(saml); SAMLAssertion saml2 = SAMLUtils.stringToSAMLAssertion(xml); verifySAMLAssertion(saml2, cm); } catch (Exception e) { FaultUtil.printFault(e); assertTrue(false); } finally { try { cm.clearDatabase(); } catch (Exception e) { e.printStackTrace(); } } }
protected boolean verify(String hostname, SSLSession session, boolean interactive) { LOGGER.log( Level.FINE, "hostname verifier for " + hostname + ", trying default verifier first"); // if the default verifier accepts the hostname, we are done if (defaultVerifier.verify(hostname, session)) { LOGGER.log(Level.FINE, "default verifier accepted " + hostname); return true; } // otherwise, we check if the hostname is an alias for this cert in our keystore try { X509Certificate cert = (X509Certificate) session.getPeerCertificates()[0]; // Log.d(TAG, "cert: " + cert); if (cert.equals(appKeyStore.getCertificate(hostname.toLowerCase(Locale.US)))) { LOGGER.log(Level.FINE, "certificate for " + hostname + " is in our keystore. accepting."); return true; } else { LOGGER.log( Level.FINE, "server " + hostname + " provided wrong certificate, asking user."); if (interactive) { return interactHostname(cert, hostname); } else { return false; } } } catch (Exception e) { e.printStackTrace(); return false; } }
/** * java.security.KeyStore#setCertificateEntry(java.lang.String, java.security.cert.Certificate) */ public void test_setCertificateEntryLjava_lang_StringLjava_security_cert_Certificate() throws Exception { // Test for method void // java.security.KeyStore.setCertificateEntry(java.lang.String, // java.security.cert.Certificate) CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) cf.generateCertificate(certArray); KeyStore keyTest = KeyStore.getInstance(KeyStore.getDefaultType()); try { keyTest.setCertificateEntry("alias", cert); fail(); } catch (KeyStoreException expected) { } keyTest.load(null, null); PublicKey pub = cert.getPublicKey(); keyTest.setCertificateEntry("alias1", cert); assertTrue( "the entry specified by the alias alias1 is not a certificate", keyTest.isCertificateEntry("alias1")); Certificate resultCert = keyTest.getCertificate("alias1"); assertEquals( "the public key of the certificate from getCertificate() " + "did not equal the original certificate", pub, resultCert.getPublicKey()); }
@Override public Component preview() { final Label commonNameLabel = new Label("certCommonName", new Model<String>()); final ByteArrayInputStream certificateStream = new ByteArrayInputStream(uploadedBytes); try { final X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(certificateStream); final StringBuilder commonNameBuilder = new StringBuilder("cn="); final LdapName ldapName = new LdapName(certificate.getIssuerDN().getName()); for (Rdn rdn : ldapName.getRdns()) { if ("CN".equalsIgnoreCase(rdn.getType())) { commonNameBuilder.append( rdn.getValue() == null ? StringUtils.EMPTY : rdn.getValue().toString()); } } commonNameLabel.setDefaultModelObject(commonNameBuilder.toString()); } catch (Exception e) { LOG.error("Error evaluating certificate file", e); throw new IllegalArgumentException("Error evaluating certificate file", e); } finally { IOUtils.closeQuietly(certificateStream); } return this.add(commonNameLabel); }
public final void check(String hostname, List<Certificate> peerCertificates) throws SSLPeerUnverifiedException { List<ByteString> pins = (List) this.hostnameToPins.get(hostname); if (pins != null) { int i = 0; int size = peerCertificates.size(); while (i < size) { if (!pins.contains(sha1((X509Certificate) peerCertificates.get(i)))) { i++; } else { return; } } StringBuilder message = new StringBuilder("Certificate pinning failure!\n Peer certificate chain:"); size = peerCertificates.size(); for (i = 0; i < size; i++) { X509Certificate x509Certificate = (X509Certificate) peerCertificates.get(i); message .append("\n ") .append(pin(x509Certificate)) .append(": ") .append(x509Certificate.getSubjectDN().getName()); } message.append("\n Pinned certificates for ").append(hostname).append(":"); size = pins.size(); for (i = 0; i < size; i++) { message.append("\n sha1/").append(Base64.encode(((ByteString) pins.get(i)).data)); } throw new SSLPeerUnverifiedException(message.toString()); } }