Java Code Examples for org.bouncycastle.asn1.x509.Extensions

The following examples show how to use org.bouncycastle.asn1.x509.Extensions. These examples are extracted from open source projects. 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 Project: hadoop-ozone   Author: apache   File: BaseApprover.java    License: 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 #2
Source Project: hadoop-ozone   Author: apache   File: CertificateSignRequest.java    License: Apache License 2.0 6 votes vote down vote up
private Extensions createExtensions() throws IOException {
  List<Extension> extensions = new ArrayList<>();

  // Add basic extension
  if(ca) {
    extensions.add(getBasicExtension());
  }

  // Add key usage extension
  extensions.add(getKeyUsageExtension());

  // Add subject alternate name extension
  Optional<Extension> san = getSubjectAltNameExtension();
  if (san.isPresent()) {
    extensions.add(san.get());
  }

  return new Extensions(
      extensions.toArray(new Extension[extensions.size()]));
}
 
Example #3
Source Project: hadoop-ozone   Author: apache   File: TestDefaultProfile.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests that  invalid extensions cause a failure in validation. We will fail
 * if rfc222 type names are added, we also add the extension as both
 * critical and non-critical fashion to verify that the we catch both cases.
 *
 * @throws SCMSecurityException - on Error.
 */

@Test
public void testInvalidExtensionsWithEmail()
    throws IOException, OperatorCreationException {
  Extensions emailExtension = getSANExtension(GeneralName.rfc822Name,
      "[email protected]", false);
  PKCS10CertificationRequest csr = getInvalidCSR(keyPair, emailExtension);
  assertFalse(testApprover.verfiyExtensions(csr));

  emailExtension = getSANExtension(GeneralName.rfc822Name, "bilbo" +
      "@apache.org", true);
  csr = getInvalidCSR(keyPair, emailExtension);
  assertFalse(testApprover.verfiyExtensions(csr));

}
 
Example #4
Source Project: hadoop-ozone   Author: apache   File: TestDefaultProfile.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Assert that if DNS is marked critical our PKI profile will reject it.
 * @throws IOException - on Error.
 * @throws OperatorCreationException - on Error.
 */
@Test
public void testInvalidExtensionsWithCriticalDNS() throws IOException,
    OperatorCreationException {
  Extensions dnsExtension = getSANExtension(GeneralName.dNSName,
      "ozone.hadoop.org",
      true);
  PKCS10CertificationRequest csr = getInvalidCSR(keyPair, dnsExtension);
  assertFalse(testApprover.verfiyExtensions(csr));
  // This tests should pass, hence the assertTrue
  dnsExtension = getSANExtension(GeneralName.dNSName,
      "ozone.hadoop.org",
      false);
  csr = getInvalidCSR(keyPair, dnsExtension);
  assertTrue(testApprover.verfiyExtensions(csr));
}
 
Example #5
Source Project: hadoop-ozone   Author: apache   File: TestDefaultProfile.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Generates an CSR with the extension specified.
 * This function is used to get an Invalid CSR and test that PKI profile
 * rejects these invalid extensions, Hence the function name, by itself it
 * is a well formed CSR, but our PKI profile will treat it as invalid CSR.
 *
 * @param kPair - Key Pair.
 * @return CSR  - PKCS10CertificationRequest
 * @throws OperatorCreationException - on Error.
 */
private PKCS10CertificationRequest getInvalidCSR(KeyPair kPair,
    Extensions extensions) throws OperatorCreationException {
  X500NameBuilder namebuilder =
      new X500NameBuilder(X500Name.getDefaultStyle());
  namebuilder.addRDN(BCStyle.CN, "invalidCert");
  PKCS10CertificationRequestBuilder p10Builder =
      new JcaPKCS10CertificationRequestBuilder(namebuilder.build(),
          keyPair.getPublic());
  p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
      extensions);
  JcaContentSignerBuilder csBuilder =
      new JcaContentSignerBuilder(this.securityConfig.getSignatureAlgo());
  ContentSigner signer = csBuilder.build(keyPair.getPrivate());
  return p10Builder.build(signer);
}
 
Example #6
Source Project: hadoop-ozone   Author: apache   File: TestCertificateSignRequest.java    License: Apache License 2.0 6 votes vote down vote up
private void verifyServiceId(Extensions extensions) {
  GeneralNames gns =
      GeneralNames.fromExtensions(
          extensions, Extension.subjectAlternativeName);
  GeneralName[] names = gns.getNames();
  for(int i=0; i < names.length; i++) {
    if(names[i].getTagNo() == GeneralName.otherName) {
      ASN1Encodable asn1Encodable = names[i].getName();
      Iterator iterator = ((DLSequence) asn1Encodable).iterator();
      while (iterator.hasNext()) {
        Object o = iterator.next();
        if (o instanceof ASN1ObjectIdentifier) {
          String oid = o.toString();
          Assert.assertEquals(oid, "2.16.840.1.113730.3.1.34");
        }
        if (o instanceof DERTaggedObject) {
          String serviceName = ((DERTaggedObject)o).getObject().toString();
          Assert.assertEquals(serviceName, "OzoneMarketingCluster003");
        }
      }
    }
  }
}
 
Example #7
Source Project: netty-4.1.22   Author: tianheframe   File: OcspRequestBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * ATTENTION: The returned {@link OCSPReq} is not re-usable/cacheable! It contains a one-time nonce
 * and CA's will (should) reject subsequent requests that have the same nonce value.
 */
public OCSPReq build() throws OCSPException, IOException, CertificateEncodingException {
    SecureRandom generator = checkNotNull(this.generator, "generator");
    DigestCalculator calculator = checkNotNull(this.calculator, "calculator");
    X509Certificate certificate = checkNotNull(this.certificate, "certificate");
    X509Certificate issuer = checkNotNull(this.issuer, "issuer");

    BigInteger serial = certificate.getSerialNumber();

    CertificateID certId = new CertificateID(calculator,
            new X509CertificateHolder(issuer.getEncoded()), serial);

    OCSPReqBuilder builder = new OCSPReqBuilder();
    builder.addRequest(certId);

    byte[] nonce = new byte[8];
    generator.nextBytes(nonce);

    Extension[] extensions = new Extension[] {
            new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false,
                    new DEROctetString(nonce)) };

    builder.setRequestExtensions(new Extensions(extensions));

    return builder.build();
}
 
Example #8
Source Project: localization_nifi   Author: wangrenlei   File: TlsHelperTest.java    License: 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 #9
Source Project: localization_nifi   Author: wangrenlei   File: CertificateUtils.java    License: 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 #10
Source Project: nifi-registry   Author: apache   File: CertificateUtils.java    License: 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 #11
Source Project: itext2   Author: albfernandez   File: OcspClientBouncyCastle.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Generates an OCSP request using BouncyCastle.
 * @param issuerCert	certificate of the issues
 * @param serialNumber	serial number
 * @return	an OCSP request
 * @throws OCSPException
 * @throws IOException
 */
private static OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber) throws OCSPException, IOException, OperatorException, CertificateEncodingException {
    //Add provider BC
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    
    JcaDigestCalculatorProviderBuilder digestCalculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder();
    DigestCalculatorProvider digestCalculatorProvider = digestCalculatorProviderBuilder.build();
    DigestCalculator digestCalculator = digestCalculatorProvider.get(CertificateID.HASH_SHA1);
    // Generate the id for the certificate we are looking for
    CertificateID id = new CertificateID(digestCalculator, new JcaX509CertificateHolder(issuerCert), serialNumber);
    
    // basic request generation with nonce
    OCSPReqBuilder gen = new OCSPReqBuilder();
    
    gen.addRequest(id);
    
    // create details for nonce extension
    Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(new DEROctetString(PdfEncryption.createDocumentId()).getEncoded()));
    gen.setRequestExtensions(new Extensions(new Extension[]{ext}));
    
    return gen.build();
}
 
Example #12
Source Project: certificate-transparency-java   Author: google   File: LogSignatureVerifier.java    License: Apache License 2.0 6 votes vote down vote up
private List<Extension> getExtensionsWithoutPoisonAndSCT(
    Extensions extensions, Extension replacementX509authorityKeyIdentifier) {
  ASN1ObjectIdentifier[] extensionsOidsArray = extensions.getExtensionOIDs();
  Iterator<ASN1ObjectIdentifier> extensionsOids = Arrays.asList(extensionsOidsArray).iterator();

  // Order is important, which is why a list is used.
  ArrayList<Extension> outputExtensions = new ArrayList<Extension>();
  while (extensionsOids.hasNext()) {
    ASN1ObjectIdentifier extn = extensionsOids.next();
    String extnId = extn.getId();
    if (extnId.equals(CTConstants.POISON_EXTENSION_OID)) {
      // Do nothing - skip copying this extension
    } else if (extnId.equals(CTConstants.SCT_CERTIFICATE_OID)) {
      // Do nothing - skip copying this extension
    } else if ((extnId.equals(X509_AUTHORITY_KEY_IDENTIFIER))
        && (replacementX509authorityKeyIdentifier != null)) {
      // Use the real issuer's authority key identifier, since it's present.
      outputExtensions.add(replacementX509authorityKeyIdentifier);
    } else {
      // Copy the extension as-is.
      outputExtensions.add(extensions.getExtension(extn));
    }
  }
  return outputExtensions;
}
 
Example #13
Source Project: athenz   Author: yahoo   File: Crypto.java    License: 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 #14
Source Project: dss   Author: esig   File: OnlineOCSPSource.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
private byte[] buildOCSPRequest(final CertificateID certId, BigInteger nonce) throws DSSException {
	try {
		final OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder();
		ocspReqBuilder.addRequest(certId);
		/*
		 * The nonce extension is used to bind a request to a response to
		 * prevent replay attacks. RFC 6960 (OCSP) section 4.1.2 such
		 * extensions SHOULD NOT be flagged as critical
		 */
		if (nonce != null) {
			DEROctetString encodedNonceValue = new DEROctetString(
					new DEROctetString(nonce.toByteArray()).getEncoded());
			Extension extension = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, encodedNonceValue);
			Extensions extensions = new Extensions(extension);
			ocspReqBuilder.setRequestExtensions(extensions);
		}
		final OCSPReq ocspReq = ocspReqBuilder.build();
		final byte[] ocspReqData = ocspReq.getEncoded();
		return ocspReqData;
	} catch (OCSPException | IOException e) {
		throw new DSSException("Cannot build OCSP Request", e);
	}
}
 
Example #15
Source Project: xipki   Author: xipki   File: ExtensionsChecker.java    License: Apache License 2.0 6 votes vote down vote up
private void checkExtnNameConstraints(StringBuilder failureMsg, byte[] extensionValue,
    Extensions requestedExtns, ExtensionControl extControl) {
  NameConstraints conf = nameConstraints;
  if (conf == null) {
    checkConstantExtnValue(Extension.nameConstraints, failureMsg, extensionValue, requestedExtns,
        extControl);
    return;
  }

  org.bouncycastle.asn1.x509.NameConstraints tmpNameConstraints =
      org.bouncycastle.asn1.x509.NameConstraints.getInstance(extensionValue);

  checkExtnNameConstraintsSubtrees(failureMsg, "PermittedSubtrees",
      tmpNameConstraints.getPermittedSubtrees(),  conf.getPermittedSubtrees());
  checkExtnNameConstraintsSubtrees(failureMsg, "ExcludedSubtrees",
      tmpNameConstraints.getExcludedSubtrees(), conf.getExcludedSubtrees());
}
 
Example #16
Source Project: xipki   Author: xipki   File: SelfSignedCertBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private static void addExtensions(X509v3CertificateBuilder certBuilder,
    IdentifiedCertprofile profile, X500Name requestedSubject, X500Name grantedSubject,
    Extensions extensions, SubjectPublicKeyInfo requestedPublicKeyInfo,
    PublicCaInfo publicCaInfo, Date notBefore, Date notAfter)
    throws CertprofileException, IOException, BadCertTemplateException {
  ExtensionValues extensionTuples = profile.getExtensions(requestedSubject, grantedSubject,
      extensions, requestedPublicKeyInfo, publicCaInfo, null, notBefore, notAfter);
  if (extensionTuples == null) {
    return;
  }

  for (ASN1ObjectIdentifier extType : extensionTuples.getExtensionTypes()) {
    ExtensionValue extValue = extensionTuples.getExtensionValue(extType);
    certBuilder.addExtension(extType, extValue.isCritical(), extValue.getValue());
  }
}
 
Example #17
Source Project: nifi   Author: apache   File: TlsHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static Extensions createDomainAlternativeNamesExtensions(List<String> domainAlternativeNames, String requestedDn) throws IOException {
    List<GeneralName> namesList = new ArrayList<>();

    try {
        final String cn = IETFUtils.valueToString(new X500Name(requestedDn).getRDNs(BCStyle.CN)[0].getFirst().getValue());
        namesList.add(new GeneralName(GeneralName.dNSName, cn));
    } catch (Exception e) {
        throw new IOException("Failed to extract CN from request DN: " + requestedDn, e);
    }

    if (domainAlternativeNames != null) {
        for (String alternativeName : domainAlternativeNames) {
             namesList.add(new GeneralName(IPAddress.isValid(alternativeName) ? GeneralName.iPAddress : GeneralName.dNSName, alternativeName));
         }
    }

    GeneralNames subjectAltNames = new GeneralNames(namesList.toArray(new GeneralName[]{}));
    ExtensionsGenerator extGen = new ExtensionsGenerator();
    extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
    return extGen.generate();
}
 
Example #18
Source Project: nifi   Author: apache   File: TlsHelperTest.java    License: 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 #19
Source Project: nifi   Author: apache   File: CertificateUtils.java    License: 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 #20
Source Project: hadoop-ozone   Author: apache   File: BaseApprover.java    License: 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 #21
Source Project: hadoop-ozone   Author: apache   File: BaseApprover.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the Extension decoded into a Java Collection.
 * @param extensions - A set of Extensions in ASN.1.
 * @return List of Decoded Extensions.
 */
List<Extension> getIndividualExtension(Extensions extensions) {
  Objects.requireNonNull(extensions);
  List<Extension> extenList = new ArrayList<>();
  for (ASN1ObjectIdentifier id : extensions.getExtensionOIDs()) {
    if (id != null) {
      Extension ext = extensions.getExtension(id);
      if (ext != null) {
        extenList.add(ext);
      }
    }
  }
  return extenList;
}
 
Example #22
Source Project: hadoop-ozone   Author: apache   File: CertificateSignRequest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Private Ctor for CSR.
 *
 * @param subject - Subject
 * @param scmID - SCM ID
 * @param clusterID - Cluster ID
 * @param keyPair - KeyPair
 * @param config - SCM Config
 * @param extensions - CSR extensions
 */
private CertificateSignRequest(String subject, String scmID, String clusterID,
                               KeyPair keyPair, SecurityConfig config,
                               Extensions extensions) {
  this.subject = subject;
  this.clusterID = clusterID;
  this.scmID = scmID;
  this.keyPair = keyPair;
  this.config = config;
  this.extensions = extensions;
}
 
Example #23
Source Project: hadoop-ozone   Author: apache   File: SecurityUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static Extensions getPkcs9Extensions(PKCS10CertificationRequest csr)
    throws CertificateException {
  ASN1Set pkcs9ExtReq = getPkcs9ExtRequest(csr);
  Object extReqElement = pkcs9ExtReq.getObjects().nextElement();
  if (extReqElement instanceof Extensions) {
    return (Extensions) extReqElement;
  } else {
    if (extReqElement instanceof ASN1Sequence) {
      return Extensions.getInstance((ASN1Sequence) extReqElement);
    } else {
      throw new CertificateException("Unknown element type :" + extReqElement
          .getClass().getSimpleName());
    }
  }
}
 
Example #24
Source Project: hadoop-ozone   Author: apache   File: TestDefaultProfile.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Same test for URI.
 * @throws IOException - On Error.
 * @throws OperatorCreationException- on Error.
 */
@Test
public void testInvalidExtensionsWithURI() throws IOException,
    OperatorCreationException {
  Extensions oExtension = getSANExtension(
      GeneralName.uniformResourceIdentifier, "s3g.ozone.org", false);
  PKCS10CertificationRequest csr = getInvalidCSR(keyPair, oExtension);
  assertFalse(testApprover.verfiyExtensions(csr));
  oExtension = getSANExtension(GeneralName.uniformResourceIdentifier,
      "s3g.ozone.org", false);
  csr = getInvalidCSR(keyPair, oExtension);
  assertFalse(testApprover.verfiyExtensions(csr));
}
 
Example #25
Source Project: hadoop-ozone   Author: apache   File: TestDefaultProfile.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Verify that valid Extended Key usage works as expected.
 * @throws IOException - on Error.
 * @throws OperatorCreationException - on Error.
 */
@Test
public void testValidExtendedKeyUsage() throws IOException,
    OperatorCreationException {
  Extensions extendedExtension =
      getKeyUsageExtension(KeyPurposeId.id_kp_clientAuth, false);
  PKCS10CertificationRequest csr = getInvalidCSR(keyPair, extendedExtension);
  assertTrue(testApprover.verfiyExtensions(csr));

  extendedExtension = getKeyUsageExtension(KeyPurposeId.id_kp_serverAuth,
      false);
  csr = getInvalidCSR(keyPair, extendedExtension);
  assertTrue(testApprover.verfiyExtensions(csr));
}
 
Example #26
Source Project: hadoop-ozone   Author: apache   File: TestDefaultProfile.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Verify that Invalid Extended Key usage works as expected, that is rejected.
 * @throws IOException - on Error.
 * @throws OperatorCreationException - on Error.
 */
@Test
public void testInValidExtendedKeyUsage() throws IOException,
    OperatorCreationException {
  Extensions extendedExtension =
      getKeyUsageExtension(KeyPurposeId.id_kp_clientAuth, true);
  PKCS10CertificationRequest csr = getInvalidCSR(keyPair, extendedExtension);
  assertFalse(testApprover.verfiyExtensions(csr));

  extendedExtension = getKeyUsageExtension(KeyPurposeId.id_kp_OCSPSigning,
      false);
  csr = getInvalidCSR(keyPair, extendedExtension);
  assertFalse(testApprover.verfiyExtensions(csr));
}
 
Example #27
Source Project: hadoop-ozone   Author: apache   File: TestDefaultProfile.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generate an Extension with rfc822Name.
 * @param extensionCode - Extension Code.
 * @param value  - email to be added to the certificate
 * @param critical - boolean value that marks the extension as critical.
 * @return - An Extension list with email address.
 * @throws IOException
 */
private Extensions getSANExtension(int extensionCode, String value,
    boolean critical) throws IOException {
  GeneralName extn = new GeneralName(extensionCode,
      value);
  ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
  extensionsGenerator.addExtension(Extension.subjectAlternativeName, critical,
      new GeneralNames(extn));
  return extensionsGenerator.generate();
}
 
Example #28
Source Project: hadoop-ozone   Author: apache   File: TestDefaultProfile.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a extension with Extended Key usage.
 * @param purposeId - Usage that we want to encode.
 * @param critical -  makes the extension critical.
 * @return Extensions.
 */
private Extensions getKeyUsageExtension(KeyPurposeId purposeId,
    boolean critical) throws IOException {
  ExtendedKeyUsage extendedKeyUsage = new ExtendedKeyUsage(purposeId);
  ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
  extensionsGenerator.addExtension(
      Extension.extendedKeyUsage, critical, extendedKeyUsage);
  return extensionsGenerator.generate();
}
 
Example #29
Source Project: localization_nifi   Author: wangrenlei   File: TlsHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static Extensions createDomainAlternativeNamesExtensions(String domainAlternativeNames) throws IOException {
    List<GeneralName> namesList = new ArrayList<>();
    for(String alternativeName : domainAlternativeNames.split(",")) {
        namesList.add(new GeneralName(GeneralName.dNSName, alternativeName));
    }

    GeneralNames subjectAltNames = new GeneralNames(namesList.toArray(new GeneralName [] {}));
    ExtensionsGenerator extGen = new ExtensionsGenerator();
    extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
    return extGen.generate();
}
 
Example #30
Source Project: localization_nifi   Author: wangrenlei   File: CertificateUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generates an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair}
 *
 * @param dn the distinguished name to use
 * @param publicKey the public key to issue the certificate to
 * @param extensions extensions extracted from the CSR
 * @param issuer the issuer's certificate
 * @param issuerKeyPair the issuer's keypair
 * @param signingAlgorithm the signing algorithm to use
 * @param days the number of days it should be valid for
 * @return an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair}
 * @throws CertificateException if there is an error issuing the certificate
 */
public static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, Extensions extensions, X509Certificate issuer, KeyPair issuerKeyPair, String signingAlgorithm, int days)
        throws CertificateException {
    try {
        ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(issuerKeyPair.getPrivate());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
        Date startDate = new Date();
        Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(days));

        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(
                reverseX500Name(new X500Name(issuer.getSubjectX500Principal().getName())),
                getUniqueSerialNumber(),
                startDate, endDate,
                reverseX500Name(new X500Name(dn)),
                subPubKeyInfo);

        certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKey));

        certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(issuerKeyPair.getPublic()));
        // Set certificate extensions
        // (1) digitalSignature extension
        certBuilder.addExtension(Extension.keyUsage, true,
                new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation));

        certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));

        // (2) extendedKeyUsage extension
        certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth}));

        // (3) subjectAlternativeName
        if(extensions != null && extensions.getExtension(Extension.subjectAlternativeName) != null) {
            certBuilder.addExtension(Extension.subjectAlternativeName, false, extensions.getExtensionParsedValue(Extension.subjectAlternativeName));
        }

        X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
        return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder);
    } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) {
        throw new CertificateException(e);
    }
}