org.bouncycastle.asn1.pkcs.Attribute Java Examples

The following examples show how to use org.bouncycastle.asn1.pkcs.Attribute. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CertificateUtils.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Extract extensions from CSR object
 */
public static Extensions getExtensionsFromCSR(JcaPKCS10CertificationRequest csr) {
    Attribute[] attributess = csr.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    for (Attribute attribute : attributess) {
        ASN1Set attValue = attribute.getAttrValues();
        if (attValue != null) {
            ASN1Encodable extension = attValue.getObjectAt(0);
            if (extension instanceof Extensions) {
                return (Extensions) extension;
            } else if (extension instanceof DERSequence) {
                return Extensions.getInstance(extension);
            }
        }
    }
    return null;
}
 
Example #2
Source File: BaseApprover.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * This function verifies all extensions in the certificate.
 *
 * @param request - CSR
 * @return - true if the extensions are acceptable by the profile, false
 * otherwise.
 */
boolean verfiyExtensions(PKCS10CertificationRequest request) {
  Objects.requireNonNull(request);
  /*
   * Inside a CSR we have
   *  1. A list of Attributes
   *    2. Inside each attribute a list of extensions.
   *      3. We need to walk thru the each extension and verify they
   *      are expected and we can put that into a certificate.
   */

  for (Attribute attr : getAttributes(request)) {
    for (Extensions extensionsList : getExtensionsList(attr)) {
      for (Extension extension : getIndividualExtension(extensionsList)) {
        if (!profile.validateExtension(extension)) {
          LOG.error("Failed to verify extension. {}",
              extension.getExtnId().getId());
          return false;
        }
      }
    }
  }
  return true;
}
 
Example #3
Source File: TlsHelperTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
private List<String> extractSanFromCsr(JcaPKCS10CertificationRequest csr) {
    List<String> sans = new ArrayList<>();
    Attribute[] certAttributes = csr.getAttributes();
    for (Attribute attribute : certAttributes) {
        if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
            GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            GeneralName[] names = gns.getNames();
            for (GeneralName name : names) {
                logger.info("Type: " + name.getTagNo() + " | Name: " + name.getName());
                String title = "";
                if (name.getTagNo() == GeneralName.dNSName) {
                    title = "DNS";
                } else if (name.getTagNo() == GeneralName.iPAddress) {
                    title = "IP Address";
                    // name.toASN1Primitive();
                } else if (name.getTagNo() == GeneralName.otherName) {
                    title = "Other Name";
                }
                sans.add(title + ": " + name.getName());
            }
        }
    }

    return sans;
}
 
Example #4
Source File: TlsHelperTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private List<String> extractSanFromCsr(JcaPKCS10CertificationRequest csr) {
    List<String> sans = new ArrayList<>();
    Attribute[] certAttributes = csr.getAttributes();
    for (Attribute attribute : certAttributes) {
        if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
            GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            GeneralName[] names = gns.getNames();
            for (GeneralName name : names) {
                logger.info("Type: " + name.getTagNo() + " | Name: " + name.getName());
                String title = "";
                if (name.getTagNo() == GeneralName.dNSName) {
                    title = "DNS";
                } else if (name.getTagNo() == GeneralName.iPAddress) {
                    title = "IP Address";
                    // name.toASN1Primitive();
                } else if (name.getTagNo() == GeneralName.otherName) {
                    title = "Other Name";
                }
                sans.add(title + ": " + name.getName());
            }
        }
    }

    return sans;
}
 
Example #5
Source File: CertificateUtils.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Extract extensions from CSR object
 */
public static Extensions getExtensionsFromCSR(JcaPKCS10CertificationRequest csr) {
    Attribute[] attributess = csr.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    for (Attribute attribute : attributess) {
        ASN1Set attValue = attribute.getAttrValues();
        if (attValue != null) {
            ASN1Encodable extension = attValue.getObjectAt(0);
            if (extension instanceof Extensions) {
                return (Extensions) extension;
            } else if (extension instanceof DERSequence) {
                return Extensions.getInstance(extension);
            }
        }
    }
    return null;
}
 
Example #6
Source File: CertificateUtils.java    From nifi-registry with Apache License 2.0 6 votes vote down vote up
/**
 * Extract extensions from CSR object
 */
public static Extensions getExtensionsFromCSR(JcaPKCS10CertificationRequest csr) {
    Attribute[] attributess = csr.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    for (Attribute attribute : attributess) {
        ASN1Set attValue = attribute.getAttrValues();
        if (attValue != null) {
            ASN1Encodable extension = attValue.getObjectAt(0);
            if (extension instanceof Extensions) {
                return (Extensions) extension;
            } else if (extension instanceof DERSequence) {
                return Extensions.getInstance(extension);
            }
        }
    }
    return null;
}
 
Example #7
Source File: Crypto.java    From athenz with Apache License 2.0 6 votes vote down vote up
public static List<String> extractX509CSRIPAddresses(PKCS10CertificationRequest certReq) {

        List<String> ipAddresses = new ArrayList<>();
        Attribute[] attributes = certReq.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
        for (Attribute attribute : attributes) {
            for (ASN1Encodable value : attribute.getAttributeValues()) {
                Extensions extensions = Extensions.getInstance(value);
                GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
                ///CLOVER:OFF
                if (gns == null) {
                    continue;
                }
                ///CLOVER:ON
                for (GeneralName name : gns.getNames()) {
                    if (name.getTagNo() == GeneralName.iPAddress) {
                        try {
                            InetAddress addr = InetAddress.getByAddress(((DEROctetString) name.getName()).getOctets());
                            ipAddresses.add(addr.getHostAddress());
                        } catch (UnknownHostException ignored) {
                        }
                    }
                }
            }
        }
        return ipAddresses;
    }
 
Example #8
Source File: DialogHelper.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
private static void populateTextField(Attribute[] attrs, JTextField textField, ASN1ObjectIdentifier pkcs9Attr) {
	if (attrs != null) {
		for (Attribute attribute : attrs) {

			ASN1ObjectIdentifier attributeOid = attribute.getAttrType();

			if (attributeOid.equals(pkcs9Attr)) {
				ASN1Encodable challenge = attribute.getAttributeValues()[0];

				// data type can be one of IA5String or UTF8String
				if (challenge instanceof DERPrintableString) {
					textField.setText(((DERPrintableString) challenge).getString());
				} else if (challenge instanceof DERUTF8String) {
					textField.setText(((DERUTF8String) challenge).getString());
				}
				textField.setCaretPosition(0);
			}
		}
	}
}
 
Example #9
Source File: BaseApprover.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a list of Extensions encoded in a given attribute.
 *
 * @param attribute - Attribute to decode.
 * @return - List of Extensions.
 */
List<Extensions> getExtensionsList(Attribute attribute) {
  Objects.requireNonNull(attribute);
  List<Extensions> extensionsList = new ArrayList<>();
  for (ASN1Encodable value : attribute.getAttributeValues()) {
    if(value != null) {
      Extensions extensions = Extensions.getInstance(value);
      extensionsList.add(extensions);
    }
  }
  return extensionsList;
}
 
Example #10
Source File: CaUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static String getChallengePassword(CertificationRequestInfo csr) {
  Args.notNull(csr, "csr");
  ASN1Set attrs = csr.getAttributes();
  for (int i = 0; i < attrs.size(); i++) {
    Attribute attr = Attribute.getInstance(attrs.getObjectAt(i));
    if (PKCSObjectIdentifiers.pkcs_9_at_challengePassword.equals(attr.getAttrType())) {
      ASN1String str = (ASN1String) attr.getAttributeValues()[0];
      return str.getString();
    }
  }
  return null;
}
 
Example #11
Source File: CaUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static Extensions getExtensions(CertificationRequestInfo csr) {
  Args.notNull(csr, "csr");
  ASN1Set attrs = csr.getAttributes();
  for (int i = 0; i < attrs.size(); i++) {
    Attribute attr = Attribute.getInstance(attrs.getObjectAt(i));
    if (PKCSObjectIdentifiers.pkcs_9_at_extensionRequest.equals(attr.getAttrType())) {
      return Extensions.getInstance(attr.getAttributeValues()[0]);
    }
  }
  return null;
}
 
Example #12
Source File: ScepResponder.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static String getChallengePassword(CertificationRequestInfo csr) {
  ASN1Set attrs = csr.getAttributes();
  for (int i = 0; i < attrs.size(); i++) {
    Attribute attr = Attribute.getInstance(attrs.getObjectAt(i));
    if (PKCSObjectIdentifiers.pkcs_9_at_challengePassword.equals(attr.getAttrType())) {
      ASN1String str = (ASN1String) attr.getAttributeValues()[0];
      return str.getString();
    }
  }
  return null;
}
 
Example #13
Source File: DSignCsr.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
private void populatePkcs10CsrDetails() throws CryptoException {
	jtfCsrFormat.setText(res.getString("DSignCsr.jtfCsrFormat.Pkcs10.text"));
	jtfCsrFormat.setCaretPosition(0);

	jdnCsrSubject.setDistinguishedName(pkcs10Csr.getSubject());

	try {
		csrPublicKey = new JcaPKCS10CertificationRequest(pkcs10Csr).getPublicKey();
	} catch (GeneralSecurityException ex) {
		throw new CryptoException(res.getString("DSignCsr.NoGetCsrPublicKey.message"), ex);
	}

	populatePublicKey();

	String sigAlgId = pkcs10Csr.getSignatureAlgorithm().getAlgorithm().getId();
	SignatureType sigAlg = SignatureType.resolveOid(sigAlgId);

	if (sigAlg != null) {
		jtfCsrSignatureAlgorithm.setText(sigAlg.friendly());
	} else {
		jtfCsrSignatureAlgorithm.setText(sigAlgId);
	}

	jtfCsrSignatureAlgorithm.setCaretPosition(0);

	DialogHelper.populatePkcs10Challenge(pkcs10Csr.getAttributes(), jtfCsrChallenge);

	Attribute[] extReqAttr = pkcs10Csr.getAttributes(pkcs_9_at_extensionRequest);
	if (extReqAttr != null && extReqAttr.length > 0) {
		jbCsrExtensions.setEnabled(true);
		jbTransferExtensions.setEnabled(true);
	} else {
		jbCsrExtensions.setEnabled(false);
		jbTransferExtensions.setEnabled(false);
	}

}
 
Example #14
Source File: DViewCsr.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
private void populatePkcs10CsrDetails() throws CryptoException {
	jtfFormat.setText(res.getString("DViewCsr.jtfFormat.Pkcs10.text"));
	jtfFormat.setCaretPosition(0);

	jdnSubject.setDistinguishedName(pkcs10Csr.getSubject());

	jbPem.setEnabled(true);
	jbAsn1.setEnabled(true);

	Attribute[] extReqAttr = pkcs10Csr.getAttributes(pkcs_9_at_extensionRequest);
	if (extReqAttr != null && extReqAttr.length > 0) {
		jbExtensions.setEnabled(true);
	} else {
		jbExtensions.setEnabled(false);
	}

	DialogHelper.populatePkcs10Challenge(pkcs10Csr.getAttributes(), jtfChallenge);
	DialogHelper.populatePkcs10UnstructuredName(pkcs10Csr.getAttributes(), jtfUnstructuredName);

	populatePublicKey(getPkcs10PublicKey());

	String sigAlgId = pkcs10Csr.getSignatureAlgorithm().getAlgorithm().getId();
	SignatureType sigAlg = SignatureType.resolveOid(sigAlgId);

	if (sigAlg != null) {
		jtfSignatureAlgorithm.setText(sigAlg.friendly());
	} else {
		jtfSignatureAlgorithm.setText(sigAlgId);
	}

	jtfSignatureAlgorithm.setCaretPosition(0);
}
 
Example #15
Source File: Pkcs10Util.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Extract sequence with extensions from CSR
 *
 * @param pkcs10Csr The CSR
 * @return Extensions from that CSR (if any)
 */
public static X509ExtensionSet getExtensions(PKCS10CertificationRequest pkcs10Csr) {
	Attribute[] attributes = pkcs10Csr.getAttributes(pkcs_9_at_extensionRequest);
	X509ExtensionSet x509ExtensionSet = new X509ExtensionSet();
	if ((attributes != null) && (attributes.length > 0)) {
		ASN1Encodable[] attributeValues = attributes[0].getAttributeValues();
		if (attributeValues.length > 0) {
			ASN1Sequence asn1Sequence = ASN1Sequence.getInstance(attributeValues[0]);
			x509ExtensionSet = new X509ExtensionSet(asn1Sequence);
		}
	}
	return x509ExtensionSet;
}
 
Example #16
Source File: CertificateGenerator.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
private ASN1Encodable getChallengePassword(Attribute[] attributes) {

        for (Attribute attribute : attributes) {
            if (PKCSObjectIdentifiers.pkcs_9_at_challengePassword.equals(attribute.getAttrType())) {
                if (attribute.getAttrValues() != null && attribute.getAttrValues().size() > 0) {
                    return attribute.getAttrValues().getObjectAt(0);
                }
            }
        }

        return null;
    }
 
Example #17
Source File: Crypto.java    From athenz with Apache License 2.0 5 votes vote down vote up
private static List<String> extractX509CSRSANField(PKCS10CertificationRequest certReq, int tagNo) {

        List<String> values = new ArrayList<>();
        Attribute[] attributes = certReq.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
        for (Attribute attribute : attributes) {
            for (ASN1Encodable value : attribute.getAttributeValues()) {
                Extensions extensions = Extensions.getInstance(value);
                GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
                ///CLOVER:OFF
                if (gns == null) {
                    continue;
                }
                ///CLOVER:ON
                for (GeneralName name : gns.getNames()) {

                    // GeneralName ::= CHOICE {
                    //     otherName                       [0]     OtherName,
                    //     rfc822Name                      [1]     IA5String,
                    //     dNSName                         [2]     IA5String,
                    //     x400Address                     [3]     ORAddress,
                    //     directoryName                   [4]     Name,
                    //     ediPartyName                    [5]     EDIPartyName,
                    //     uniformResourceIdentifier       [6]     IA5String,
                    //     iPAddress                       [7]     OCTET STRING,
                    //     registeredID                    [8]     OBJECT IDENTIFIER}

                    if (name.getTagNo() == tagNo) {
                        values.add(((DERIA5String) name.getName()).getString());
                    }
                }
            }
        }
        return values;
    }
 
Example #18
Source File: SecurityUtil.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
public static ASN1Set getPkcs9ExtRequest(PKCS10CertificationRequest csr)
    throws CertificateException {
  for (Attribute attr : csr.getAttributes()) {
    ASN1ObjectIdentifier oid = attr.getAttrType();
    if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
      return attr.getAttrValues();
    }
  }
  throw new CertificateException("No PKCS#9 extension found in CSR");
}
 
Example #19
Source File: CSRParser.java    From acme_client with MIT License 4 votes vote down vote up
public static Set<String> getDomains(byte[] csrBytes) throws IOException {

        Set<String> domains = new HashSet<>();

        JcaPKCS10CertificationRequest p10Object = new JcaPKCS10CertificationRequest(csrBytes);

        for(RDN rdn : p10Object.getSubject().getRDNs()){
            String id = rdn.getFirst().getType().getId();
            if(COMMON_NAME.equals(id)){
                String commonName = rdn.getFirst().getValue().toString();
                domains.add(commonName);
            }
        }

        for(Attribute attribute : p10Object.getAttributes(EXTENSION_REQUEST_IDENTIFIER)){

            Iterator<ASN1Encodable> attrValIt = attribute.getAttrValues().iterator();
            while (attrValIt.hasNext()){

                Iterator<ASN1Encodable> seqIt = ((DERSequence) attrValIt.next()).iterator();

                while (seqIt.hasNext()){
                    DERSequence seq = (DERSequence) seqIt.next();
                    ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) seq.getObjectAt(0);
                    if (SUBJECT_ALTERNATIVE_NAME.equals(oid.getId())) {
                        DEROctetString str = (DEROctetString) seq.getObjectAt(1);

                        GeneralNames names = GeneralNames.getInstance(str.getOctets());

                        for(String domain : names.toString().split("\\s+")) {
                            if(!domain.endsWith(":")){
                                domains.add(domain);
                            }
                        }

                    }
                }

            }

        }

        return domains;
    }
 
Example #20
Source File: RootCAProvider.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
private Certificate generateCertificateUsingCsr(final String csr, final List<String> names, final List<String> ips, final int validityDays) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, CertificateException, SignatureException, IOException, OperatorCreationException {
    final List<String> dnsNames = new ArrayList<>();
    final List<String> ipAddresses = new ArrayList<>();

    if (names != null) {
        dnsNames.addAll(names);
    }
    if (ips != null) {
        ipAddresses.addAll(ips);
    }

    PemObject pemObject = null;

    try {
        final PemReader pemReader = new PemReader(new StringReader(csr));
        pemObject = pemReader.readPemObject();
    } catch (IOException e) {
        LOG.error("Failed to read provided CSR string as a PEM object", e);
    }

    if (pemObject == null) {
        throw new CloudRuntimeException("Unable to read/process CSR: " + csr);
    }

    final JcaPKCS10CertificationRequest request = new JcaPKCS10CertificationRequest(pemObject.getContent());
    final String subject = request.getSubject().toString();
    for (final Attribute attribute : request.getAttributes()) {
        if (attribute == null) {
            continue;
        }
        if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            final Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
            final GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            if (gns != null && gns.getNames() != null && gns.getNames().length > 0) {
                for (final GeneralName name : gns.getNames()) {
                    if (name.getTagNo() == GeneralName.dNSName) {
                        dnsNames.add(name.getName().toString());
                    }
                    if (name.getTagNo() == GeneralName.iPAddress) {
                        final InetAddress address = InetAddress.getByAddress(DatatypeConverter.parseHexBinary(name.getName().toString().substring(1)));
                        ipAddresses.add(address.toString().replace("/", ""));
                    }
                }
            }
        }
    }

    final X509Certificate clientCertificate = CertUtils.generateV3Certificate(
            caCertificate, caKeyPair, request.getPublicKey(),
            subject, CAManager.CertSignatureAlgorithm.value(),
            validityDays, dnsNames, ipAddresses);
    return new Certificate(clientCertificate, null, Collections.singletonList(caCertificate));
}
 
Example #21
Source File: DialogHelper.java    From keystore-explorer with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Populates a JTextField with PKCS#10 challenge
 *
 * @param attributes
 * 				Attributes from CSR
 * @param textField
 * 				Text field to be populated with the challenge
 */
public static void populatePkcs10Challenge(Attribute[] attributes, JTextField textField) {

	ASN1ObjectIdentifier pkcs9AtChallengepassword = PKCSObjectIdentifiers.pkcs_9_at_challengePassword;
	populateTextField(attributes, textField, pkcs9AtChallengepassword);
}
 
Example #22
Source File: DialogHelper.java    From keystore-explorer with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Populates a JTextField with PKCS#10/#9 unstructuredName
 *
 * @param attributes
 *              Attributes from CSR
 * @param textField
 *              Text field to be populated with the unstructuredName
 */
public static void populatePkcs10UnstructuredName(Attribute[] attributes, JTextField textField) {

	ASN1ObjectIdentifier pkcs9UnstructureName = PKCSObjectIdentifiers.pkcs_9_at_unstructuredName;
	populateTextField(attributes, textField, pkcs9UnstructureName);
}
 
Example #23
Source File: BaseApprover.java    From hadoop-ozone with Apache License 2.0 2 votes vote down vote up
/**
 * Returns the Attribute array that encodes extensions.
 *
 * @param request - Certificate Request
 * @return - An Array of Attributes that encode various extensions requested
 * in this certificate.
 */
Attribute[] getAttributes(PKCS10CertificationRequest request) {
  Objects.requireNonNull(request);
  return
      request.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
}