List of usage examples for org.bouncycastle.asn1.x509 GeneralName GeneralName
public GeneralName(int tag, String name)
From source file:eu.emi.security.authn.x509.helpers.pkipath.bc.RFC3280CertPathUtilitiesHelper.java
License:Open Source License
/** * Checks a certificate if it is revoked. * //from w w w . ja v a2 s .c o m * @param paramsPKIX PKIX parameters. * @param cert Certificate to check if it is revoked. * @param validDate The date when the certificate revocation status * should be checked. * @param sign The issuer certificate of the certificate * <code>cert</code>. * @param workingPublicKey The public key of the issuer certificate * <code>sign</code>. * @param certPathCerts The certificates of the certification path. * @throws AnnotatedException if the certificate is revoked or the * status cannot be checked or some error occurs. */ protected static void checkCRLs2(ExtPKIXParameters paramsPKIX, X509Certificate cert, Date validDate, X509Certificate sign, PublicKey workingPublicKey, List<?> certPathCerts) throws SimpleValidationErrorException { SimpleValidationErrorException lastException = null; CRLDistPoint crldp = null; try { crldp = CRLDistPoint.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, RFC3280CertPathUtilities.CRL_DISTRIBUTION_POINTS)); } catch (Exception e) { throw new SimpleValidationErrorException(ValidationErrorCode.crlDistPtExtError, e); } try { CertPathValidatorUtilities.addAdditionalStoresFromCRLDistributionPoint(crldp, paramsPKIX); } catch (AnnotatedException e) { throw new SimpleValidationErrorException(ValidationErrorCode.crlDistPtExtError, e); } CertStatus certStatus = new CertStatus(); ReasonsMask reasonsMask = new ReasonsMask(); boolean validCrlFound = false; // for each distribution point if (crldp != null) { DistributionPoint dps[] = null; try { dps = crldp.getDistributionPoints(); } catch (Exception e) { throw new SimpleValidationErrorException(ValidationErrorCode.crlDistPtExtError, e); } if (dps != null) { for (int i = 0; i < dps.length && certStatus.getCertStatus() == CertStatus.UNREVOKED && !reasonsMask.isAllReasons(); i++) { ExtendedPKIXParameters paramsPKIXClone = (ExtendedPKIXParameters) paramsPKIX.clone(); try { checkCRL(dps[i], paramsPKIXClone, cert, validDate, sign, workingPublicKey, certStatus, reasonsMask, certPathCerts); validCrlFound = true; } catch (SimpleValidationErrorException e) { lastException = e; } } } } /* * If the revocation status has not been determined, repeat the * process above with any available CRLs not specified in a * distribution point but issued by the certificate issuer. */ if (certStatus.getCertStatus() == CertStatus.UNREVOKED && !reasonsMask.isAllReasons()) { try { /* * assume a DP with both the reasons and the * cRLIssuer fields omitted and a distribution * point name of the certificate issuer. */ ASN1Primitive issuer = null; try { issuer = new ASN1InputStream( CertPathValidatorUtilities.getEncodedIssuerPrincipal(cert).getEncoded()).readObject(); } catch (Exception e) { throw new SimpleValidationErrorException(ValidationErrorCode.crlIssuerException, e); } DistributionPoint dp = new DistributionPoint(new DistributionPointName(0, new GeneralNames(new GeneralName(GeneralName.directoryName, issuer))), null, null); ExtendedPKIXParameters paramsPKIXClone = (ExtendedPKIXParameters) paramsPKIX.clone(); checkCRL(dp, paramsPKIXClone, cert, validDate, sign, workingPublicKey, certStatus, reasonsMask, certPathCerts); validCrlFound = true; } catch (SimpleValidationErrorException e) { lastException = e; } } if (!validCrlFound) throw lastException; if (certStatus.getCertStatus() != CertStatus.UNREVOKED) { throw new SimpleValidationErrorException(ValidationErrorCode.certRevoked, new TrustedInput(certStatus.getRevocationDate()), crlReasons[certStatus.getCertStatus()]); } if (!reasonsMask.isAllReasons() && certStatus.getCertStatus() == CertStatus.UNREVOKED) { certStatus.setCertStatus(CertStatus.UNDETERMINED); } if (certStatus.getCertStatus() == CertStatus.UNDETERMINED) { throw new SimpleValidationErrorException(ValidationErrorCode.noValidCrlFound); } }
From source file:eu.emi.security.authn.x509.helpers.proxy.ProxyAddressRestrictionData.java
License:Open Source License
/** * Adds a new permitted IP addressSpace to the data structure. * // w ww .j av a 2 s.c o m * @param address The address space to add to the allowed ip address * space. Example of the format: 192.168.0.0/16. Which * equals a 192.168.0.0 with a net mask 255.255.0.0. A * single IP address can be defined as * xxx.xxx.xxx.xxx/32. <br> It is also possible to provide IPv6 * addresses. * See <a href="http://www.ietf.org/rfc/rfc4632.txt"> RFC4632.</a> */ public void addPermittedIPAddressWithNetmask(String address) { permittedGeneralSubtrees .add(new GeneralSubtree(new GeneralName(GeneralName.iPAddress, address), null, null)); }
From source file:eu.emi.security.authn.x509.helpers.proxy.ProxyAddressRestrictionData.java
License:Open Source License
/** * Adds a new excluded IP addressSpace to the data structure. * //from w w w.ja v a2 s.c o m * @param address The address space to add to the allowed ip address * space. Example of the format: 192.168.0.0/16. Which * equals a 192.168.0.0 with a net mask 255.255.0.0. A * single IP address can be defined as * xxx.xxx.xxx.xxx/32. <br> It is also possible to provide IPv6 * addresses. See <a href="http://www.ietf.org/rfc/rfc4632.txt"> RFC4632.</a> */ public void addExcludedIPAddressWithNetmask(String address) { excludedGeneralSubtrees .add(new GeneralSubtree(new GeneralName(GeneralName.iPAddress, address), null, null)); }
From source file:eu.emi.security.authn.x509.helpers.proxy.ProxyTracingExtension.java
License:Open Source License
/** * Generates a new proxy tracing item from the URL. * /*from w w w .ja v a 2s . co m*/ * @param url * The URL to identify the issuer or the subject. */ public ProxyTracingExtension(String url) { name = new GeneralName(GeneralName.uniformResourceIdentifier, url); names = new GeneralNames(name); }
From source file:fathom.x509.X509Utils.java
License:Apache License
/** * Creates a new SSL certificate signed by the CA private key and stored in * keyStore.//from w w w. j av a2s . c om * * @param sslMetadata * @param caPrivateKey * @param caCert * @param targetStoreFile * @param x509log */ public static X509Certificate newSSLCertificate(X509Metadata sslMetadata, PrivateKey caPrivateKey, X509Certificate caCert, File targetStoreFile, X509Log x509log) { try { KeyPair pair = newKeyPair(); X500Name webDN = buildDistinguishedName(sslMetadata); X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName()); X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuerDN, BigInteger.valueOf(System.currentTimeMillis()), sslMetadata.notBefore, sslMetadata.notAfter, webDN, pair.getPublic()); JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); certBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(pair.getPublic())); certBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false)); certBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert.getPublicKey())); // support alternateSubjectNames for SSL certificates List<GeneralName> altNames = new ArrayList<GeneralName>(); if (isIpAddress(sslMetadata.commonName)) { altNames.add(new GeneralName(GeneralName.iPAddress, sslMetadata.commonName)); } if (altNames.size() > 0) { GeneralNames subjectAltName = new GeneralNames(altNames.toArray(new GeneralName[altNames.size()])); certBuilder.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName); } ContentSigner caSigner = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC) .build(caPrivateKey); X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC) .getCertificate(certBuilder.build(caSigner)); cert.checkValidity(new Date()); cert.verify(caCert.getPublicKey()); // Save to keystore KeyStore serverStore = openKeyStore(targetStoreFile, sslMetadata.password); serverStore.setKeyEntry(sslMetadata.commonName, pair.getPrivate(), sslMetadata.password.toCharArray(), new Certificate[] { cert, caCert }); saveKeyStore(targetStoreFile, serverStore, sslMetadata.password); x509log.log(MessageFormat.format("New SSL certificate {0,number,0} [{1}]", cert.getSerialNumber(), cert.getSubjectDN().getName())); // update serial number in metadata object sslMetadata.serialNumber = cert.getSerialNumber().toString(); return cert; } catch (Throwable t) { throw new RuntimeException("Failed to generate SSL certificate!", t); } }
From source file:fathom.x509.X509Utils.java
License:Apache License
/** * Creates a new client certificate PKCS#12 and PEM store. Any existing * stores are destroyed./* www . ja v a 2 s . c o m*/ * * @param clientMetadata a container for dynamic parameters needed for generation * @param caPrivateKey * @param caCert * @param targetFolder * @return */ public static X509Certificate newClientCertificate(X509Metadata clientMetadata, PrivateKey caPrivateKey, X509Certificate caCert, File targetFolder) { try { KeyPair pair = newKeyPair(); X500Name userDN = buildDistinguishedName(clientMetadata); X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName()); // create a new certificate signed by the Fathom CA certificate X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuerDN, BigInteger.valueOf(System.currentTimeMillis()), clientMetadata.notBefore, clientMetadata.notAfter, userDN, pair.getPublic()); JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); certBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(pair.getPublic())); certBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false)); certBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert.getPublicKey())); certBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.digitalSignature)); if (!Strings.isNullOrEmpty(clientMetadata.emailAddress)) { GeneralNames subjectAltName = new GeneralNames( new GeneralName(GeneralName.rfc822Name, clientMetadata.emailAddress)); certBuilder.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName); } ContentSigner signer = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC) .build(caPrivateKey); X509Certificate userCert = new JcaX509CertificateConverter().setProvider(BC) .getCertificate(certBuilder.build(signer)); PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) pair.getPrivate(); bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, extUtils.createSubjectKeyIdentifier(pair.getPublic())); // confirm the validity of the user certificate userCert.checkValidity(); userCert.verify(caCert.getPublicKey()); userCert.getIssuerDN().equals(caCert.getSubjectDN()); // verify user certificate chain verifyChain(userCert, caCert); targetFolder.mkdirs(); // save certificate, stamped with unique name String date = new SimpleDateFormat("yyyyMMdd").format(new Date()); String id = date; File certFile = new File(targetFolder, id + ".cer"); int count = 0; while (certFile.exists()) { id = date + "_" + Character.toString((char) (0x61 + count)); certFile = new File(targetFolder, id + ".cer"); count++; } // save user private key, user certificate and CA certificate to a PKCS#12 store File p12File = new File(targetFolder, clientMetadata.commonName + ".p12"); if (p12File.exists()) { p12File.delete(); } KeyStore userStore = openKeyStore(p12File, clientMetadata.password); userStore.setKeyEntry( MessageFormat.format("Fathom ({0}) {1} {2}", clientMetadata.serverHostname, clientMetadata.userDisplayname, id), pair.getPrivate(), null, new Certificate[] { userCert }); userStore.setCertificateEntry( MessageFormat.format("Fathom ({0}) Certificate Authority", clientMetadata.serverHostname), caCert); saveKeyStore(p12File, userStore, clientMetadata.password); // save user private key, user certificate, and CA certificate to a PEM store File pemFile = new File(targetFolder, clientMetadata.commonName + ".pem"); if (pemFile.exists()) { pemFile.delete(); } PEMWriter pemWriter = new PEMWriter(new FileWriter(pemFile)); pemWriter.writeObject(pair.getPrivate(), "DES-EDE3-CBC", clientMetadata.password.toCharArray(), new SecureRandom()); pemWriter.writeObject(userCert); pemWriter.writeObject(caCert); pemWriter.flush(); pemWriter.close(); // save certificate after successfully creating the key stores saveCertificate(userCert, certFile); // update serial number in metadata object clientMetadata.serialNumber = userCert.getSerialNumber().toString(); return userCert; } catch (Throwable t) { throw new RuntimeException("Failed to generate client certificate!", t); } }
From source file:fi.aalto.cs.drumbeat.ClientCertificateCreator.java
License:Open Source License
public void addURI(String subjectAlternativeName) { sans.add(new GeneralName(GeneralName.uniformResourceIdentifier, subjectAlternativeName)); }
From source file:g4mfs.impl.org.peertrust.security.credentials.CryptTools.java
License:Open Source License
/** * Generate a Certificate that holds a Credential as a critical Extension in it. * @param pubKey the public key of the subject of the credential. This * is needed to create a valid X509Certificate and might be usefull to * improve security, when a public key infrastructure is used in this * prototype environment.// w w w.j a v a2 s. c o m * @param subject the distinguished name of the subject of this * credential. Important: There exists a certain format for distinguished * names. For example "CN=alice" is a valid DN. * @param credential the String Representation of the credential * @param issuer the name of the signer of the credential. This should * be the person the caPrivKey belongs to. * @param caPrivKey the key that is used to sign the credential * @return A X.509Certificate */ public static X509Certificate createCert(String subject, String credential, PublicKey pubKey, String issuer, PrivateKey caPrivKey) throws Exception { X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); // create the certificate - version 3 (only v3 allows usage of extensions) v3CertGen.reset(); // TODO: Eindeutige Serialno v3CertGen.setSerialNumber(java.math.BigInteger.valueOf(3)); v3CertGen.setIssuerDN(new X509Principal(issuer)); v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30)); v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30))); v3CertGen.setSubjectDN(new X509Principal(subject)); v3CertGen.setPublicKey(pubKey); v3CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); // add the extensions // - the credential as an extension // - try to create a "SubjectAlternativeName" Extension in the othername field // - create an OtherName (there is no OtherName class, so I have to improvise) int tag = 2; // Tag-Class 'Universal', BIT STRING: 2(works fine), OCTET STRING: 3 DERObject derO = new DERPrintableString(credential); // - create a GeneralName GeneralName gn = new GeneralName(derO, tag); // - create a GeneralNames set of it: DERSequence ders = new DERSequence(gn); GeneralNames gns = new GeneralNames(ders); v3CertGen.addExtension(X509Extensions.SubjectAlternativeName, true, gns); // generate the cert X509Certificate cert = v3CertGen.generateX509Certificate(caPrivKey); // Testing: cert.checkValidity(new Date()); return cert; }
From source file:gui.ExtensionsPopup.java
private void addIssuerAltNameButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addIssuerAltNameButtonActionPerformed String extension = issuerAltNameTextField.getText(); issuerAltNameTextField.setText(""); if (!extension.isEmpty()) { String extName = (String) issuerAltNameComboBox.getSelectedItem(); try {/*ww w . j a v a 2 s . c o m*/ switch (extName) { case "Other Name": generalNamesBuilder.addName(new GeneralName(GeneralName.otherName, extension)); break; case "RFC822 Name": generalNamesBuilder.addName(new GeneralName(GeneralName.rfc822Name, extension)); break; case "DNS Name": generalNamesBuilder.addName(new GeneralName(GeneralName.dNSName, extension)); break; case "x400 Address": generalNamesBuilder.addName(new GeneralName(GeneralName.x400Address, extension)); break; case "Directory Name": generalNamesBuilder .addName(new GeneralName(GeneralName.directoryName, new X500Name(extension))); break; case "EDI Party Name": generalNamesBuilder.addName(new GeneralName(GeneralName.ediPartyName, extension)); break; case "URI": generalNamesBuilder.addName(new GeneralName(GeneralName.uniformResourceIdentifier, extension)); break; case "IP Address": generalNamesBuilder.addName(new GeneralName(GeneralName.iPAddress, extension)); break; case "Registered ID": generalNamesBuilder.addName(new GeneralName(GeneralName.registeredID, extension)); break; } } catch (Exception e) { JOptionPane.showMessageDialog(this, Errors.EXTENSION_INVALID_FORMAT, "Error", JOptionPane.ERROR_MESSAGE); return; } issuerAltNameTextArea.append(extName + ": " + extension + "\n"); } }
From source file:hu.akarnokd.utils.crypto.KeystoreManager.java
License:Apache License
/** * Generate a X509 certificate for the given keypair. * The distinguished names must be in format: CN=cName, OU=orgUnit, O=org, L=city, S=state, C=countryCode * use backslash to escape a comma/*from w w w . j a v a 2s . co m*/ * @param keypair the keypair * @param months the validity length in months * @param issuerDN the issuer distinguished name: "CN=David Karnok,OU=EMI,O=MTA SZTAKI" * @param subjectDN the subject distinguished name: "CN=David Karnok,OU=EMI,O=MTA SZTAKI" * @param domain domain of the server to store in the subject alternative name extension * @param signAlgorithm the signing algorithm to use * @return the generated X509 certificate */ public X509Certificate createX509Certificate(KeyPair keypair, int months, String issuerDN, String subjectDN, String domain, String signAlgorithm) { try { // calendar for date calculations GregorianCalendar cal = new GregorianCalendar(); // extract keypair components PublicKey pubKey = keypair.getPublic(); PrivateKey privKey = keypair.getPrivate(); // generate a random serial number SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(System.currentTimeMillis()); byte[] serialNo = new byte[8]; random.nextBytes(serialNo); BigInteger serial = new BigInteger(serialNo).abs(); // create the certificate generator X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.reset(); // set certificate attributes certGen.setSerialNumber(serial); cal.setTimeInMillis(System.currentTimeMillis()); certGen.setNotBefore(cal.getTime()); cal.add(GregorianCalendar.MONTH, months); certGen.setNotAfter(cal.getTime()); certGen.setPublicKey(pubKey); certGen.setSignatureAlgorithm(signAlgorithm); certGen.setIssuerDN(new X509Name(issuerDN)); certGen.setSubjectDN(new X509Name(subjectDN)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pubKey)); // create subject alternative name boolean isCritical = subjectDN == null || "".equals(subjectDN.trim()); DERSequence othernameSeq = new DERSequence( new ASN1Encodable[] { new DERObjectIdentifier("1.3.6.1.5.5.7.8.5"), new DERTaggedObject(true, 0, new DERUTF8String(domain)) }); GeneralName othernameGen = new GeneralName(GeneralName.otherName, othernameSeq); GeneralNames subjectAlternatives = new GeneralNames(othernameGen); certGen.addExtension(X509Extensions.SubjectAlternativeName, isCritical, subjectAlternatives); // finally generate the certificate X509Certificate cert = certGen.generateX509Certificate(privKey, BC_PROVIDER.getName(), new SecureRandom()); cert.checkValidity(new Date()); cert.verify(pubKey); return cert; } catch (NoSuchAlgorithmException ex) { throw new KeystoreFault(ex); } catch (CertificateException ex) { throw new KeystoreFault(ex); } catch (SignatureException ex) { throw new KeystoreFault(ex); } catch (NoSuchProviderException ex) { throw new KeystoreFault(ex); } catch (InvalidKeyException ex) { throw new KeystoreFault(ex); } }