List of usage examples for org.bouncycastle.asn1.x509 GeneralName GeneralName
public GeneralName(int tag, String name)
From source file:org.deviceconnect.android.ssl.EndPointKeyStoreManager.java
License:MIT License
@Override public void requestKeyStore(final String ipAddress, final KeyStoreCallback callback) { mExecutor.execute(new Runnable() { @Override//from www. ja va2 s. co m public void run() { if (BuildConfig.DEBUG) { mLogger.info("Requested keystore: alias = " + getAlias() + ", IP Address = " + ipAddress); } try { String alias = getAlias(); if (hasIPAddress(ipAddress)) { if (BuildConfig.DEBUG) { mLogger.info("Certificate is cached for alias: " + alias); } Certificate[] chain = mKeyStore.getCertificateChain(getAlias()); callback.onSuccess(mKeyStore, chain[0], chain[1]); } else { if (BuildConfig.DEBUG) { mLogger.info("Generating key pair..."); } final KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA"); final KeyPair keyPair = keyGenerator.generateKeyPair(); if (BuildConfig.DEBUG) { mLogger.info("Generated key pair."); mLogger.info("Executing certificate request..."); } final CertificateAuthorityClient localCA = new CertificateAuthorityClient(mContext, mRootCA); final List<ASN1Encodable> names = new ArrayList<>(); names.add(new GeneralName(GeneralName.iPAddress, ipAddress)); for (SAN cache : mSANs) { if (!cache.mName.equals(ipAddress)) { names.add(new GeneralName(cache.mTagNo, cache.mName)); } } names.add(new GeneralName(GeneralName.iPAddress, "0.0.0.0")); names.add(new GeneralName(GeneralName.iPAddress, "127.0.0.1")); names.add(new GeneralName(GeneralName.dNSName, "localhost")); GeneralNames generalNames = new GeneralNames( new DERSequence(names.toArray(new ASN1Encodable[names.size()]))); localCA.executeCertificateRequest(createCSR(keyPair, "localhost", generalNames), new CertificateRequestCallback() { @Override public void onCreate(final Certificate cert, final Certificate rootCert) { if (BuildConfig.DEBUG) { mLogger.info("Generated server certificate"); } try { Certificate[] chain = { cert, rootCert }; setCertificate(chain, keyPair.getPrivate()); saveKeyStore(); if (BuildConfig.DEBUG) { mLogger.info("Saved server certificate"); } mSANs.add(new SAN(GeneralName.iPAddress, ipAddress)); callback.onSuccess(mKeyStore, cert, rootCert); } catch (Exception e) { mLogger.log(Level.SEVERE, "Failed to save server certificate", e); callback.onError(KeyStoreError.FAILED_BACKUP_KEYSTORE); } finally { localCA.dispose(); } } @Override public void onError() { mLogger.severe("Failed to generate server certificate"); localCA.dispose(); callback.onError(KeyStoreError.FAILED_BACKUP_KEYSTORE); } }); } } catch (KeyStoreException e) { callback.onError(KeyStoreError.BROKEN_KEYSTORE); } catch (GeneralSecurityException e) { callback.onError(KeyStoreError.UNSUPPORTED_CERTIFICATE_FORMAT); } } }); }
From source file:org.eclipse.milo.opcua.stack.core.util.CertificateUtil.java
License:Open Source License
/** * Generate a {@link PKCS10CertificationRequest}. * * @param keyPair the {@link KeyPair} containing Public and Private keys. * @param subject the subject name {@link X500Name}. * @param sanUri the URI to request in the SAN. * @param sanDnsNames the DNS names to request in the SAN. * @param sanIpAddresses the IP addresses to request in the SAN. * @param signatureAlgorithm the signature algorithm to use when generating the signature to validate the * certificate. * @return a {@link PKCS10CertificationRequest}. * @throws Exception if creating the signing request fails for any reason. *///from w w w .j a va2s . c o m public static PKCS10CertificationRequest generateCsr(KeyPair keyPair, X500Name subject, String sanUri, List<String> sanDnsNames, List<String> sanIpAddresses, String signatureAlgorithm) throws Exception { PKCS10CertificationRequestBuilder builder = new PKCS10CertificationRequestBuilder(subject, SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded())); List<GeneralName> generalNames = new ArrayList<>(); generalNames.add(new GeneralName(SUBJECT_ALT_NAME_URI, sanUri)); sanDnsNames.stream().map(n -> new GeneralName(SUBJECT_ALT_NAME_DNS_NAME, n)).forEach(generalNames::add); sanIpAddresses.stream().map(n -> new GeneralName(SUBJECT_ALT_NAME_IP_ADDRESS, n)) .forEach(generalNames::add); ExtensionsGenerator extGen = new ExtensionsGenerator(); extGen.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(generalNames.toArray(new GeneralName[0]))); builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate()); JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlgorithm); ContentSigner signer = signerBuilder.build(keyPair.getPrivate()); return builder.build(signer); }
From source file:org.eclipse.milo.opcua.stack.core.util.CertificateUtil.java
License:Open Source License
private static List<GeneralName> getSubjectAltNames(X509Certificate certificate) { try {/*from ww w . j ava2s . c o m*/ List<GeneralName> generalNames = new ArrayList<>(); Collection<List<?>> subjectAltNames = certificate.getSubjectAlternativeNames(); if (subjectAltNames == null) subjectAltNames = Collections.emptyList(); for (List<?> idAndValue : subjectAltNames) { if (idAndValue != null && idAndValue.size() == 2) { Object id = idAndValue.get(0); String value = Objects.toString(idAndValue.get(1)); if (Objects.equals(id, SUBJECT_ALT_NAME_DNS_NAME)) { generalNames.add(new GeneralName(SUBJECT_ALT_NAME_DNS_NAME, value)); } else if (Objects.equals(id, SUBJECT_ALT_NAME_IP_ADDRESS)) { generalNames.add(new GeneralName(SUBJECT_ALT_NAME_IP_ADDRESS, value)); } else if (Objects.equals(id, SUBJECT_ALT_NAME_URI)) { generalNames.add(new GeneralName(SUBJECT_ALT_NAME_URI, value)); } } } return generalNames; } catch (CertificateParsingException e) { return Collections.emptyList(); } }
From source file:org.eclipse.milo.opcua.stack.core.util.SelfSignedCertificateGenerator.java
License:Open Source License
protected void addSubjectAlternativeNames(X509v3CertificateBuilder certificateBuilder, KeyPair keyPair, @Nullable String applicationUri, List<String> dnsNames, List<String> ipAddresses) throws CertIOException, NoSuchAlgorithmException { List<GeneralName> generalNames = new ArrayList<>(); if (applicationUri != null) { generalNames.add(new GeneralName(GeneralName.uniformResourceIdentifier, applicationUri)); }//w w w . j ava 2 s. c om dnsNames.stream().distinct().map(s -> new GeneralName(GeneralName.dNSName, s)).forEach(generalNames::add); ipAddresses.stream().distinct().map(s -> new GeneralName(GeneralName.iPAddress, s)) .forEach(generalNames::add); certificateBuilder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(generalNames.toArray(new GeneralName[] {}))); // Subject Key Identifier certificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic())); }
From source file:org.ejbca.core.model.ca.caadmin.X509CA.java
License:Open Source License
/** Generate a list of Distribution points. * @param distPoints distribution points as String in semi column (';') separated format. * @return list of distribution points.//from www. j a v a2 s . c o m */ private List<DistributionPoint> generateDistributionPoints(String distPoints) { if (distPoints == null) { distPoints = ""; } // Multiple CDPs are separated with the ';' sign Iterator<String> it = StringTools.splitURIs(distPoints).iterator(); ArrayList<DistributionPoint> result = new ArrayList<DistributionPoint>(); while (it.hasNext()) { String uri = (String) it.next(); GeneralName gn = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(uri)); if (log.isDebugEnabled()) { log.debug("Added CRL distpoint: " + uri); } ASN1EncodableVector vec = new ASN1EncodableVector(); vec.add(gn); GeneralNames gns = new GeneralNames(new DERSequence(vec)); DistributionPointName dpn = new DistributionPointName(0, gns); result.add(new DistributionPoint(dpn, null, null)); } return result; }
From source file:org.ejbca.core.model.ca.certextensions.standard.AuthorityInformationAccess.java
License:Open Source License
@Override public DEREncodable getValue(final UserDataVO subject, final CA ca, final CertificateProfile certProfile, final PublicKey userPublicKey, final PublicKey caPublicKey) throws CertificateExtentionConfigurationException, CertificateExtensionException { final ASN1EncodableVector accessList = new ASN1EncodableVector(); GeneralName accessLocation;//from w w w . j a v a 2 s.c o m String url; // caIssuers final List<String> caIssuers = certProfile.getCaIssuers(); if (caIssuers != null) { for (final Iterator<String> it = caIssuers.iterator(); it.hasNext();) { url = it.next(); if (StringUtils.isNotEmpty(url)) { accessLocation = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(url)); accessList.add(new AccessDescription(AccessDescription.id_ad_caIssuers, accessLocation)); } } } // ocsp url final X509CA x509ca = (X509CA) ca; url = certProfile.getOCSPServiceLocatorURI(); if (certProfile.getUseDefaultOCSPServiceLocator()) { url = x509ca.getDefaultOCSPServiceLocator(); } if (StringUtils.isNotEmpty(url)) { accessLocation = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(url)); accessList.add(new AccessDescription(AccessDescription.id_ad_ocsp, accessLocation)); } org.bouncycastle.asn1.x509.AuthorityInformationAccess ret = null; if (accessList.size() > 0) { ret = new org.bouncycastle.asn1.x509.AuthorityInformationAccess(new DERSequence(accessList)); } if (ret == null) { log.error("AuthorityInformationAccess is used, but nor caIssuers not Ocsp url are defined!"); } return ret; }
From source file:org.ejbca.core.model.ca.certextensions.standard.CrlDistributionPoints.java
License:Open Source License
@Override public DEREncodable getValue(final UserDataVO subject, final CA ca, final CertificateProfile certProfile, final PublicKey userPublicKey, final PublicKey caPublicKey) throws CertificateExtentionConfigurationException, CertificateExtensionException { String crldistpoint = certProfile.getCRLDistributionPointURI(); String crlissuer = certProfile.getCRLIssuer(); final X509CA x509ca = (X509CA) ca; if (certProfile.getUseDefaultCRLDistributionPoint()) { crldistpoint = x509ca.getDefaultCRLDistPoint(); crlissuer = x509ca.getDefaultCRLIssuer(); }//from w w w . j a va 2s . co m // Multiple CDPs are separated with the ';' sign final ArrayList<DistributionPointName> dpns = new ArrayList<DistributionPointName>(); if (StringUtils.isNotEmpty(crldistpoint)) { final Iterator<String> it = StringTools.splitURIs(crldistpoint).iterator(); while (it.hasNext()) { // 6 is URI final String uri = (String) it.next(); final GeneralName gn = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(uri)); if (log.isDebugEnabled()) { log.debug("Added CRL distpoint: " + uri); } final ASN1EncodableVector vec = new ASN1EncodableVector(); vec.add(gn); final GeneralNames gns = new GeneralNames(new DERSequence(vec)); final DistributionPointName dpn = new DistributionPointName(0, gns); dpns.add(dpn); } } // CRL issuer works much like Dist point URI. If separated by ; it is put in the same global distPoint as the URI, // if there is more of one of them, the one with more is put in an own global distPoint. final ArrayList<GeneralNames> issuers = new ArrayList<GeneralNames>(); if (StringUtils.isNotEmpty(crlissuer)) { final StringTokenizer tokenizer = new StringTokenizer(crlissuer, ";", false); while (tokenizer.hasMoreTokens()) { final String issuer = tokenizer.nextToken(); final GeneralName gn = new GeneralName(new X509Name(issuer)); if (log.isDebugEnabled()) { log.debug("Added CRL issuer: " + issuer); } final ASN1EncodableVector vec = new ASN1EncodableVector(); vec.add(gn); final GeneralNames gns = new GeneralNames(new DERSequence(vec)); issuers.add(gns); } } final ArrayList<DistributionPoint> distpoints = new ArrayList<DistributionPoint>(); if ((!issuers.isEmpty()) || (!dpns.isEmpty())) { int i = dpns.size(); if (issuers.size() > i) { i = issuers.size(); } for (int j = 0; j < i; j++) { DistributionPointName dpn = null; GeneralNames issuer = null; if (dpns.size() > j) { dpn = (DistributionPointName) dpns.get(j); } if (issuers.size() > j) { issuer = (GeneralNames) issuers.get(j); } if ((dpn != null) || (issuer != null)) { distpoints.add(new DistributionPoint(dpn, null, issuer)); } } } CRLDistPoint ret = null; if (!distpoints.isEmpty()) { ret = new CRLDistPoint( (DistributionPoint[]) distpoints.toArray(new DistributionPoint[distpoints.size()])); } if (ret == null) { log.error("DrlDistributionPoints missconfigured, no distribution points available."); } return ret; }
From source file:org.ejbca.core.model.ca.certextensions.standard.FreshestCrl.java
License:Open Source License
@Override public DEREncodable getValue(final UserDataVO subject, final CA ca, final CertificateProfile certProfile, final PublicKey userPublicKey, final PublicKey caPublicKey) throws CertificateExtentionConfigurationException, CertificateExtensionException { String freshestcrldistpoint = certProfile.getFreshestCRLURI(); final X509CA x509ca = (X509CA) ca; if (certProfile.getUseCADefinedFreshestCRL()) { freshestcrldistpoint = x509ca.getCADefinedFreshestCRL(); }/*from ww w . j a v a 2 s .c o m*/ // Multiple FCDPs are separated with the ';' sign CRLDistPoint ret = null; if (freshestcrldistpoint != null) { final StringTokenizer tokenizer = new StringTokenizer(freshestcrldistpoint, ";", false); final ArrayList<DistributionPoint> distpoints = new ArrayList<DistributionPoint>(); while (tokenizer.hasMoreTokens()) { final String uri = tokenizer.nextToken(); final GeneralName gn = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(uri)); if (log.isDebugEnabled()) { log.debug("Added freshest CRL distpoint: " + uri); } final ASN1EncodableVector vec = new ASN1EncodableVector(); vec.add(gn); final GeneralNames gns = new GeneralNames(new DERSequence(vec)); final DistributionPointName dpn = new DistributionPointName(0, gns); distpoints.add(new DistributionPoint(dpn, null, null)); } if (!distpoints.isEmpty()) { ret = new CRLDistPoint( (DistributionPoint[]) distpoints.toArray(new DistributionPoint[distpoints.size()])); } } if (ret == null) { log.error("UseFreshestCRL is true, but no URI string defined!"); } return ret; }
From source file:org.ejbca.util.CertTools.java
License:Open Source License
/** * From an altName string as defined in getSubjectAlternativeName * @param altName//from w w w .j av a2s. co m * @return ASN.1 GeneralNames * @see #getSubjectAlternativeName */ public static GeneralNames getGeneralNamesFromAltName(String altName) { if (log.isTraceEnabled()) { log.trace(">getGeneralNamesFromAltName: " + altName); } ASN1EncodableVector vec = new ASN1EncodableVector(); ArrayList<String> emails = CertTools.getEmailFromDN(altName); if (!emails.isEmpty()) { Iterator<String> iter = emails.iterator(); while (iter.hasNext()) { GeneralName gn = new GeneralName(1, new DERIA5String((String) iter.next())); vec.add(gn); } } ArrayList<String> dns = CertTools.getPartsFromDN(altName, CertTools.DNS); if (!dns.isEmpty()) { Iterator<String> iter = dns.iterator(); while (iter.hasNext()) { GeneralName gn = new GeneralName(2, new DERIA5String((String) iter.next())); vec.add(gn); } } String directoryName = getDirectoryStringFromAltName(altName); if (directoryName != null) { X509Name x509DirectoryName = new X509Name(directoryName); GeneralName gn = new GeneralName(4, x509DirectoryName); vec.add(gn); } ArrayList<String> uri = CertTools.getPartsFromDN(altName, CertTools.URI); if (!uri.isEmpty()) { Iterator<String> iter = uri.iterator(); while (iter.hasNext()) { GeneralName gn = new GeneralName(6, new DERIA5String((String) iter.next())); vec.add(gn); } } uri = CertTools.getPartsFromDN(altName, CertTools.URI1); if (!uri.isEmpty()) { Iterator<String> iter = uri.iterator(); while (iter.hasNext()) { GeneralName gn = new GeneralName(6, new DERIA5String((String) iter.next())); vec.add(gn); } } uri = CertTools.getPartsFromDN(altName, CertTools.URI2); if (!uri.isEmpty()) { Iterator<String> iter = uri.iterator(); while (iter.hasNext()) { GeneralName gn = new GeneralName(6, new DERIA5String((String) iter.next())); vec.add(gn); } } ArrayList<String> ipstr = CertTools.getPartsFromDN(altName, CertTools.IPADDR); if (!ipstr.isEmpty()) { Iterator<String> iter = ipstr.iterator(); while (iter.hasNext()) { byte[] ipoctets = StringTools.ipStringToOctets((String) iter.next()); GeneralName gn = new GeneralName(7, new DEROctetString(ipoctets)); vec.add(gn); } } // UPN is an OtherName see method getUpn... for asn.1 definition ArrayList<String> upn = CertTools.getPartsFromDN(altName, CertTools.UPN); if (!upn.isEmpty()) { Iterator<String> iter = upn.iterator(); while (iter.hasNext()) { ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new DERObjectIdentifier(CertTools.UPN_OBJECTID)); v.add(new DERTaggedObject(true, 0, new DERUTF8String((String) iter.next()))); //GeneralName gn = new GeneralName(new DERSequence(v), 0); DERObject gn = new DERTaggedObject(false, 0, new DERSequence(v)); vec.add(gn); } } ArrayList<String> guid = CertTools.getPartsFromDN(altName, CertTools.GUID); if (!guid.isEmpty()) { Iterator<String> iter = guid.iterator(); while (iter.hasNext()) { ASN1EncodableVector v = new ASN1EncodableVector(); byte[] guidbytes = Hex.decode((String) iter.next()); if (guidbytes != null) { v.add(new DERObjectIdentifier(CertTools.GUID_OBJECTID)); v.add(new DERTaggedObject(true, 0, new DEROctetString(guidbytes))); DERObject gn = new DERTaggedObject(false, 0, new DERSequence(v)); vec.add(gn); } else { log.error("Cannot decode hexadecimal guid: " + guid); } } } // Krb5PrincipalName is an OtherName, see method getKrb5Principal...for ASN.1 definition ArrayList<String> krb5principalname = CertTools.getPartsFromDN(altName, CertTools.KRB5PRINCIPAL); if (!krb5principalname.isEmpty()) { Iterator<String> iter = krb5principalname.iterator(); while (iter.hasNext()) { // Start by parsing the input string to separate it in different parts String principalString = (String) iter.next(); if (log.isDebugEnabled()) { log.debug("principalString: " + principalString); } // The realm is the last part moving back until an @ int index = principalString.lastIndexOf('@'); String realm = ""; if (index > 0) { realm = principalString.substring(index + 1); } if (log.isDebugEnabled()) { log.debug("realm: " + realm); } // Now we can have several principals separated by / ArrayList<String> principalarr = new ArrayList<String>(); int jndex = 0; int bindex = 0; while (jndex < index) { // Loop and add all strings separated by / jndex = principalString.indexOf('/', bindex); if (jndex == -1) { jndex = index; } String s = principalString.substring(bindex, jndex); if (log.isDebugEnabled()) { log.debug("adding principal name: " + s); } principalarr.add(s); bindex = jndex + 1; } // Now we must construct the rather complex asn.1... ASN1EncodableVector v = new ASN1EncodableVector(); // this is the OtherName v.add(new DERObjectIdentifier(CertTools.KRB5PRINCIPAL_OBJECTID)); // First the Krb5PrincipalName sequence ASN1EncodableVector krb5p = new ASN1EncodableVector(); // The realm is the first tagged GeneralString krb5p.add(new DERTaggedObject(true, 0, new DERGeneralString(realm))); // Second is the sequence of principal names, which is at tagged position 1 in the krb5p ASN1EncodableVector principals = new ASN1EncodableVector(); // According to rfc4210 the type NT-UNKNOWN is 0, and according to some other rfc this type should be used... principals.add(new DERTaggedObject(true, 0, new DERInteger(0))); // The names themselves are yet another sequence Iterator<String> i = principalarr.iterator(); ASN1EncodableVector names = new ASN1EncodableVector(); while (i.hasNext()) { String principalName = (String) i.next(); names.add(new DERGeneralString(principalName)); } principals.add(new DERTaggedObject(true, 1, new DERSequence(names))); krb5p.add(new DERTaggedObject(true, 1, new DERSequence(principals))); v.add(new DERTaggedObject(true, 0, new DERSequence(krb5p))); DERObject gn = new DERTaggedObject(false, 0, new DERSequence(v)); vec.add(gn); } } // To support custom OIDs in altNames, they must be added as an OtherName of plain type UTF8String ArrayList<String> customoids = CertTools.getCustomOids(altName); if (!customoids.isEmpty()) { Iterator<String> iter = customoids.iterator(); while (iter.hasNext()) { String oid = (String) iter.next(); ArrayList<String> oidval = CertTools.getPartsFromDN(altName, oid); if (!oidval.isEmpty()) { Iterator<String> valiter = oidval.iterator(); while (valiter.hasNext()) { ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new DERObjectIdentifier(oid)); v.add(new DERTaggedObject(true, 0, new DERUTF8String((String) valiter.next()))); DERObject gn = new DERTaggedObject(false, 0, new DERSequence(v)); vec.add(gn); } } } } GeneralNames ret = null; if (vec.size() > 0) { ret = new GeneralNames(new DERSequence(vec)); } return ret; }
From source file:org.elasticsearch.xpack.core.ssl.CertGenUtils.java
License:Open Source License
@SuppressForbidden(reason = "need to use getHostName to resolve DNS name and getHostAddress to ensure we resolved the name") private static void addSubjectAlternativeNames(boolean resolveName, InetAddress inetAddress, Set<GeneralName> list) { String hostaddress = inetAddress.getHostAddress(); String ip = NetworkAddress.format(inetAddress); list.add(new GeneralName(GeneralName.iPAddress, ip)); if (resolveName && (inetAddress.isLinkLocalAddress() == false)) { String possibleHostName = inetAddress.getHostName(); if (possibleHostName.equals(hostaddress) == false) { list.add(new GeneralName(GeneralName.dNSName, possibleHostName)); }//from www .j a v a2s . com } }