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

The following examples show how to use org.bouncycastle.asn1.x509.Extension. 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: dss   Source 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 2
Source Project: dss   Source File: DSSASN1Utils.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * This method returns SKI bytes from certificate.
 *
 * @param certificateToken
 *            {@code CertificateToken}
 * @param computeIfMissing
 *            if the extension is missing and computeIfMissing = true, it will compute the SKI value from the Public
 *            Key
 * @return ski bytes from the given certificate
 */
public static byte[] getSki(final CertificateToken certificateToken, boolean computeIfMissing) {
	try {
		byte[] extensionValue = certificateToken.getCertificate().getExtensionValue(Extension.subjectKeyIdentifier.getId());
		if (Utils.isArrayNotEmpty(extensionValue)) {
			ASN1Primitive extension = JcaX509ExtensionUtils.parseExtensionValue(extensionValue);
			SubjectKeyIdentifier skiBC = SubjectKeyIdentifier.getInstance(extension);
			return skiBC.getKeyIdentifier();
		} else if (computeIfMissing) {
			// If extension not present, we compute it from the certificate public key
			return computeSkiFromCert(certificateToken);
		}
		return null;
	} catch (IOException e) {
		throw new DSSException(e);
	}
}
 
Example 3
Source Project: hadoop-ozone   Source File: DefaultProfile.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean validateExtension(Extension extension) {
  Preconditions.checkNotNull(extension, "Extension cannot be null");

  if (!isSupportedExtension(extension)) {
    LOG.error("Unsupported Extension found: {} ",
        extension.getExtnId().getId());
    return false;
  }

  BiFunction<Extension, PKIProfile, Boolean> func =
      EXTENSIONS_MAP.get(extension.getExtnId());

  if (func != null) {
    return func.apply(extension, this);
  }
  return false;
}
 
Example 4
Source Project: hadoop-ozone   Source File: CertificateSignRequest.java    License: Apache License 2.0 6 votes vote down vote up
private Extension getKeyUsageExtension() throws IOException {
  int keyUsageFlag = KeyUsage.keyAgreement;
  if(digitalEncryption){
    keyUsageFlag |= KeyUsage.keyEncipherment | KeyUsage.dataEncipherment;
  }
  if(digitalSignature) {
    keyUsageFlag |= KeyUsage.digitalSignature;
  }

  if (ca) {
    keyUsageFlag |= KeyUsage.keyCertSign | KeyUsage.cRLSign;
  }
  KeyUsage keyUsage = new KeyUsage(keyUsageFlag);
  return new Extension(Extension.keyUsage, true,
      new DEROctetString(keyUsage));
}
 
Example 5
Source Project: nifi   Source 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 6
Source Project: dss   Source File: OnlineOCSPSource.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
private BigInteger getEmbeddedNonceValue(final OCSPResp ocspResp) {
	try {
		BasicOCSPResp basicOCSPResp = (BasicOCSPResp)ocspResp.getResponseObject();
		
		Extension extension = basicOCSPResp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
		ASN1OctetString extnValue = extension.getExtnValue();
		ASN1Primitive value;
		try {
			value = ASN1Primitive.fromByteArray(extnValue.getOctets());
		} catch (IOException ex) {
			throw new OCSPException("Invalid encoding of nonce extension value in OCSP response", ex);
		}
		if (value instanceof DEROctetString) {
			return new BigInteger(((DEROctetString) value).getOctets());
		}
		throw new OCSPException("Nonce extension value in OCSP response is not an OCTET STRING");
	} catch (Exception e) {
		throw new DSSException(String.format("Unable to extract the nonce from the OCSPResponse! Reason : [%s]", e.getMessage()), e);
	}
}
 
Example 7
Source Project: dss   Source File: OCSPToken.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * This method extracts the CertHash extension if present
 * 
 * Common PKI Part 4: Operational Protocols
 * 3.1.2 Common PKI Private OCSP Extensions
 * 
 * CertHash ::= SEQUENCE {
 * hashAlgorithm AlgorithmIdentifier,
 * certificateHash OCTET STRING }
 * 
 * @param bestSingleResp
 *            the related SingleResponse
 */
private void extractCertHashExtension(SingleResp bestSingleResp) {
	Extension extension = bestSingleResp.getExtension(ISISMTTObjectIdentifiers.id_isismtt_at_certHash);
	if (extension != null) {
		try {
			CertHash asn1CertHash = CertHash.getInstance(extension.getParsedValue());
			DigestAlgorithm digestAlgo = DigestAlgorithm.forOID(asn1CertHash.getHashAlgorithm().getAlgorithm().getId());
			Digest certHash = new Digest(digestAlgo, asn1CertHash.getCertificateHash());

			certHashPresent = true;
			byte[] expectedDigest = relatedCertificate.getDigest(certHash.getAlgorithm());
			byte[] foundDigest = certHash.getValue();
			certHashMatch = Arrays.equals(expectedDigest, foundDigest);

		} catch (Exception e) {
			LOG.warn("Unable to extract id_isismtt_at_certHash : {}", e.getMessage());
		}
	}
}
 
Example 8
Source Project: dss   Source File: DSSASN1Utils.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
public static SemanticsIdentifier getSemanticsIdentifier(CertificateToken certToken) {
	final byte[] qcStatement = certToken.getCertificate().getExtensionValue(Extension.qCStatements.getId());
	if (Utils.isArrayNotEmpty(qcStatement)) {
		try {
			final ASN1Sequence seq = getAsn1SequenceFromDerOctetString(qcStatement);
			for (int i = 0; i < seq.size(); i++) {
				final QCStatement statement = QCStatement.getInstance(seq.getObjectAt(i));
				if (RFC3739QCObjectIdentifiers.id_qcs_pkixQCSyntax_v2.equals(statement.getStatementId())) {
					SemanticsInformation semanticsInfo = SemanticsInformation.getInstance(statement.getStatementInfo());
					if (semanticsInfo != null && semanticsInfo.getSemanticsIdentifier() != null) {
						return SemanticsIdentifier.fromOid(semanticsInfo.getSemanticsIdentifier().getId());
					}
				}
			}
		} catch (Exception e) {
			LOG.warn("Unable to extract the SemanticsIdentifier", e);
		}
	}
	return null;
}
 
Example 9
Source Project: logback-gelf   Source File: X509Util.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
private X509Certificate build() throws NoSuchAlgorithmException,
    CertIOException, OperatorCreationException, CertificateException {

    final X500Principal issuer = new X500Principal("CN=MyCA");
    final BigInteger sn = new BigInteger(64, new SecureRandom());
    final Date from = Date.valueOf(LocalDate.now());
    final Date to = Date.valueOf(LocalDate.now().plusYears(1));
    final X509v3CertificateBuilder v3CertGen =
        new JcaX509v3CertificateBuilder(issuer, sn, from, to, issuer, keyPair.getPublic());
    final JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
    v3CertGen.addExtension(Extension.authorityKeyIdentifier, false,
        extUtils.createAuthorityKeyIdentifier(keyPair.getPublic()));
    v3CertGen.addExtension(Extension.subjectKeyIdentifier, false,
        extUtils.createSubjectKeyIdentifier(keyPair.getPublic()));
    v3CertGen.addExtension(Extension.basicConstraints, true,
        new BasicConstraints(0));
    v3CertGen.addExtension(Extension.keyUsage, true,
        new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));
    final ContentSigner signer = new JcaContentSignerBuilder(SIG_ALGORITHM)
        .build(keyPair.getPrivate());
    return new JcaX509CertificateConverter()
        .setProvider(BouncyCastleProvider.PROVIDER_NAME)
        .getCertificate(v3CertGen.build(signer));
}
 
Example 10
Source Project: SecuritySample   Source File: CRLDistributionPointsImpl.java    License: Apache License 2.0 6 votes vote down vote up
public CRLDistributionPointsImpl(X509Certificate cert) throws CertificateException, IOException {
	URINames = new ArrayList<>();
	byte[] extVal = cert.getExtensionValue(Extension.cRLDistributionPoints.getId());
	if (extVal == null)
		return;
	CRLDistPoint crlDistPoint = CRLDistPoint.getInstance(X509ExtensionUtil.fromExtensionValue(extVal));
	DistributionPoint[] points = crlDistPoint.getDistributionPoints();
	for (DistributionPoint p : points) {
		GeneralNames tmp = p.getCRLIssuer();
		if (tmp != null) {
			GeneralName[] crlIssers = tmp.getNames();
			for (int i = 0; i < crlIssers.length; i++) {
				if (crlIssers[i].getTagNo() == GeneralName.uniformResourceIdentifier) {
					String issuerUrl = crlIssers[i].toString();
					URINames.add(issuerUrl);
				}
			}
		}
	}
}
 
Example 11
Source Project: bouncr   Source File: Certificate.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public static X500PrivateCredential generateServerCertificate(KeyPair caKeyPair) throws NoSuchAlgorithmException, CertificateException, OperatorCreationException, CertIOException {
    X500Name issuerName = new X500Name("CN=bouncrca");
    X500Name subjectName = new X500Name("CN=bouncr");
    BigInteger serial = BigInteger.valueOf(2);
    long t1 = System.currentTimeMillis();
    KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA");
    rsa.initialize(2048, SecureRandom.getInstance("NativePRNGNonBlocking"));
    KeyPair kp = rsa.generateKeyPair();
    System.out.println(System.currentTimeMillis() - t1);

    X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerName, serial, NOT_BEFORE, NOT_AFTER, subjectName, kp.getPublic());
    DERSequence subjectAlternativeNames = new DERSequence(new ASN1Encodable[] {
            new GeneralName(GeneralName.dNSName, "localhost"),
            new GeneralName(GeneralName.dNSName, "127.0.0.1")
    });
    builder.addExtension(Extension.subjectAlternativeName, false, subjectAlternativeNames);
    X509Certificate cert = signCertificate(builder, caKeyPair.getPrivate());

    return new X500PrivateCredential(cert, kp.getPrivate());
}
 
Example 12
Source Project: xipki   Source File: X509Util.java    License: Apache License 2.0 6 votes vote down vote up
public static Extension createExtnSubjectInfoAccess(List<String> accessMethodAndLocations,
    boolean critical) throws BadInputException {
  if (CollectionUtil.isEmpty(accessMethodAndLocations)) {
    return null;
  }

  ASN1EncodableVector vector = new ASN1EncodableVector();
  for (String accessMethodAndLocation : accessMethodAndLocations) {
    vector.add(createAccessDescription(accessMethodAndLocation));
  }
  ASN1Sequence seq = new DERSequence(vector);
  try {
    return new Extension(Extension.subjectInfoAccess, critical, seq.getEncoded());
  } catch (IOException ex) {
    throw new IllegalStateException(ex.getMessage(), ex);
  }
}
 
Example 13
Source Project: xipki   Source File: CtLogTest.java    License: Apache License 2.0 6 votes vote down vote up
private void parseCtLogInCert(String certFile) throws Exception {
  byte[] certBytes = IoUtil.read(getClass().getResourceAsStream(certFile));
  certBytes = X509Util.toDerEncoded(certBytes);
  Certificate cert = Certificate.getInstance(certBytes);
  Extension extn = cert.getTBSCertificate().getExtensions().getExtension(
                      ObjectIdentifiers.Extn.id_SCTs);
  byte[] encodedScts = DEROctetString.getInstance(extn.getParsedValue()).getOctets();
  SignedCertificateTimestampList sctList2 =
      SignedCertificateTimestampList.getInstance(encodedScts);
  SignedCertificateTimestamp sct = sctList2.getSctList().get(0);
  sct.getDigitallySigned().getEncoded();
  sctList2.getSctList().get(0).getDigitallySigned().getSignatureObject();
  byte[] encoded2 = sctList2.getEncoded();
  Assert.assertArrayEquals(encodedScts, encoded2);
}
 
Example 14
Source Project: xipki   Source File: XijsonCertprofile.java    License: Apache License 2.0 5 votes vote down vote up
private void initBasicConstraints(Set<ASN1ObjectIdentifier> extnIds,
    Map<String, ExtensionType> extensions) throws CertprofileException {
  ASN1ObjectIdentifier type = Extension.basicConstraints;
  if (extensionControls.containsKey(type)) {
    extnIds.remove(type);
    BasicConstraints extConf = getExtension(type, extensions).getBasicConstrains();
    if (extConf != null) {
      this.pathLen = extConf.getPathLen();
    }
  }
}
 
Example 15
@Override
public CRLValidity buildCRLValidity(CRLBinary crlBinary, CertificateToken issuerToken) throws IOException {
	
	final CRLValidity crlValidity = new CRLValidity(crlBinary);
	
	CRLInfo crlInfos = getCrlInfo(crlValidity);
	SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.forOidAndParams(crlInfos.getCertificateListSignatureAlgorithmOid(),
			crlInfos.getCertificateListSignatureAlgorithmParams());
	crlValidity.setSignatureAlgorithm(signatureAlgorithm);

	crlValidity.setThisUpdate(crlInfos.getThisUpdate());
	crlValidity.setNextUpdate(crlInfos.getNextUpdate());

	crlValidity.setCriticalExtensionsOid(crlInfos.getCriticalExtensions().keySet());
	extractIssuingDistributionPointBinary(crlValidity, crlInfos.getCriticalExtension(Extension.issuingDistributionPoint.getId()));
	extractExpiredCertsOnCRL(crlValidity, crlInfos.getNonCriticalExtension(Extension.expiredCertsOnCRL.getId()));

	final X500Principal x509CRLIssuerX500Principal = crlInfos.getIssuer();
	final X500Principal issuerTokenSubjectX500Principal = issuerToken.getSubject().getPrincipal();
	if (x509CRLIssuerX500Principal.equals(issuerTokenSubjectX500Principal)) {
		crlValidity.setIssuerX509PrincipalMatches(true);
	}

	checkSignatureValue(crlValidity, crlInfos.getSignatureValue(), signatureAlgorithm, getSignedData(crlValidity), issuerToken);
	
	return crlValidity;
}
 
Example 16
Source Project: dcos-commons   Source File: TLSArtifactsGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("checkstyle:ThrowsCount")
private static byte[] generateCSR(
    KeyPair keyPair,
    CertificateNamesGenerator certificateNamesGenerator)
    throws IOException, OperatorCreationException
{
  ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
  extensionsGenerator
      .addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature));
  extensionsGenerator.addExtension(
      Extension.extendedKeyUsage,
      true,
      new ExtendedKeyUsage(
          new KeyPurposeId[]{
              KeyPurposeId.id_kp_clientAuth,
              KeyPurposeId.id_kp_serverAuth,
          }
      ));
  extensionsGenerator.addExtension(
      Extension.subjectAlternativeName,
      true,
      certificateNamesGenerator.getSANs()
  );

  PKCS10CertificationRequest csr =
      new JcaPKCS10CertificationRequestBuilder(
          certificateNamesGenerator.getSubject(),
          keyPair.getPublic())
          .addAttribute(
              PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
              extensionsGenerator.generate()
          )
          .build(
              new JcaContentSignerBuilder("SHA256withRSA")
                  .build(keyPair.getPrivate())
          );
  return PEMUtils.toPEM(csr);
}
 
Example 17
Source Project: xipki   Source File: CertprofileQa.java    License: Apache License 2.0 5 votes vote down vote up
public static Map<ASN1ObjectIdentifier, QaExtensionValue> buildConstantExtesions(
    Map<String, ExtensionType> extensionsType) throws CertprofileException {
  if (extensionsType == null) {
    return null;
  }

  Map<ASN1ObjectIdentifier, QaExtensionValue> map = new HashMap<>();

  for (String type : extensionsType.keySet()) {
    ExtensionType extn = extensionsType.get(type);
    if (extn.getConstant() == null) {
      continue;
    }

    ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier(type);
    if (Extension.subjectAlternativeName.equals(oid) || Extension.subjectInfoAccess.equals(oid)
        || Extension.biometricInfo.equals(oid)) {
      continue;
    }

    byte[] encodedValue;
    try {
      encodedValue = extn.getConstant().toASN1Encodable().toASN1Primitive().getEncoded();
    } catch (IOException | InvalidConfException ex) {
      throw new CertprofileException(
          "could not parse the constant extension value of type" + type, ex);
    }

    QaExtensionValue extension = new QaExtensionValue(extn.isCritical(), encodedValue);
    map.put(oid, extension);
  }

  if (CollectionUtil.isEmpty(map)) {
    return null;
  }

  return Collections.unmodifiableMap(map);
}
 
Example 18
Source Project: credhub   Source File: SignedCertificateGeneratorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void getSignedByIssuer_setsSubjectKeyIdentifier() throws Exception {
  final X509Certificate generatedCertificate = subject
    .getSignedByIssuer(generatedCertificateKeyPair, certificateGenerationParameters,
      certificateAuthorityWithSubjectKeyId, issuerKey.getPrivate());
  expectedSubjectKeyIdentifier = jcaX509ExtensionUtils.createSubjectKeyIdentifier(generatedCertificateKeyPair.getPublic()).getKeyIdentifier();
  final byte[] actual = generatedCertificate.getExtensionValue(Extension.subjectKeyIdentifier.getId());
  // four bit type field is added at the beginning as per RFC 5280
  assertThat(Arrays.copyOfRange(actual, 4, actual.length), equalTo(expectedSubjectKeyIdentifier));
}
 
Example 19
Source Project: fabric-sdk-java   Source File: TLSCertificateBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private X509Certificate createSelfSignedCertificate(CertType certType, KeyPair keyPair, String san) throws Exception {
    X509v3CertificateBuilder certBuilder = createCertBuilder(keyPair);

    // Basic constraints
    BasicConstraints constraints = new BasicConstraints(false);
    certBuilder.addExtension(
            Extension.basicConstraints,
            true,
            constraints.getEncoded());
    // Key usage
    KeyUsage usage = new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.digitalSignature);
    certBuilder.addExtension(Extension.keyUsage, false, usage.getEncoded());
    // Extended key usage
    certBuilder.addExtension(
            Extension.extendedKeyUsage,
            false,
            certType.keyUsage().getEncoded());

    if (san != null) {
        addSAN(certBuilder, san);
    }

    ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm)
            .build(keyPair.getPrivate());
    X509CertificateHolder holder = certBuilder.build(signer);

    JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
    converter.setProvider(new BouncyCastleProvider());
    return converter.getCertificate(holder);
}
 
Example 20
Source Project: Spark   Source File: SparkTrustManager.java    License: Apache License 2.0 5 votes vote down vote up
public Collection<X509CRL> loadCRL(X509Certificate[] chain) throws IOException, InvalidAlgorithmParameterException,
        NoSuchAlgorithmException, CertStoreException, CRLException, CertificateException {

    // for each certificate in chain
    for (X509Certificate cert : chain) {
        if (cert.getExtensionValue(Extension.cRLDistributionPoints.getId()) != null) {
            ASN1Primitive primitive = JcaX509ExtensionUtils
                    .parseExtensionValue(cert.getExtensionValue(Extension.cRLDistributionPoints.getId()));
            // extract distribution point extension
            CRLDistPoint distPoint = CRLDistPoint.getInstance(primitive);
            DistributionPoint[] dp = distPoint.getDistributionPoints();
            // each distribution point extension can hold number of distribution points
            for (DistributionPoint d : dp) {
                DistributionPointName dpName = d.getDistributionPoint();
                // Look for URIs in fullName
                if (dpName != null && dpName.getType() == DistributionPointName.FULL_NAME) {
                    GeneralName[] genNames = GeneralNames.getInstance(dpName.getName()).getNames();
                    // Look for an URI
                    for (GeneralName genName : genNames) {
                        // extract url
                        URL url = new URL(genName.getName().toString());
                        try {
                            // download from Internet to the collection
                            crlCollection.add(downloadCRL(url));
                        } catch (CertificateException | CRLException e) {
                            throw new CRLException("Couldn't download CRL");
                        }
                    }
                }
            }
        } else {
            Log.warning("Certificate " + cert.getSubjectX500Principal().getName().toString() + " have no CRLs");
        }
        // parameters for cert store is collection type, using collection with crl create parameters
        CollectionCertStoreParameters params = new CollectionCertStoreParameters(crlCollection);
        // this parameters are next used for creation of certificate store with crls
        crlStore = CertStore.getInstance("Collection", params);
    }
    return crlCollection;
}
 
Example 21
Source Project: hadoop-ozone   Source 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 22
Source Project: hadoop-ozone   Source File: TestRootCertificate.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCACert()
    throws SCMSecurityException, NoSuchProviderException,
    NoSuchAlgorithmException, IOException {
  LocalDate notBefore = LocalDate.now();
  LocalDate notAfter = notBefore.plus(365, ChronoUnit.DAYS);
  String clusterID = UUID.randomUUID().toString();
  String scmID = UUID.randomUUID().toString();
  String subject = "testRootCert";
  HDDSKeyGenerator keyGen =
      new HDDSKeyGenerator(securityConfig.getConfiguration());
  KeyPair keyPair = keyGen.generateKey();

  SelfSignedCertificate.Builder builder =
      SelfSignedCertificate.newBuilder()
          .setBeginDate(notBefore)
          .setEndDate(notAfter)
          .setClusterID(clusterID)
          .setScmID(scmID)
          .setSubject(subject)
          .setKey(keyPair)
          .setConfiguration(conf)
          .makeCA();

  X509CertificateHolder certificateHolder = builder.build();
  // This time we asked for a CertificateServer Certificate, make sure that
  // extension is
  // present and valid.
  Extension basicExt =
      certificateHolder.getExtension(Extension.basicConstraints);

  Assert.assertNotNull(basicExt);
  Assert.assertTrue(basicExt.isCritical());

  // Since this code assigns ONE for the root certificate, we check if the
  // serial number is the expected number.
  Assert.assertEquals(certificateHolder.getSerialNumber(), BigInteger.ONE);
}
 
Example 23
Source Project: ph-commons   Source File: OCSPFuncTest.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
public static OCSPReq generateOCSPRequest (final X509Certificate aIssuerCert,
                                           final BigInteger aCheckSerialNumber) throws OCSPException
{
  try
  {
    final DigestCalculatorProvider aDigestCalculatorProvider = new JcaDigestCalculatorProviderBuilder ().setProvider (PBCProvider.getProvider ())
                                                                                                        .build ();
    final DigestCalculator aDigestCalculator = aDigestCalculatorProvider.get (CertificateID.HASH_SHA1);

    // CertID structure is used to uniquely identify certificates that are the
    // subject of an OCSP request or response and has an ASN.1 definition.
    // CertID structure is defined in RFC 2560
    final CertificateID aCertificateID = new JcaCertificateID (aDigestCalculator, aIssuerCert, aCheckSerialNumber);

    // create details for nonce extension. The nonce extension is used to bind
    // a request to a response to prevent replay attacks. As the name implies,
    // the nonce value is something that the client should only use once
    // within a reasonably small period.
    final BigInteger aNonce = BigInteger.valueOf (System.nanoTime ());

    // to create the request Extension
    final Extensions aExtensions = new Extensions (new Extension (OCSPObjectIdentifiers.id_pkix_ocsp_nonce,
                                                                  false,
                                                                  new DEROctetString (aNonce.toByteArray ())));

    // basic request generation with nonce
    final OCSPReqBuilder aBuilder = new OCSPReqBuilder ();
    aBuilder.addRequest (aCertificateID);
    // Extension to the whole request
    aBuilder.setRequestExtensions (aExtensions);
    return aBuilder.build ();
  }
  catch (final OperatorCreationException | CertificateEncodingException ex)
  {
    throw new IllegalStateException (ex);
  }
}
 
Example 24
Source Project: PowerTunnel   Source File: SubjectAlternativeNameHolder.java    License: MIT License 5 votes vote down vote up
public void fillInto(X509v3CertificateBuilder certGen)
        throws CertIOException {
    if (!sans.isEmpty()) {
        ASN1Encodable[] encodables = sans.toArray(new ASN1Encodable[sans
                .size()]);
        certGen.addExtension(Extension.subjectAlternativeName, false,
                new DERSequence(encodables));
    }
}
 
Example 25
Source Project: xipki   Source File: XijsonCertprofile.java    License: Apache License 2.0 5 votes vote down vote up
private void initSubjectAlternativeName(Set<ASN1ObjectIdentifier> extnIds,
    Map<String, ExtensionType> extensions) throws CertprofileException {
  ASN1ObjectIdentifier type = Extension.subjectAlternativeName;
  if (extensionControls.containsKey(type)) {
    extnIds.remove(type);
    GeneralNameType extConf = getExtension(type, extensions).getSubjectAltName();
    if (extConf != null) {
      this.subjectAltNameModes = extConf.toGeneralNameModes();
    }
  }
}
 
Example 26
Source Project: acme-client   Source File: X509Utils.java    License: Apache License 2.0 5 votes vote down vote up
public static PKCS10CertificationRequest generateCSR(String[] commonNames, KeyPair pair) throws OperatorCreationException, IOException {
	X500NameBuilder namebuilder = new X500NameBuilder(X500Name.getDefaultStyle());
	namebuilder.addRDN(BCStyle.CN, commonNames[0]);
	
	List<GeneralName> subjectAltNames = new ArrayList<>(commonNames.length);
	for (String cn:commonNames)
		subjectAltNames.add(new GeneralName(GeneralName.dNSName, cn));
	GeneralNames subjectAltName = new GeneralNames(subjectAltNames.toArray(new GeneralName[0]));         
	
	ExtensionsGenerator extGen = new ExtensionsGenerator();
	extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltName.toASN1Primitive());
	
	PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(namebuilder.build(), pair.getPublic());
	p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate());
	JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA");
	ContentSigner signer = csBuilder.build(pair.getPrivate());
	PKCS10CertificationRequest request = p10Builder.build(signer);
	return request;
}
 
Example 27
Source Project: xipki   Source File: IdentifiedCertprofile.java    License: Apache License 2.0 5 votes vote down vote up
private static ASN1Sequence createSubjectInfoAccess(
    Map<ASN1ObjectIdentifier, Extension> requestedExtensions,
    Map<ASN1ObjectIdentifier, Set<GeneralNameMode>> modes) throws BadCertTemplateException {
  if (modes == null) {
    return null;
  }

  Extension extn = requestedExtensions.get(Extension.subjectInfoAccess);
  if (extn == null) {
    return null;
  }

  ASN1Encodable extValue = extn.getParsedValue();
  if (extValue == null) {
    return null;
  }

  ASN1Sequence reqSeq = ASN1Sequence.getInstance(extValue);
  int size = reqSeq.size();

  ASN1EncodableVector vec = new ASN1EncodableVector();
  for (int i = 0; i < size; i++) {
    AccessDescription ad = AccessDescription.getInstance(reqSeq.getObjectAt(i));
    ASN1ObjectIdentifier accessMethod = ad.getAccessMethod();
    Set<GeneralNameMode> generalNameModes = modes.get(accessMethod);

    if (generalNameModes == null) {
      throw new BadCertTemplateException("subjectInfoAccess.accessMethod "
          + accessMethod.getId() + " is not allowed");
    }

    GeneralName accessLocation = BaseCertprofile.createGeneralName(
        ad.getAccessLocation(), generalNameModes);
    vec.add(new AccessDescription(accessMethod, accessLocation));
  } // end for

  return vec.size() > 0 ? new DERSequence(vec) : null;
}
 
Example 28
Source Project: Openfire   Source File: CertificateManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@link CertificateManager#getServerIdentities(X509Certificate)} should return:
 * <ul>
 *     <li>the 'DNS SRV' subjectAltName value</li>
 *     <li>explicitly not the Common Name</li>
 * </ul>
 *
 * when a certificate contains:
 * <ul>
 *     <li>a subjectAltName entry of type otherName with an ASN.1 Object Identifier of "id-on-dnsSRV"</li>
 * </ul>
 */
@Test
public void testServerIdentitiesDnsSrv() throws Exception
{
    // Setup fixture.
    final String subjectCommonName = "MySubjectCommonName";
    final String subjectAltNameDnsSrv = "MySubjectAltNameXmppAddr";

    final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
            new X500Name( "CN=MyIssuer" ),                                          // Issuer
            BigInteger.valueOf( Math.abs( new SecureRandom().nextInt() ) ),         // Random serial number
            new Date( System.currentTimeMillis() - ( 1000L * 60 * 60 * 24 * 30 ) ), // Not before 30 days ago
            new Date( System.currentTimeMillis() + ( 1000L * 60 * 60 * 24 * 99 ) ), // Not after 99 days from now
            new X500Name( "CN=" + subjectCommonName ),                              // Subject
            subjectKeyPair.getPublic()
    );

    final DERSequence otherName = new DERSequence( new ASN1Encodable[] {DNS_SRV_OID, new DERUTF8String( "_xmpp-server."+subjectAltNameDnsSrv ) });
    final GeneralNames subjectAltNames = new GeneralNames( new GeneralName(GeneralName.otherName, otherName ) );
    builder.addExtension( Extension.subjectAlternativeName, true, subjectAltNames );

    final X509CertificateHolder certificateHolder = builder.build( contentSigner );
    final X509Certificate cert = new JcaX509CertificateConverter().getCertificate( certificateHolder );

    // Execute system under test
    final List<String> serverIdentities = CertificateManager.getServerIdentities( cert );

    // Verify result
    assertEquals( 1, serverIdentities.size() );
    assertTrue( serverIdentities.contains( subjectAltNameDnsSrv ));
    assertFalse( serverIdentities.contains( subjectCommonName ) );
}
 
Example 29
Source Project: NetBare   Source File: CertificateGenerator.java    License: MIT License 5 votes vote down vote up
public KeyStore generateServer(String commonName, JKS jks,
                                      Certificate caCert, PrivateKey caPrivKey)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        IOException, OperatorCreationException, CertificateException,
        InvalidKeyException, SignatureException, KeyStoreException {

    KeyPair keyPair = generateKeyPair(SERVER_KEY_SIZE);

    X500Name issuer = new X509CertificateHolder(caCert.getEncoded()).getSubject();
    BigInteger serial = BigInteger.valueOf(randomSerial());
    X500NameBuilder name = new X500NameBuilder(BCStyle.INSTANCE);
    name.addRDN(BCStyle.CN, commonName);
    name.addRDN(BCStyle.O, jks.certOrganisation());
    name.addRDN(BCStyle.OU, jks.certOrganizationalUnitName());
    X500Name subject = name.build();

    X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, NOT_BEFORE,
            new Date(System.currentTimeMillis() + ONE_DAY), subject, keyPair.getPublic());
    builder.addExtension(Extension.subjectKeyIdentifier, false,
            createSubjectKeyIdentifier(keyPair.getPublic()));
    builder.addExtension(Extension.basicConstraints, false,
            new BasicConstraints(false));
    builder.addExtension(Extension.subjectAlternativeName, false,
            new DERSequence(new GeneralName(GeneralName.dNSName, commonName)));

    X509Certificate cert = signCertificate(builder, caPrivKey);

    cert.checkValidity(new Date());
    cert.verify(caCert.getPublicKey());

    KeyStore result = KeyStore.getInstance(KeyStore.getDefaultType());
    result.load(null, null);
    Certificate[] chain = { cert, caCert };
    result.setKeyEntry(jks.alias(), keyPair.getPrivate(), jks.password(), chain);
    return result;
}
 
Example 30
Source Project: localization_nifi   Source 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();
}