List of usage examples for org.bouncycastle.asn1.x500.style BCStyle EmailAddress
ASN1ObjectIdentifier EmailAddress
To view the source code for org.bouncycastle.asn1.x500.style BCStyle EmailAddress.
Click Source Link
From source file:com.thoughtworks.go.security.X509CertificateGenerator.java
License:Apache License
private X509Certificate createIntermediateCertificate(PrivateKey caPrivKey, X509Certificate caCert, Date startDate, KeyPair keyPair) throws Exception { X500Name issuerDn = JcaX500NameUtil.getSubject(caCert); X500NameBuilder subjectBuilder = new X500NameBuilder(BCStyle.INSTANCE); subjectBuilder.addRDN(BCStyle.OU, INTERMEDIATE_CERT_OU); subjectBuilder.addRDN(BCStyle.EmailAddress, CERT_EMAIL); X500Name subjectDn = subjectBuilder.build(); X509CertificateGenerator.V3X509CertificateGenerator v3CertGen = new V3X509CertificateGenerator(startDate, issuerDn, subjectDn, keyPair.getPublic(), serialNumber()); // extensions v3CertGen.addSubjectKeyIdExtension(keyPair.getPublic()); v3CertGen.addAuthorityKeyIdExtension(caCert); v3CertGen.addBasicConstraintsExtension(); X509Certificate cert = v3CertGen.generate(caPrivKey); Date now = new Date(); cert.checkValidity(now);//from w w w .j a v a2s . co m cert.verify(caCert.getPublicKey()); PKCS12BagAttributeSetter.usingBagAttributeCarrier(cert).setFriendlyName(INTERMEDIATE_CERT_OU); PKCS12BagAttributeSetter.usingBagAttributeCarrier(keyPair.getPrivate()).setFriendlyName(FRIENDLY_NAME) .setLocalKeyId(keyPair.getPublic()); return cert; }
From source file:com.thoughtworks.go.security.X509CertificateGenerator.java
License:Apache License
private X509Certificate createAgentCertificate(PublicKey publicKey, PrivateKey intermediatePrivateKey, PublicKey intermediatePublicKey, String hostname, Date startDate) throws Exception { X500NameBuilder issuerBuilder = new X500NameBuilder(BCStyle.INSTANCE); issuerBuilder.addRDN(BCStyle.OU, INTERMEDIATE_CERT_OU); issuerBuilder.addRDN(BCStyle.EmailAddress, CERT_EMAIL); X500Name issuerDn = issuerBuilder.build(); X500NameBuilder subjectBuilder = new X500NameBuilder(BCStyle.INSTANCE); subjectBuilder.addRDN(BCStyle.OU, AGENT_CERT_OU); subjectBuilder.addRDN(BCStyle.CN, hostname); subjectBuilder.addRDN(BCStyle.EmailAddress, CERT_EMAIL); X500Name subjectDn = subjectBuilder.build(); X509CertificateGenerator.V3X509CertificateGenerator v3CertGen = new V3X509CertificateGenerator(startDate, issuerDn, subjectDn, publicKey, BigInteger.valueOf(3)); // add the extensions v3CertGen.addSubjectKeyIdExtension(publicKey); v3CertGen.addAuthorityKeyIdExtension(intermediatePublicKey); X509Certificate cert = v3CertGen.generate(intermediatePrivateKey); Date now = new Date(); cert.checkValidity(now);/* w ww . j a v a2s .c o m*/ cert.verify(intermediatePublicKey); PKCS12BagAttributeSetter.usingBagAttributeCarrier(cert).setFriendlyName("cruise-agent") .setLocalKeyId(publicKey); return cert; }
From source file:cz.etruhla.mailsigner.Helpers.java
License:Apache License
/** * vybere z certifikatu vsechny emaily ktere muze podepsat * /* w w w. j av a 2 s .c o m*/ * @param cert * @return * @throws CertificateParsingException * @throws AddressException */ public static Set<InternetAddress> getEmailAddresses(X509Certificate cert) throws CertificateParsingException, AddressException { HashSet<InternetAddress> addresses = new HashSet<InternetAddress>(); X500Name x500name = new X500Name(cert.getSubjectDN().getName()); RDN[] ems; ems = x500name.getRDNs(BCStyle.EmailAddress);// Email address (RSA // PKCS#9 extension) - // IA5String. if (ems != null && ems.length > 0) { for (RDN em : ems) { addresses.add(new InternetAddress(IETFUtils.valueToString(em.getFirst().getValue()))); } } ems = x500name.getRDNs(BCStyle.E);// email address in Verisign // certificates if (ems != null && ems.length > 0) { for (RDN em : ems) { addresses.add(new InternetAddress(IETFUtils.valueToString(em.getFirst().getValue()))); } } // projeti subject alternative name if (cert.getSubjectAlternativeNames() != null) { for (List<?> l : cert.getSubjectAlternativeNames()) { if ((Integer) (l.get(0)) == SUBALTNAME_RFC822NAME) { addresses.add(new InternetAddress((String) (l.get(1)))); } } } return addresses; }
From source file:net.maritimecloud.identityregistry.keycloak.spi.authenticators.certificate.utils.CertificateUtil.java
License:Apache License
public Map<String, String> getUserFromCert(X509Certificate userCertificate) { Map<String, String> user = new HashMap<>(); String certDN = userCertificate.getSubjectDN().getName(); X500Name x500name = new X500Name(certDN); logger.warn("Parsed certificate, DN: " + certDN); String fullname = getElement(x500name, BCStyle.CN); user.put("fullname", fullname); String combinedOrg = getElement(x500name, BCStyle.O); user.put("email", getElement(x500name, BCStyle.EmailAddress)); // Extract first and last name from full name String lastName = ""; String firstName = ""; if (fullname.split("\\w+").length > 1) { lastName = fullname.substring(fullname.lastIndexOf(" ") + 1); firstName = fullname.substring(0, fullname.lastIndexOf(' ')); } else {/*from w w w . ja v a 2 s .c o m*/ firstName = fullname; } user.put("lastName", lastName); user.put("firstName", firstName); String[] orgNames = combinedOrg.split(";"); String orgShortName = orgNames[0].toLowerCase(); user.put("orgShortName", orgShortName); user.put("orgFullName", orgNames[1]); // prefix orgUserName with org shortname if not already done String orgUserName = getElement(x500name, BCStyle.UID).toLowerCase(); if (!orgUserName.startsWith(orgShortName + ".")) { orgUserName = orgShortName.toLowerCase() + "." + orgUserName; } user.put("orgUserName", orgUserName); user.put("type", getElement(x500name, BCStyle.OU)); // Extract info from Subject Alternative Name extension Collection<List<?>> san = null; try { san = userCertificate.getSubjectAlternativeNames(); } catch (CertificateParsingException e) { logger.warn("could not extract info from Subject Alternative Names - will be ignored."); } // Check that the certificate includes the SubjectAltName extension if (san != null) { // Use the type OtherName to search for the certified server name for (List item : san) { Integer type = (Integer) item.get(0); if (type == 0) { // Type OtherName found so return the associated value ASN1InputStream decoder = null; String oid = ""; String value = ""; try { // Value is encoded using ASN.1 so decode it to get it out again decoder = new ASN1InputStream((byte[]) item.toArray()[1]); DLSequence seq = (DLSequence) decoder.readObject(); ASN1ObjectIdentifier asnOID = (ASN1ObjectIdentifier) seq.getObjectAt(0); ASN1Encodable encoded = seq.getObjectAt(1); encoded = ((DERTaggedObject) encoded).getObject(); encoded = ((DERTaggedObject) encoded).getObject(); oid = asnOID.getId(); value = ((DERUTF8String) encoded).getString(); } catch (UnsupportedEncodingException e) { logger.error("Error decoding subjectAltName" + e.getLocalizedMessage(), e); continue; } catch (Exception e) { logger.error("Error decoding subjectAltName" + e.getLocalizedMessage(), e); continue; } finally { if (decoder != null) { try { decoder.close(); } catch (IOException e) { } } } logger.debug("oid: " + oid + ", value: " + value); switch (oid) { case MC_OID_FLAGSTATE: case MC_OID_CALLSIGN: case MC_OID_IMO_NUMBER: case MC_OID_MMSI_NUMBER: case MC_OID_AIS_SHIPTYPE: case MC_OID_PORT_OF_REGISTER: logger.debug("Ship specific OIDs are ignored"); break; case MC_OID_MRN: // We only support 1 mrn user.put("mrn", value); break; case MC_OID_PERMISSIONS: user.put("permissions", value); break; default: logger.error("Unknown OID!"); break; } } else { // Other types are not supported so ignore them logger.warn("SubjectAltName of invalid type found: " + type); } } } return user; }
From source file:net.maritimecloud.pki.CertificateHandler.java
License:Apache License
/** * Extracts a PKIIdentity from a certificate using the MC PKI certificate "format" * * @param userCertificate The certificate * @return The extracted identity//from w w w .j av a2 s. co m */ public static PKIIdentity getIdentityFromCert(X509Certificate userCertificate) { PKIIdentity identity = new PKIIdentity(); String certDN = userCertificate.getSubjectDN().getName(); X500Name x500name = new X500Name(certDN); String name = getElement(x500name, BCStyle.CN); String uid = getElement(x500name, BCStyle.UID); identity.setMrn(uid); identity.setDn(certDN); identity.setCn(name); identity.setSn(name); identity.setO(getElement(x500name, BCStyle.O)); identity.setOu(getElement(x500name, BCStyle.OU)); identity.setCountry(getElement(x500name, BCStyle.C)); identity.setEmail(getElement(x500name, BCStyle.EmailAddress)); // Extract first and last name from full name String lastName = ""; String firstName = ""; if (name.split("\\w +\\w").length > 1) { lastName = name.substring(name.lastIndexOf(" ") + 1); firstName = name.substring(0, name.lastIndexOf(' ')); } else { firstName = name; } identity.setFirstName(firstName); identity.setLastName(lastName); log.debug("Parsed certificate, name: " + name); // Extract info from Subject Alternative Name extension Collection<List<?>> san = null; try { san = userCertificate.getSubjectAlternativeNames(); } catch (CertificateParsingException e) { log.warn("could not extract info from Subject Alternative Names - will be ignored."); } // Check that the certificate includes the SubjectAltName extension if (san != null) { // Use the type OtherName to search for the certified server name StringBuilder permissions = new StringBuilder(); for (List item : san) { Integer type = (Integer) item.get(0); if (type == 0) { // Type OtherName found so return the associated value ASN1InputStream decoder = null; String oid; String value; try { // Value is encoded using ASN.1 so decode it to get it out again decoder = new ASN1InputStream((byte[]) item.toArray()[1]); DLSequence seq = (DLSequence) decoder.readObject(); ASN1ObjectIdentifier asnOID = (ASN1ObjectIdentifier) seq.getObjectAt(0); ASN1Encodable encoded = seq.getObjectAt(1); oid = asnOID.getId(); // For some weird reason we need to do this 2 times - otherwise we get a // ClassCastException when extracting the value. encoded = ((DERTaggedObject) encoded).getObject(); encoded = ((DERTaggedObject) encoded).getObject(); value = ((DERUTF8String) encoded).getString(); } catch (UnsupportedEncodingException e) { log.error("Error decoding subjectAltName" + e.getLocalizedMessage(), e); continue; } catch (Exception e) { log.error("Error decoding subjectAltName" + e.getLocalizedMessage(), e); continue; } finally { if (decoder != null) { try { decoder.close(); } catch (IOException e) { e.printStackTrace(); } } } log.debug("oid: " + oid + ", value: " + value); switch (oid) { case MC_OID_FLAGSTATE: identity.setFlagState(value); break; case MC_OID_CALLSIGN: identity.setCallSign(value); break; case MC_OID_IMO_NUMBER: identity.setImoNumber(value); break; case MC_OID_MMSI_NUMBER: identity.setMmsiNumber(value); break; case MC_OID_AIS_SHIPTYPE: identity.setAisShipType(value); break; case MC_OID_PORT_OF_REGISTER: identity.setPortOfRegister(value); break; case MC_OID_MRN: // We only support 1 mrn identity.setMrn(value); break; case MC_OID_SHIP_MRN: identity.setShipMrn(value); case MC_OID_PERMISSIONS: if (value != null && !value.trim().isEmpty()) { if (permissions.length() == 0) { permissions = new StringBuilder(value); } else { permissions.append(',').append(value); } } break; default: log.error("Unknown OID!"); break; } } else { // Other types are not supported so ignore them log.warn("SubjectAltName of invalid type found: " + type); } } if (permissions.length() > 0) { identity.setPermissions(permissions.toString()); } } return identity; }
From source file:org.apache.jmeter.assertions.SMIMEAssertion.java
License:Apache License
/** * Extract email addresses from a certificate * //from www.j a va 2 s .c o m * @param cert the X509 certificate holder * @return a List of all email addresses found * @throws CertificateException */ private static List<String> getEmailFromCert(X509CertificateHolder cert) throws CertificateException { List<String> res = new ArrayList<>(); X500Name subject = cert.getSubject(); for (RDN emails : subject.getRDNs(BCStyle.EmailAddress)) { for (AttributeTypeAndValue emailAttr : emails.getTypesAndValues()) { log.debug("Add email from RDN: " + IETFUtils.valueToString(emailAttr.getValue())); res.add(IETFUtils.valueToString(emailAttr.getValue())); } } Extension subjectAlternativeNames = cert.getExtension(Extension.subjectAlternativeName); if (subjectAlternativeNames != null) { for (GeneralName name : GeneralNames.getInstance(subjectAlternativeNames.getParsedValue()).getNames()) { if (name.getTagNo() == GeneralName.rfc822Name) { String email = IETFUtils.valueToString(name.getName()); log.debug("Add email from subjectAlternativeName: " + email); res.add(email); } } } return res; }
From source file:org.computerist.ssltools.zap.FixedSslCertificateService.java
License:Apache License
public KeyStore createCertForHost(String hostname) throws NoSuchAlgorithmException, InvalidKeyException, CertificateException, NoSuchProviderException, SignatureException, KeyStoreException, IOException, UnrecoverableKeyException { if (hostname == null) { throw new IllegalArgumentException("Error, 'hostname' is not allowed to be null!"); }//from ww w. j a v a 2 s . c o m if (this.caCert == null || this.caPrivKey == null || this.caPubKey == null) { throw new RuntimeException( this.getClass() + " wasn't initialized! Got to options 'Dynamic SSL Certs' and create one."); } final KeyPair mykp = this.createKeyPair(); final PrivateKey privKey = mykp.getPrivate(); final PublicKey pubKey = mykp.getPublic(); X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE); namebld.addRDN(BCStyle.CN, hostname); namebld.addRDN(BCStyle.OU, "Zed Attack Proxy Project"); namebld.addRDN(BCStyle.O, "OWASP"); namebld.addRDN(BCStyle.C, "xx"); namebld.addRDN(BCStyle.EmailAddress, "owasp-zed-attack-proxy@lists.owasp.org"); X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder( new X509CertificateHolder(caCert.getEncoded()).getSubject(), BigInteger.valueOf(serial.getAndIncrement()), new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), new Date(System.currentTimeMillis() + 100 * (1000L * 60 * 60 * 24 * 30)), namebld.build(), pubKey); certGen.addExtension(X509Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pubKey)); certGen.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false)); ContentSigner sigGen; try { sigGen = new JcaContentSignerBuilder("SHA1WithRSAEncryption").setProvider("BC").build(caPrivKey); } catch (OperatorCreationException e) { throw new CertificateException(e); } final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC") .getCertificate(certGen.build(sigGen)); cert.checkValidity(new Date()); cert.verify(caPubKey); final Certificate[] chain = new Certificate[2]; chain[1] = this.caCert; chain[0] = cert; userKs.setKeyEntry(hostname, privKey, PASSPHRASE, chain); return userKs; }
From source file:org.icepdf.ri.common.utility.signatures.SignatureTreeNode.java
License:Apache License
/** * Validates the signatures represented by this tree node. This method is called by a worker thread * and once validation is complete the notes states is updated with a call to {@link #refreshSignerNode()} * * @throws SignatureIntegrityException/*from w w w. j av a2 s. c o m*/ */ public void validateSignatureNode() throws SignatureIntegrityException { SignatureFieldDictionary fieldDictionary = signatureWidgetAnnotation.getFieldDictionary(); SignatureDictionary signatureDictionary = signatureWidgetAnnotation.getSignatureDictionary(); if (fieldDictionary != null) { // grab some signer properties right from the annotations dictionary. name = signatureDictionary.getName(); location = signatureDictionary.getLocation(); reason = signatureDictionary.getReason(); contact = signatureDictionary.getContactInfo(); date = signatureDictionary.getDate(); // getting a signatureValidator should give us a pointer the to the signer cert if all goes well. signatureValidator = signatureWidgetAnnotation.getSignatureValidator(); // try and parse out the signer info. X509Certificate certificate = signatureValidator.getSignerCertificate(); X500Principal principal = certificate.getIssuerX500Principal(); X500Name x500name = new X500Name(principal.getName()); if (x500name.getRDNs() != null) { commonName = SignatureUtilities.parseRelativeDistinguishedName(x500name, BCStyle.CN); organization = SignatureUtilities.parseRelativeDistinguishedName(x500name, BCStyle.O); emailAddress = SignatureUtilities.parseRelativeDistinguishedName(x500name, BCStyle.EmailAddress); } // Start validation process. setVerifyingSignature(true); signatureValidator.validate(); setVerifyingSignature(true); } }
From source file:org.icepdf.ri.common.views.annotations.signatures.CertificatePropertiesDialog.java
License:Apache License
/** * Break down DN string into an array used for message format. * Organization: {0}\n Organization Unit :{1}\n Common Name: {2}\n Local: {3}\n State: {4}\n Country:{5}\n Email: {6} *//* w w w .j a va 2s . c o m*/ private Object[] formatDNString(X500Name rdName) { Object[] output = new Object[7]; output[0] = parseRelativeDistinguishedName(rdName, BCStyle.O); output[1] = parseRelativeDistinguishedName(rdName, BCStyle.OU); output[2] = parseRelativeDistinguishedName(rdName, BCStyle.CN); output[3] = parseRelativeDistinguishedName(rdName, BCStyle.L); output[4] = parseRelativeDistinguishedName(rdName, BCStyle.ST); output[5] = parseRelativeDistinguishedName(rdName, BCStyle.C); output[6] = parseRelativeDistinguishedName(rdName, BCStyle.EmailAddress); return output; }
From source file:org.icepdf.ri.common.views.annotations.signatures.SignatureValidationStatus.java
License:Apache License
private void validateSignatureNode(SignatureWidgetAnnotation signatureWidgetAnnotation, SignatureValidator signatureValidator) throws SignatureIntegrityException { SignatureFieldDictionary fieldDictionary = signatureWidgetAnnotation.getFieldDictionary(); if (fieldDictionary != null) { // try and parse out the signer info. X509Certificate certificate = signatureValidator.getSignerCertificate(); X500Principal principal = certificate.getIssuerX500Principal(); X500Name x500name = new X500Name(principal.getName()); if (x500name.getRDNs() != null) { commonName = SignatureUtilities.parseRelativeDistinguishedName(x500name, BCStyle.CN); organization = SignatureUtilities.parseRelativeDistinguishedName(x500name, BCStyle.O); emailAddress = SignatureUtilities.parseRelativeDistinguishedName(x500name, BCStyle.EmailAddress); }/*from w w w . ja v a 2s . c om*/ } }