List of usage examples for org.bouncycastle.asn1.x509 GeneralName getInstance
public static GeneralName getInstance(Object obj)
From source file:be.fedict.eid.pkira.crypto.certificate.CertificateInfo.java
License:Open Source License
public List<String> getAlternativeNames() throws CryptoException { try {/*w w w . j ava2 s . c o m*/ List<String> result = new ArrayList<String>(); byte[] extensionBytes = certificate.getExtensionValue(X509Extension.subjectAlternativeName.getId()); ASN1OctetString octs = (ASN1OctetString) ASN1Object.fromByteArray(extensionBytes); DERSequence extension = (DERSequence) ASN1Object.fromByteArray(octs.getOctets()); for (int i = 0; i < extension.size(); i++) { GeneralName name = GeneralName.getInstance(extension.getObjectAt(i)); if (name.getTagNo() == GeneralName.dNSName) { result.add(name.getName().toString()); } } return result; } catch (IOException e) { throw new CryptoException("Could not extract SAN value.", e); } }
From source file:com.gsma.iariauth.validator.dsig.jre.BCCertificateInfo.java
License:Apache License
private void getSANData(X509Certificate x509Cert) throws IOException { byte[] bytes = x509Cert.getExtensionValue(SAN_OID); if (bytes != null) { ArrayList<String> cUriIdentities = new ArrayList<String>(); Enumeration<?> it = DERSequence.getInstance(fromExtensionValue(bytes)).getObjects(); while (it.hasMoreElements()) { GeneralName genName = GeneralName.getInstance(it.nextElement()); if (genName.getTagNo() == GeneralName.uniformResourceIdentifier) { cUriIdentities.add(((ASN1String) genName.getName()).getString()); }//from w ww. j av a 2s.c om } if (cUriIdentities.size() > 0) { uriIdentities = cUriIdentities.toArray(new String[cUriIdentities.size()]); } } }
From source file:com.novosec.pkix.asn1.cmp.PKIHeader.java
License:Open Source License
public PKIHeader(ASN1Sequence seq) { Enumeration e = seq.getObjects(); pvno = DERInteger.getInstance(e.nextElement()); sender = GeneralName.getInstance(e.nextElement()); recipient = GeneralName.getInstance(e.nextElement()); while (e.hasMoreElements()) { ASN1TaggedObject tagObj = (ASN1TaggedObject) e.nextElement(); switch (tagObj.getTagNo()) { case 0:/*from w ww . j a va2 s. c o m*/ messageTime = DERGeneralizedTime.getInstance(tagObj.getObject()); break; case 1: protectionAlg = AlgorithmIdentifier.getInstance(tagObj.getObject()); break; case 2: senderKID = (DEROctetString) DEROctetString.getInstance(tagObj); break; case 3: recipKID = (DEROctetString) DEROctetString.getInstance(tagObj); break; case 4: transactionID = (DEROctetString) DEROctetString.getInstance(tagObj); break; case 5: senderNonce = (DEROctetString) DEROctetString.getInstance(tagObj); break; case 6: recipNonce = (DEROctetString) DEROctetString.getInstance(tagObj); break; case 7: freeText = PKIFreeText.getInstance(tagObj.getObject()); break; case 8: ASN1Sequence s = (ASN1Sequence) tagObj.getObject(); for (int i = 0; i < s.size(); i++) { generalInfos.addElement(InfoTypeAndValue.getInstance(s.getObjectAt(i))); } break; } } }
From source file:com.novosec.pkix.asn1.crmf.POPOSigningKeyInput.java
License:Open Source License
public POPOSigningKeyInput(ASN1Sequence seq) { Object obj = seq.getObjectAt(0); if (obj instanceof ASN1TaggedObject) { ASN1TaggedObject tagObj = (ASN1TaggedObject) obj; if (tagObj.getTagNo() == 0) { this.sender = GeneralName.getInstance(tagObj.getObject()); } else {/* w w w .j a v a 2 s . c o m*/ throw new IllegalArgumentException("unknown tag: " + tagObj.getTagNo()); } } else { publicKeyMAC = PKMACValue.getInstance(obj); } this.publicKey = SubjectPublicKeyInfo.getInstance(seq.getObjectAt(1)); }
From source file:edu.washington.iam.tools.IamCertificateHelper.java
License:Apache License
public static int parseCsr(IamCertificate cert) throws IamCertificateException { try {//from w ww . j a v a2 s. c o m PEMReader pRd = new PEMReader(new StringReader(cert.pemRequest)); PKCS10CertificationRequest request = (PKCS10CertificationRequest) pRd.readObject(); if (request == null) throw new IamCertificateException("invalid CSR (request)"); CertificationRequestInfo info = request.getCertificationRequestInfo(); if (info == null) throw new IamCertificateException("invalid CSR (info)"); X509Name dn = info.getSubject(); if (dn == null) throw new IamCertificateException("invalid CSR (dn)"); log.debug("dn=" + dn.toString()); cert.dn = dn.toString(); try { List cns = dn.getValues(X509Name.CN); cert.cn = (String) (cns.get(0)); log.debug("cn=" + cert.cn); cert.names.add(cert.cn); // first entry for names is always cn cns = dn.getValues(X509Name.C); cert.dnC = (String) (cns.get(0)); cns = dn.getValues(X509Name.ST); cert.dnST = (String) (cns.get(0)); } catch (Exception e) { log.debug("get cn error: " + e); throw new IamCertificateException("invalid CSR"); } // see if we've got alt names (in extensions) ASN1Set attrs = info.getAttributes(); if (attrs != null) { for (int a = 0; a < attrs.size(); a++) { Attribute attr = Attribute.getInstance(attrs.getObjectAt(a)); if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) { // is the extension X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0)); // get the subAltName extension DERObjectIdentifier sanoid = new DERObjectIdentifier( X509Extensions.SubjectAlternativeName.getId()); X509Extension xext = extensions.getExtension(sanoid); if (xext != null) { log.debug("processing altname extensions"); ASN1Object asn1 = X509Extension.convertValueToObject(xext); Enumeration dit = DERSequence.getInstance(asn1).getObjects(); while (dit.hasMoreElements()) { GeneralName gn = GeneralName.getInstance(dit.nextElement()); log.debug("altname tag=" + gn.getTagNo()); log.debug("altname name=" + gn.getName().toString()); if (gn.getTagNo() == GeneralName.dNSName) cert.names.add(gn.getName().toString()); } } } } } // check key size PublicKey pk = request.getPublicKey(); log.debug("key alg = " + pk.getAlgorithm()); log.debug("key fmt = " + pk.getFormat()); if (pk.getAlgorithm().equals("RSA")) { RSAPublicKey rpk = (RSAPublicKey) pk; cert.keySize = rpk.getModulus().bitLength(); log.debug("key size = " + cert.keySize); } } catch (IOException e) { log.debug("ioerror: " + e); throw new IamCertificateException("invalid CSR " + e.getMessage()); } catch (Exception e) { log.debug("excp: " + e); throw new IamCertificateException("invalid CSR"); } return 1; }
From source file:eu.emi.security.authn.x509.helpers.pkipath.bc.FixedBCPKIXCertPathReviewer.java
License:Open Source License
private void checkNameConstraints() { X509Certificate cert = null;//from w w w . j ava 2s. c o m // // Setup // // (b) and (c) PKIXNameConstraintValidator nameConstraintValidator = new PKIXNameConstraintValidator(); // // process each certificate except the self issued which are not last in the path // int index; try { for (index = certs.size() - 1; index >= 0; index--) { // // certificate processing // cert = (X509Certificate) certs.get(index); // b),c) if (!(isSelfIssued(cert) && index != 0)) { X500Principal principal = getSubjectPrincipal(cert); ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(principal.getEncoded())); ASN1Sequence dns; try { dns = (ASN1Sequence) aIn.readObject(); } catch (IOException e) { ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.ncSubjectNameError", new Object[] { new UntrustedInput(principal) }); throw new CertPathReviewerException(msg, e, certPath, index); } try { nameConstraintValidator.checkPermittedDN(dns); } catch (PKIXNameConstraintValidatorException cpve) { ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.notPermittedDN", new Object[] { new UntrustedInput(principal.getName()) }); throw new CertPathReviewerException(msg, cpve, certPath, index); } try { nameConstraintValidator.checkExcludedDN(dns); } catch (PKIXNameConstraintValidatorException cpve) { ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.excludedDN", new Object[] { new UntrustedInput(principal.getName()) }); throw new CertPathReviewerException(msg, cpve, certPath, index); } //FIX (missing in orig cert path reviewer) Vector emails = new X509Name(dns).getValues(X509Name.EmailAddress); for (Enumeration e = emails.elements(); e.hasMoreElements();) { String email = (String) e.nextElement(); GeneralName emailAsGeneralName = new GeneralName(GeneralName.rfc822Name, email); try { nameConstraintValidator.checkPermitted(emailAsGeneralName); } catch (PKIXNameConstraintValidatorException cpve) { ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.notPermittedDN", new Object[] { new UntrustedInput(principal.getName()) }); throw new CertPathReviewerException(msg, cpve, certPath, index); } try { nameConstraintValidator.checkExcluded(emailAsGeneralName); } catch (PKIXNameConstraintValidatorException cpve) { ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.excludedDN", new Object[] { new UntrustedInput(principal.getName()) }); throw new CertPathReviewerException(msg, cpve, certPath, index); } } ASN1Sequence altName; try { altName = (ASN1Sequence) getExtensionValue(cert, SUBJECT_ALTERNATIVE_NAME); } catch (AnnotatedException ae) { ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.subjAltNameExtError"); throw new CertPathReviewerException(msg, ae, certPath, index); } if (altName != null) { for (int j = 0; j < altName.size(); j++) { GeneralName name = GeneralName.getInstance(altName.getObjectAt(j)); try { nameConstraintValidator.checkPermitted(name); nameConstraintValidator.checkExcluded(name); } catch (PKIXNameConstraintValidatorException cpve) { ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.notPermittedEmail", new Object[] { new UntrustedInput(name) }); throw new CertPathReviewerException(msg, cpve, certPath, index); } } } } // // prepare for next certificate // // // (g) handle the name constraints extension // ASN1Sequence ncSeq; try { ncSeq = (ASN1Sequence) getExtensionValue(cert, NAME_CONSTRAINTS); } catch (AnnotatedException ae) { ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.ncExtError"); throw new CertPathReviewerException(msg, ae, certPath, index); } if (ncSeq != null) { NameConstraints nc = NameConstraints.getInstance(ncSeq); // // (g) (1) permitted subtrees // GeneralSubtree[] permitted = nc.getPermittedSubtrees(); if (permitted != null) { nameConstraintValidator.intersectPermittedSubtree(permitted); } // // (g) (2) excluded subtrees // GeneralSubtree[] excluded = nc.getExcludedSubtrees(); if (excluded != null) { for (int c = 0; c != excluded.length; c++) { nameConstraintValidator.addExcludedSubtree(excluded[c]); } } } } // for } catch (CertPathReviewerException cpre) { addError(cpre.getErrorMessage(), cpre.getIndex()); } }
From source file:eu.europa.esig.dss.xades.validation.XAdESSignature.java
License:Open Source License
@Override public void checkSigningCertificate() { final CandidatesForSigningCertificate candidates = getCandidatesForSigningCertificate(); /**/*w w w. j a v a 2s . c om*/ * The ../SignedProperties/SignedSignatureProperties/SigningCertificate element MAY contain references and * digests values of other certificates (that * MAY form a chain up to the point of trust). */ boolean isEn319132 = false; NodeList list = DSSXMLUtils.getNodeList(signatureElement, xPathQueryHolder.XPATH_SIGNING_CERTIFICATE_CERT); int length = list.getLength(); if (length == 0) { list = DSSXMLUtils.getNodeList(signatureElement, xPathQueryHolder.XPATH_SIGNING_CERTIFICATE_CERT_V2); length = list.getLength(); isEn319132 = true; } if (length == 0) { final CertificateValidity theCertificateValidity = candidates.getTheCertificateValidity(); final CertificateToken certificateToken = theCertificateValidity == null ? null : theCertificateValidity.getCertificateToken(); // The check need to be done at the level of KeyInfo for (final Reference reference : references) { final String uri = reference.getURI(); if (!uri.startsWith("#")) { continue; } final String id = uri.substring(1); final Element element = signatureElement.getOwnerDocument().getElementById(id); // final Element element = // DSSXMLUtils.getElement(signatureElement, ""); if (!hasSignatureAsParent(element)) { continue; } if ((certificateToken != null) && id.equals(certificateToken.getXmlId())) { theCertificateValidity.setSigned(element.getNodeName()); return; } } } // This Map contains the list of the references to the certificate which // were already checked and which correspond to a certificate. Map<Element, Boolean> alreadyProcessedElements = new HashMap<Element, Boolean>(); final List<CertificateValidity> certificateValidityList = candidates.getCertificateValidityList(); for (final CertificateValidity certificateValidity : certificateValidityList) { final CertificateToken certificateToken = certificateValidity.getCertificateToken(); for (int ii = 0; ii < length; ii++) { certificateValidity.setAttributePresent(true); final Element element = (Element) list.item(ii); if (alreadyProcessedElements.containsKey(element)) { continue; } final Element certDigestElement = DSSXMLUtils.getElement(element, xPathQueryHolder.XPATH__CERT_DIGEST); certificateValidity.setDigestPresent(certDigestElement != null); final Element digestMethodElement = DSSXMLUtils.getElement(certDigestElement, xPathQueryHolder.XPATH__DIGEST_METHOD); if (digestMethodElement == null) { continue; } final String xmlAlgorithmName = digestMethodElement.getAttribute(XMLE_ALGORITHM); // The default algorithm is used in case of bad encoded // algorithm name final DigestAlgorithm digestAlgorithm = DigestAlgorithm.forXML(xmlAlgorithmName, DigestAlgorithm.SHA1); final Element digestValueElement = DSSXMLUtils.getElement(element, xPathQueryHolder.XPATH__CERT_DIGEST_DIGEST_VALUE); if (digestValueElement == null) { continue; } // That must be a binary comparison final byte[] storedBase64DigestValue = DSSUtils .base64StringToBase64Binary(digestValueElement.getTextContent()); /** * Step 1:<br> * Take the first child of the property and check that the content of ds:DigestValue matches the result * of digesting <i>the candidate for</i> * the signing certificate with the algorithm indicated in ds:DigestMethod. If they do not match, take * the next child and repeat this step until * a matching child element has been found or all children of the element have been checked. If they do * match, continue with step 2. If the last * element is reached without finding any match, the validation of this property shall be taken as * failed and INVALID/FORMAT_FAILURE is * returned. */ final byte[] digest = DSSUtils.digest(digestAlgorithm, certificateToken.getEncoded()); final byte[] recalculatedBase64DigestValue = Base64.encodeBase64(digest); certificateValidity.setDigestEqual(false); BigInteger serialNumber = new BigInteger("0"); if (Arrays.equals(recalculatedBase64DigestValue, storedBase64DigestValue)) { X500Principal issuerName = null; if (isEn319132) { final Element issuerNameEl = DSSXMLUtils.getElement(element, xPathQueryHolder.XPATH__X509_ISSUER_V2); if (issuerNameEl != null) { final String textContent = issuerNameEl.getTextContent(); ASN1InputStream is = null; GeneralName name = null; ASN1Integer serial = null; try { is = new ASN1InputStream(Base64.decodeBase64(textContent)); ASN1Sequence seq = (ASN1Sequence) is.readObject(); ASN1Sequence obj = (ASN1Sequence) seq.getObjectAt(0); name = GeneralName.getInstance(obj.getObjectAt(0)); serial = (ASN1Integer) seq.getObjectAt(1); } catch (IOException e) { LOG.error("Unable to decode textContent " + textContent + " : " + e.getMessage(), e); } finally { IOUtils.closeQuietly(is); } try { issuerName = new X500Principal(name.getName().toASN1Primitive().getEncoded()); } catch (Exception e) { LOG.error("Unable to decode X500Principal : " + e.getMessage(), e); } try { serialNumber = serial.getValue(); } catch (Exception e) { LOG.error("Unable to decode serialNumber : " + e.getMessage(), e); } } } else { final Element issuerNameEl = DSSXMLUtils.getElement(element, xPathQueryHolder.XPATH__X509_ISSUER_NAME); // This can be allayed when the distinguished name is not // correctly encoded // final String textContent = // DSSUtils.unescapeMultiByteUtf8Literals(issuerNameEl.getTextContent()); final String textContent = issuerNameEl.getTextContent(); issuerName = DSSUtils.getX500PrincipalOrNull(textContent); final Element serialNumberEl = DSSXMLUtils.getElement(element, xPathQueryHolder.XPATH__X509_SERIAL_NUMBER); final String serialNumberText = serialNumberEl.getTextContent(); // serial number can contain leading and trailing whitespace. serialNumber = new BigInteger(serialNumberText.trim()); } final X500Principal candidateIssuerName = certificateToken.getIssuerX500Principal(); final boolean issuerNameMatches = DSSUtils.x500PrincipalAreEquals(candidateIssuerName, issuerName); if (!issuerNameMatches) { final String c14nCandidateIssuerName = candidateIssuerName.getName(X500Principal.CANONICAL); LOG.info("candidateIssuerName: " + c14nCandidateIssuerName); final String c14nIssuerName = issuerName == null ? "" : issuerName.getName(X500Principal.CANONICAL); LOG.info("issuerName : " + c14nIssuerName); } final BigInteger candidateSerialNumber = certificateToken.getSerialNumber(); final boolean serialNumberMatches = candidateSerialNumber.equals(serialNumber); certificateValidity.setDigestEqual(true); certificateValidity.setSerialNumberEqual(serialNumberMatches); certificateValidity.setDistinguishedNameEqual(issuerNameMatches); // The certificate was identified alreadyProcessedElements.put(element, true); // If the signing certificate is not set yet then it must be // done now. Actually if the signature is tempered then the // method checkSignatureIntegrity cannot set the signing // certificate. if (candidates.getTheCertificateValidity() == null) { candidates.setTheCertificateValidity(certificateValidity); } break; } } } }
From source file:mitm.common.security.certificate.AltNamesInspector.java
License:Open Source License
/** * Use this constructor for ASN1Utils.getExtensionValue(X509Extension, String) * @param altName//from w w w . ja v a2 s .co m */ public AltNamesInspector(ASN1Sequence altName) { if (altName != null) { Collection<List<?>> altNames = new LinkedList<List<?>>(); for (int i = 0; i < altName.size(); i++) { GeneralName generalName = GeneralName.getInstance(altName.getObjectAt(i)); ASN1Encodable obj = generalName.getName(); String value; switch (generalName.getTagNo()) { case rfc822NameTag: case dnsNameTag: case uniformResourceIdentifierTag: value = DERIA5String.getInstance(obj).getString(); break; default: value = obj.toString(); } List<Object> list = new LinkedList<Object>(); list.add(generalName.getTagNo()); list.add(value); altNames.add(list); } parseAltNames(altNames); } }
From source file:net.wstech2.me.httpsclient.CertificateValidatorUtils.java
License:Apache License
/** * Retrieves the list of alternative DNS names for this certificate, if any. * // w ww . ja va2 s. co m * @param cert * The certificate from which the issuer name is to the * extracted. * @return A list with all alternative DNS names included in the * certificate. * @throws IOException */ public static List extractSubjectAlternativeNameList(org.bouncycastle.asn1.x509.Certificate cert) throws IOException { List dnsNames = new ArrayList(); dnsNames.add(CertificateValidatorUtils.extractCommonName(cert, true)); Extension subjectAlternativeName = cert.getTBSCertificate().getExtensions() .getExtension(Extension.subjectAlternativeName); if (subjectAlternativeName == null) { return dnsNames; } ASN1OctetString oct = subjectAlternativeName.getExtnValue(); ASN1InputStream extIn = new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())); GeneralNames gn = GeneralNames.getInstance(extIn.readObject()); extIn.close(); ASN1Sequence sq = (ASN1Sequence) gn.toASN1Primitive(); for (int i = 0; i != sq.size(); i++) { GeneralName n = GeneralName.getInstance(sq.getObjectAt(i)); dnsNames.add(n.getName().toString()); } return dnsNames; }
From source file:org.ccnx.ccn.impl.security.crypto.util.CryptoUtil.java
License:Open Source License
/** * Helper method to pull SubjectAlternativeNames from a certificate. BouncyCastle has * one of these, but it isn't included on all platforms. We get one by default from X509Certificate * but it returns us a collection of ? and we can't ever know what the ? is because we might * get a different impl class on different platforms. So we have to roll our own. * /*from w w w . ja va 2 s . c o m*/ * We filter the general names down to ones we can handle. * @param certificate * @return * @throws IOException * @throws CertificateEncodingException */ public static ArrayList<Tuple<Integer, String>> getSubjectAlternativeNames(X509Certificate certificate) throws IOException, CertificateEncodingException { byte[] encodedExtension = certificate.getExtensionValue(X509Extensions.SubjectAlternativeName.getId()); ArrayList<Tuple<Integer, String>> list = new ArrayList<Tuple<Integer, String>>(); if (null == encodedExtension) { return list; } // content of extension is wrapped in a DEROctetString DEROctetString content = (DEROctetString) CryptoUtil.decode(encodedExtension); byte[] encapsulatedOctetString = content.getOctets(); ASN1InputStream aIn = new ASN1InputStream(encapsulatedOctetString); ASN1Encodable decodedObject = (ASN1Encodable) aIn.readObject(); ASN1Sequence sequence = (ASN1Sequence) decodedObject.getDERObject(); Integer tag; GeneralName generalName; Enumeration<?> it = sequence.getObjects(); while (it.hasMoreElements()) { generalName = GeneralName.getInstance(it.nextElement()); tag = generalName.getTagNo(); switch (tag) { case GeneralName.dNSName: case GeneralName.rfc822Name: case GeneralName.uniformResourceIdentifier: list.add(new Tuple<Integer, String>(tag, ((DERString) generalName.getName()).getString())); default: // ignore other types } } return list; }