org.bouncycastle.asn1.x509.Extension Java Examples

The following examples show how to use org.bouncycastle.asn1.x509.Extension. 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: CtLogTest.java    From xipki with 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 #2
Source File: X509Util.java    From xipki with 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 #3
Source File: Certificate.java    From bouncr with 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 #4
Source File: CRLDistributionPointsImpl.java    From SecuritySample with 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 #5
Source File: X509Util.java    From logback-gelf with 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 #6
Source File: OCSPToken.java    From dss with 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 #7
Source File: OnlineOCSPSource.java    From dss with 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 #8
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 #9
Source File: DSSASN1Utils.java    From dss with 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 #10
Source File: DSSASN1Utils.java    From dss with 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 #11
Source File: DefaultProfile.java    From hadoop-ozone with 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 #12
Source File: CertificateSignRequest.java    From hadoop-ozone with 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 #13
Source File: OnlineOCSPSource.java    From dss with 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 #14
Source File: XijsonCertprofile.java    From xipki with Apache License 2.0 5 votes vote down vote up
private void initPrivateKeyUsagePeriod(Set<ASN1ObjectIdentifier> extnIds,
    Map<String, ExtensionType> extensions) throws CertprofileException {
  ASN1ObjectIdentifier type = Extension.privateKeyUsagePeriod;
  if (extensionControls.containsKey(type)) {
    extnIds.remove(type);
    PrivateKeyUsagePeriod extConf = getExtension(type, extensions).getPrivateKeyUsagePeriod();
    if (extConf != null) {
      privateKeyUsagePeriod = Validity.getInstance(extConf.getValidity());
    }
  }
}
 
Example #15
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static List<CertificatePolicy> getCertificatePolicies(final CertificateToken certToken) {
	List<CertificatePolicy> certificatePolicies = new ArrayList<>();
	final byte[] certificatePoliciesBinaries = certToken.getCertificate().getExtensionValue(Extension.certificatePolicies.getId());
	if (Utils.isArrayNotEmpty(certificatePoliciesBinaries)) {
		try {
			ASN1Sequence seq = getAsn1SequenceFromDerOctetString(certificatePoliciesBinaries);
			for (int ii = 0; ii < seq.size(); ii++) {
				CertificatePolicy cp = new CertificatePolicy();
				final PolicyInformation policyInfo = PolicyInformation.getInstance(seq.getObjectAt(ii));
				cp.setOid(policyInfo.getPolicyIdentifier().getId());
				ASN1Sequence policyQualifiersSeq = policyInfo.getPolicyQualifiers();
				if (policyQualifiersSeq != null) {
					for (int jj = 0; jj < policyQualifiersSeq.size(); jj++) {
						PolicyQualifierInfo pqi = PolicyQualifierInfo.getInstance(policyQualifiersSeq.getObjectAt(jj));
						if (PolicyQualifierId.id_qt_cps.equals(pqi.getPolicyQualifierId())) {
							cp.setCpsUrl(getString(pqi.getQualifier()));
						}
					}
				}
				certificatePolicies.add(cp);
			}
		} catch (Exception e) {
			LOG.warn("Unable to parse the certificatePolicies extension '{}' : {}", Utils.toBase64(certificatePoliciesBinaries), e.getMessage(), e);
		}
	}
	return certificatePolicies;
}
 
Example #16
Source File: SubjectAlternativeNameHolder.java    From LittleProxy-mitm with Apache License 2.0 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 #17
Source File: TlsResourceBuilder.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private static Extension createExtendedUsageExtension(final ExtendedKeyUsage extendedKeyUsage)
        throws CertificateException
{
    try
    {
        return new Extension(Extension.extendedKeyUsage, false, extendedKeyUsage.getEncoded());
    }
    catch (IOException e)
    {
        throw new CertificateException(e);
    }
}
 
Example #18
Source File: CertificateUtils.java    From nifi-registry with 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);
    }
}
 
Example #19
Source File: TlsResourceBuilder.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private static X509Certificate generateIntermediateCertificate(final KeyPair keyPair,
                                                               final KeyCertificatePair rootCA,
                                                               final String dn,
                                                               final ValidityPeriod validityPeriod,
                                                               final String crlUri)
        throws CertificateException
{
    try
    {
        final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
                rootCA.getCertificate(),
                generateSerialNumber(),
                new Date(validityPeriod.getFrom().toEpochMilli()),
                new Date(validityPeriod.getTo().toEpochMilli()),
                new X500Name(RFC4519Style.INSTANCE, dn),
                keyPair.getPublic());
        //builder.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.keyCertSign));
        builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));
        builder.addExtension(createSubjectKeyExtension(keyPair.getPublic()));
        builder.addExtension(createAuthorityKeyExtension(rootCA.getCertificate().getPublicKey()));
        if (crlUri != null)
        {
            builder.addExtension(createDistributionPointExtension(crlUri));
        }

        return buildX509Certificate(builder, rootCA.getPrivateKey());
    }
    catch (OperatorException | IOException e)
    {
        throw new CertificateException(e);
    }
}
 
Example #20
Source File: TlsResourceBuilder.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private static Extension createAuthorityKeyExtension(final PublicKey publicKey)
        throws CertificateException
{
    try
    {
        return new Extension(Extension.authorityKeyIdentifier,
                             false,
                             new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(publicKey).getEncoded());
    }
    catch (IOException | NoSuchAlgorithmException e)
    {
        throw new CertificateException(e);
    }
}
 
Example #21
Source File: TLSArtifactsGenerator.java    From dcos-commons with 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 #22
Source File: BasicConstraintsImpl.java    From SecuritySample with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
	StringBuilder sb = new StringBuilder();
	sb.append(OIDMap.getName(Extension.basicConstraints.getId()));
	sb.append(" [\n");
	sb.append("isCA:");
	sb.append(isCA);
	sb.append("\nPathLen:");
	if (pathLen == null)
		sb.append("undefined");
	else
		sb.append(pathLen);
	sb.append("\n]\n");
	return sb.toString();
}
 
Example #23
Source File: X509Cert.java    From xipki with Apache License 2.0 5 votes vote down vote up
public byte[] getExtensionCoreValue(ASN1ObjectIdentifier extnType) {
  if (bcInstance != null) {
    Extension extn = bcInstance.getExtensions().getExtension(extnType);
    return extn == null ? null : extn.getExtnValue().getOctets();
  } else {
    byte[] rawValue = jceInstance.getExtensionValue(extnType.getId());
    return rawValue == null ? null : ASN1OctetString.getInstance(rawValue).getOctets();
  }
}
 
Example #24
Source File: CertificateUtils.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Generates a self-signed {@link X509Certificate} suitable for use as a Certificate Authority.
 *
 * @param keyPair                 the {@link KeyPair} to generate the {@link X509Certificate} for
 * @param dn                      the distinguished name to user for the {@link X509Certificate}
 * @param signingAlgorithm        the signing algorithm to use for the {@link X509Certificate}
 * @param certificateDurationDays the duration in days for which the {@link X509Certificate} should be valid
 * @return a self-signed {@link X509Certificate} suitable for use as a Certificate Authority
 * @throws CertificateException if there is an generating the new certificate
 */
public static X509Certificate generateSelfSignedX509Certificate(KeyPair keyPair, String dn, String signingAlgorithm, int certificateDurationDays)
        throws CertificateException {
    try {
        ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keyPair.getPrivate());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
        Date startDate = new Date();
        Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(certificateDurationDays));

        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(
                reverseX500Name(new X500Name(dn)),
                getUniqueSerialNumber(),
                startDate, endDate,
                reverseX500Name(new X500Name(dn)),
                subPubKeyInfo);

        // Set certificate extensions
        // (1) digitalSignature extension
        certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment
                | KeyUsage.keyAgreement | KeyUsage.nonRepudiation | KeyUsage.cRLSign | KeyUsage.keyCertSign));

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

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

        certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(keyPair.getPublic()));

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

        // Sign the certificate
        X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
        return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder);
    } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) {
        throw new CertificateException(e);
    }
}
 
Example #25
Source File: CertUtil.java    From proxyee with MIT License 5 votes vote down vote up
/**
 * 生成CA服务器证书
 */
public static X509Certificate genCACert(String subject, Date caNotBefore, Date caNotAfter,
                                        KeyPair keyPair) throws Exception {
    JcaX509v3CertificateBuilder jv3Builder = new JcaX509v3CertificateBuilder(new X500Name(subject),
            BigInteger.valueOf(System.currentTimeMillis() + (long) (Math.random() * 10000) + 1000),
            caNotBefore,
            caNotAfter,
            new X500Name(subject),
            keyPair.getPublic());
    jv3Builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(0));
    ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
            .build(keyPair.getPrivate());
    return new JcaX509CertificateConverter().getCertificate(jv3Builder.build(signer));
}
 
Example #26
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * This method extract the PSD2 QcStatement informations for a given certificate
 * 
 * @param certToken the certificate
 * @return an instance of {@code PSD2QcType} or null
 */
public static PSD2QcType getPSD2QcStatement(CertificateToken certToken) {
	PSD2QcType result = null;
	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 (OID.psd2_qcStatement.equals(statement.getStatementId())) {
					result = new PSD2QcType();
					ASN1Sequence psd2Seq = ASN1Sequence.getInstance(statement.getStatementInfo());
					ASN1Sequence rolesSeq = ASN1Sequence.getInstance(psd2Seq.getObjectAt(0));

					List<RoleOfPSP> rolesOfPSP = new ArrayList<>();
					for (int ii = 0; ii < rolesSeq.size(); ii++) {
						ASN1Sequence oneRoleSeq = ASN1Sequence.getInstance(rolesSeq.getObjectAt(ii));
						RoleOfPSP roleOfPSP = new RoleOfPSP();
						ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) oneRoleSeq.getObjectAt(0);
						roleOfPSP.setPspOid(RoleOfPspOid.fromOid(oid.getId()));
						roleOfPSP.setPspName(getString(oneRoleSeq.getObjectAt(1)));
						rolesOfPSP.add(roleOfPSP);
					}
					result.setRolesOfPSP(rolesOfPSP);
					result.setNcaName(getString(psd2Seq.getObjectAt(1)));
					result.setNcaId(getString(psd2Seq.getObjectAt(2)));
				}
			}
		} catch (Exception e) {
			LOG.warn("Unable to read QCStatement", e);
		}
	}
	return result;
}
 
Example #27
Source File: CertificateUtils.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Generates a self-signed {@link X509Certificate} suitable for use as a Certificate Authority.
 *
 * @param keyPair                 the {@link KeyPair} to generate the {@link X509Certificate} for
 * @param dn                      the distinguished name to user for the {@link X509Certificate}
 * @param signingAlgorithm        the signing algorithm to use for the {@link X509Certificate}
 * @param certificateDurationDays the duration in days for which the {@link X509Certificate} should be valid
 * @return a self-signed {@link X509Certificate} suitable for use as a Certificate Authority
 * @throws CertificateException      if there is an generating the new certificate
 */
public static X509Certificate generateSelfSignedX509Certificate(KeyPair keyPair, String dn, String signingAlgorithm, int certificateDurationDays)
        throws CertificateException {
    try {
        ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keyPair.getPrivate());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
        Date startDate = new Date();
        Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(certificateDurationDays));

        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(
                reverseX500Name(new X500Name(dn)),
                getUniqueSerialNumber(),
                startDate, endDate,
                reverseX500Name(new X500Name(dn)),
                subPubKeyInfo);

        // Set certificate extensions
        // (1) digitalSignature extension
        certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment
                | KeyUsage.keyAgreement | KeyUsage.nonRepudiation | KeyUsage.cRLSign | KeyUsage.keyCertSign));

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

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

        certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(keyPair.getPublic()));

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

        // Sign the certificate
        X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
        return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder);
    } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) {
        throw new CertificateException(e);
    }
}
 
Example #28
Source File: TlsHelper.java    From localization_nifi with 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 #29
Source File: XijsonCertprofile.java    From xipki with 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 #30
Source File: ExtendedKeyUsageImpl.java    From SecuritySample with Apache License 2.0 5 votes vote down vote up
public ExtendedKeyUsageImpl(X509Certificate cert) throws IOException {
	keyPurposeIds = new ArrayList<>();
	byte[] extVal = cert.getExtensionValue(Extension.extendedKeyUsage.getId());
	if (extVal == null)
		return;
	org.bouncycastle.asn1.x509.ExtendedKeyUsage usage = org.bouncycastle.asn1.x509.ExtendedKeyUsage
			.getInstance(X509ExtensionUtil.fromExtensionValue(extVal));
	KeyPurposeId[] usages = usage.getUsages();
	for (int i = 0; i < usages.length; i++) {
		keyPurposeIds.add(usages[i].getId());
	}
}