org.bouncycastle.cert.X509CertificateHolder Java Examples

The following examples show how to use org.bouncycastle.cert.X509CertificateHolder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CertificateUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 7 votes vote down vote up
public static X509Certificate generateCert(PublicKey rqPubKey, BigInteger serialNr, Credential cred) throws TechnicalConnectorException {
   try {
      X509Certificate cert = cred.getCertificate();
      X500Principal principal = cert.getSubjectX500Principal();
      Date notBefore = cert.getNotBefore();
      Date notAfter = cert.getNotAfter();
      X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(principal, serialNr, notBefore, notAfter, principal, rqPubKey);
      int keyUsageDetails = 16 + 32;
      builder.addExtension(Extension.keyUsage, true, new KeyUsage(keyUsageDetails));
      ContentSigner signer = (new JcaContentSignerBuilder(cert.getSigAlgName())).build(cred.getPrivateKey());
      X509CertificateHolder holder = builder.build(signer);
      return (new JcaX509CertificateConverter()).setProvider("BC").getCertificate(holder);
   } catch (OperatorCreationException | IOException | CertificateException ex) {
      throw new IllegalArgumentException(ex);
   }
}
 
Example #2
Source File: OcspServerExample.java    From netty-4.1.22 with Apache License 2.0 7 votes vote down vote up
private static X509Certificate[] parseCertificates(Reader reader) throws Exception {

        JcaX509CertificateConverter converter = new JcaX509CertificateConverter()
                .setProvider(new BouncyCastleProvider());

        List<X509Certificate> dst = new ArrayList<X509Certificate>();

        PEMParser parser = new PEMParser(reader);
        try {
          X509CertificateHolder holder = null;

          while ((holder = (X509CertificateHolder) parser.readObject()) != null) {
            X509Certificate certificate = converter.getCertificate(holder);
            if (certificate == null) {
              continue;
            }

            dst.add(certificate);
          }
        } finally {
            parser.close();
        }

        return dst.toArray(new X509Certificate[0]);
    }
 
Example #3
Source File: TestDefaultCAServer.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
@Test
public void testInit() throws SCMSecurityException, CertificateException,
    IOException {
  SecurityConfig securityConfig = new SecurityConfig(conf);
  CertificateServer testCA = new DefaultCAServer("testCA",
      RandomStringUtils.randomAlphabetic(4),
      RandomStringUtils.randomAlphabetic(4), caStore);
  testCA.init(securityConfig, CertificateServer.CAType.SELF_SIGNED_CA);
  X509CertificateHolder first = testCA.getCACertificate();
  assertNotNull(first);
  //Init is idempotent.
  testCA.init(securityConfig, CertificateServer.CAType.SELF_SIGNED_CA);
  X509CertificateHolder second = testCA.getCACertificate();
  assertEquals(first, second);

  // we only support Self Signed CA for now.
  try {
    testCA.init(securityConfig, CertificateServer.CAType.INTERMEDIARY_CA);
    fail("code should not reach here, exception should have been thrown.");
  } catch (IllegalStateException e) {
    // This is a run time exception, hence it is not caught by the junit
    // expected Exception.
    assertTrue(e.toString().contains("Not implemented"));
  }
}
 
Example #4
Source File: IdentityController.java    From Spark with Apache License 2.0 6 votes vote down vote up
public X509Certificate createSelfSignedCertificate(KeyPair keyPair) throws NoSuchAlgorithmException, NoSuchProviderException, CertIOException, OperatorCreationException, CertificateException {

        long serial = System.currentTimeMillis();
        SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
        X500Name name = new X500Name(createX500NameString());
        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(name, 
                                                                            BigInteger.valueOf(serial), 
                                                                            new Date(System.currentTimeMillis() - 1000000000), 
                                                                            new Date(System.currentTimeMillis() + 1000000000),
                                                                            name, 
                                                                            keyInfo
                                                                            );
        certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); 
        certBuilder.addExtension(Extension.keyUsage,         true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
        certBuilder.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));
    
        JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA");
        ContentSigner signer = csBuilder.build(keyPair.getPrivate());
        X509CertificateHolder certHolder = certBuilder.build(signer);
        X509Certificate cert = new JcaX509CertificateConverter().getCertificate(certHolder);
        
        return cert;
    }
 
Example #5
Source File: CertificateManager.java    From Launcher with GNU General Public License v3.0 6 votes vote down vote up
public X509CertificateHolder generateCertificate(String subjectName, PublicKey subjectPublicKey) throws OperatorCreationException {
    SubjectPublicKeyInfo subjectPubKeyInfo = SubjectPublicKeyInfo.getInstance(subjectPublicKey.getEncoded());
    BigInteger serial = BigInteger.valueOf(SecurityHelper.newRandom().nextLong());
    Date startDate = Date.from(Instant.now().minus(minusHours, ChronoUnit.HOURS));
    Date endDate = Date.from(startDate.toInstant().plus(validDays, ChronoUnit.DAYS));

    X500NameBuilder subject = new X500NameBuilder();
    subject.addRDN(BCStyle.CN, subjectName);
    subject.addRDN(BCStyle.O, orgName);
    X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(ca.getSubject(), serial,
            startDate, endDate, subject.build(), subjectPubKeyInfo);

    AlgorithmIdentifier sigAlgId = ca.getSignatureAlgorithm();
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    ContentSigner sigGen = new BcECContentSignerBuilder(sigAlgId, digAlgId).build(caKey);

    return v3CertGen.build(sigGen);
}
 
Example #6
Source File: DefaultCAServer.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a self-signed Root Certificate for CA.
 *
 * @param securityConfig - SecurityConfig
 * @param key - KeyPair.
 * @throws IOException          - on Error.
 * @throws SCMSecurityException - on Error.
 */
private void generateRootCertificate(SecurityConfig securityConfig,
    KeyPair key) throws IOException, SCMSecurityException {
  Preconditions.checkNotNull(this.config);
  LocalDate beginDate = LocalDate.now().atStartOfDay().toLocalDate();
  LocalDateTime temp = LocalDateTime.of(beginDate, LocalTime.MIDNIGHT);
  LocalDate endDate =
      temp.plus(securityConfig.getMaxCertificateDuration()).toLocalDate();
  X509CertificateHolder selfSignedCertificate =
      SelfSignedCertificate
          .newBuilder()
          .setSubject(this.subject)
          .setScmID(this.scmID)
          .setClusterID(this.clusterID)
          .setBeginDate(beginDate)
          .setEndDate(endDate)
          .makeCA()
          .setConfiguration(securityConfig.getConfiguration())
          .setKey(key)
          .build();

  CertificateCodec certCodec =
      new CertificateCodec(config, componentName);
  certCodec.writeCertificate(selfSignedCertificate);
}
 
Example #7
Source File: OcspRef.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public List<X509Certificate> getAssociatedCertificates() {
   List<X509Certificate> result = new ArrayList();
   X509CertificateHolder[] arr$ = this.ocsp.getCerts();
   int len$ = arr$.length;

   for(int i$ = 0; i$ < len$; ++i$) {
      X509CertificateHolder certificateHolder = arr$[i$];

      try {
         result.add((new JcaX509CertificateConverter()).setProvider("BC").getCertificate(certificateHolder));
      } catch (CertificateException var7) {
         throw new IllegalArgumentException(var7);
      }
   }

   return result;
}
 
Example #8
Source File: CertUtils.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public static X509Certificate generateV1Certificate(final KeyPair keyPair,
                                                    final String subject,
                                                    final String issuer,
                                                    final int validityYears,
                                                    final String signatureAlgorithm) throws CertificateException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException, InvalidKeyException, OperatorCreationException {
    final DateTime now = DateTime.now(DateTimeZone.UTC);
    final X509v1CertificateBuilder certBuilder = new JcaX509v1CertificateBuilder(
            new X500Name(issuer),
            generateRandomBigInt(),
            now.minusDays(1).toDate(),
            now.plusYears(validityYears).toDate(),
            new X500Name(subject),
            keyPair.getPublic());
    final ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).setProvider("BC").build(keyPair.getPrivate());
    final X509CertificateHolder certHolder = certBuilder.build(signer);
    return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder);
}
 
Example #9
Source File: SFTrustManager.java    From snowflake-jdbc with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a OCSP Request
 *
 * @param pairIssuerSubject a pair of issuer and subject certificates
 * @return OCSPReq object
 */
private OCSPReq createRequest(
    SFPair<Certificate, Certificate> pairIssuerSubject) throws IOException
{
  Certificate issuer = pairIssuerSubject.left;
  Certificate subject = pairIssuerSubject.right;
  OCSPReqBuilder gen = new OCSPReqBuilder();
  try
  {
    DigestCalculator digest = new SHA1DigestCalculator();
    X509CertificateHolder certHolder = new X509CertificateHolder(issuer.getEncoded());
    CertificateID certId = new CertificateID(
        digest, certHolder, subject.getSerialNumber().getValue());
    gen.addRequest(certId);
    return gen.build();
  }
  catch (OCSPException ex)
  {
    throw new IOException("Failed to build a OCSPReq.", ex);
  }
}
 
Example #10
Source File: CreateMultipleVisualizations.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * Copy of <code>org.apache.pdfbox.examples.signature.CreateSignatureBase.sign(InputStream)</code>
 * from the pdfbox examples artifact.
 */
@Override
public byte[] sign(InputStream content) throws IOException {
    try
    {
        List<Certificate> certList = new ArrayList<>();
        certList.addAll(Arrays.asList(chain));
        Store<?> certs = new JcaCertStore(certList);
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        org.bouncycastle.asn1.x509.Certificate cert = org.bouncycastle.asn1.x509.Certificate.getInstance(chain[0].getEncoded());
        ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA256WithRSA").build(pk);
        gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()).build(sha1Signer, new X509CertificateHolder(cert)));
        gen.addCertificates(certs);
        CMSProcessableInputStream msg = new CMSProcessableInputStream(content);
        CMSSignedData signedData = gen.generate(msg, false);
        return signedData.getEncoded();
    }
    catch (GeneralSecurityException | CMSException | OperatorCreationException e)
    {
        throw new IOException(e);
    }
}
 
Example #11
Source File: RsaSsaPss.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * This specific doesn't verify in combination with its document, so
 * I wanted to look at its contents. As RSASSA-PSS does not allow to
 * read the original hash from the decrypted signature bytes, this
 * did not help at all.
 */
@Test
public void testDecryptSLMBC_PSS_Test1() throws IOException, CMSException, GeneralSecurityException
{
    Cipher cipherNoPadding = Cipher.getInstance("RSA/ECB/NoPadding");
    KeyFactory rsaKeyFactory = KeyFactory.getInstance("RSA");

    try (   InputStream resource = getClass().getResourceAsStream("SLMBC-PSS-Test1.cms")    )
    {
        CMSSignedData cmsSignedData = new CMSSignedData(resource);
        for (SignerInformation signerInformation : (Iterable<SignerInformation>)cmsSignedData.getSignerInfos().getSigners())
        {
            Collection<X509CertificateHolder> x509CertificateHolders = cmsSignedData.getCertificates().getMatches(signerInformation.getSID());
            if (x509CertificateHolders.size() != 1)
            {
                Assert.fail("Cannot uniquely determine signer certificate.");
            }
            X509CertificateHolder x509CertificateHolder = x509CertificateHolders.iterator().next();
            PublicKey publicKey = rsaKeyFactory.generatePublic(new X509EncodedKeySpec(x509CertificateHolder.getSubjectPublicKeyInfo().getEncoded()));
            cipherNoPadding.init(Cipher.DECRYPT_MODE, publicKey);
            byte[] bytes = cipherNoPadding.doFinal(signerInformation.getSignature());

            Files.write(new File(RESULT_FOLDER, "SLMBC-PSS-Test1-signature-decoded").toPath(), bytes);
        }
    }
}
 
Example #12
Source File: KeyStoreHelperTest.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Nonnull
private static X509Certificate _createX509V1Certificate (final KeyPair aKeyPair) throws Exception
{
  // generate the certificate
  final PublicKey aPublicKey = aKeyPair.getPublic ();
  final PrivateKey aPrivateKey = aKeyPair.getPrivate ();
  final ContentSigner aContentSigner = new JcaContentSignerBuilder ("SHA256WithRSA").setProvider (PBCProvider.getProvider ())
                                                                                    .build (aPrivateKey);

  final X509CertificateHolder aCertHolder = new JcaX509v1CertificateBuilder (new X500Principal ("CN=Test Certificate"),
                                                                             BigInteger.valueOf (System.currentTimeMillis ()),
                                                                             new Date (System.currentTimeMillis () -
                                                                                       50000),
                                                                             new Date (System.currentTimeMillis () +
                                                                                       50000),
                                                                             new X500Principal ("CN=Test Certificate"),
                                                                             aPublicKey).build (aContentSigner);
  // Convert to JCA X509Certificate
  return new JcaX509CertificateConverter ().getCertificate (aCertHolder);
}
 
Example #13
Source File: SslInitializerTestUtils.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * Signs the given key pair with the given self signed certificate to generate a certificate with
 * the given validity range.
 *
 * @return signed public key (of the key pair) certificate
 */
public static X509Certificate signKeyPair(
    SelfSignedCaCertificate ssc, KeyPair keyPair, String hostname, Date from, Date to)
    throws Exception {
  X500Name subjectDnName = new X500Name("CN=" + hostname);
  BigInteger serialNumber = BigInteger.valueOf(System.currentTimeMillis());
  X500Name issuerDnName = new X500Name(ssc.cert().getIssuerDN().getName());
  ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(ssc.key());
  X509v3CertificateBuilder v3CertGen =
      new JcaX509v3CertificateBuilder(
          issuerDnName, serialNumber, from, to, subjectDnName, keyPair.getPublic());

  X509CertificateHolder certificateHolder = v3CertGen.build(sigGen);
  return new JcaX509CertificateConverter()
      .setProvider(PROVIDER)
      .getCertificate(certificateHolder);
}
 
Example #14
Source File: TimeStampValidatorImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public void validateTimeStampToken(TimeStampToken tsToken) throws InvalidTimeStampException, TechnicalConnectorException {
   Validate.notNull(this.keyStore, "keyStore is not correctly initialised.");
   Validate.notNull(this.aliases, "aliases is not correctly initialised.");
   Validate.notNull(tsToken, "Parameter tsToken value is not nullable.");
   TimeStampTokenInfo timeStampInfo = tsToken.getTimeStampInfo();
   if (timeStampInfo != null) {
      LOG.debug("Validating TimeStampToken with SerialNumber [" + timeStampInfo.getSerialNumber() + "]");
      if (timeStampInfo.getTsa() != null) {
         X500Name name = (X500Name)timeStampInfo.getTsa().getName();
         LOG.debug("Validating Timestamp against TrustStore Looking for [" + name + "].");
      }
   }

   boolean signatureValid = false;
   Exception lastException = null;
   Iterator i$ = this.aliases.iterator();

   while(i$.hasNext()) {
      String alias = (String)i$.next();

      try {
         X509Certificate ttsaCert = (X509Certificate)this.keyStore.getCertificate(alias);
         LOG.debug("Trying to validate timestamp against certificate with alias [" + alias + "] : [" + ttsaCert.getSubjectX500Principal().getName("RFC1779") + "]");
         X509CertificateHolder tokenSigner = new X509CertificateHolder(ttsaCert.getEncoded());
         SignerInformationVerifier verifier = (new BcRSASignerInfoVerifierBuilder(new DefaultCMSSignatureAlgorithmNameGenerator(), new DefaultSignatureAlgorithmIdentifierFinder(), new DefaultDigestAlgorithmIdentifierFinder(), new BcDigestCalculatorProvider())).build(tokenSigner);
         tsToken.validate(verifier);
         signatureValid = true;
         break;
      } catch (Exception var10) {
         lastException = var10;
         LOG.debug("TimeStampToken not valid with certificate-alias [" + alias + "]: " + var10.getMessage());
      }
   }

   if (!signatureValid) {
      throw new InvalidTimeStampException("timestamp is not valid ", lastException);
   } else {
      LOG.debug("timestampToken is valid");
   }
}
 
Example #15
Source File: CertificateUtils.java    From nifi-registry 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 #16
Source File: TestUtil.java    From fabric-chaincode-java with Apache License 2.0 5 votes vote down vote up
/**
 * Function to create a certificate with dummy attributes
 *
 * @param attributeValue {String} value to be written to the identity attributes
 *                       section of the certificate
 * @return encodedCert {String} encoded certificate with re-written attributes
 */
public static String createCertWithIdentityAttributes(final String attributeValue) throws Exception {

    // Use existing certificate with attributes
    final byte[] decodedCert = Base64.getDecoder().decode(CERT_MULTIPLE_ATTRIBUTES);
    // Create a certificate holder and builder
    final X509CertificateHolder certHolder = new X509CertificateHolder(decodedCert);
    final X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(certHolder);

    // special OID used by Fabric to save attributes in x.509 certificates
    final String fabricCertOid = "1.2.3.4.5.6.7.8.1";
    // Write the new attribute value
    final byte[] extDataToWrite = attributeValue.getBytes();
    certBuilder.replaceExtension(new ASN1ObjectIdentifier(fabricCertOid), true, extDataToWrite);

    // Create a privateKey
    final KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
    generator.initialize(384);
    final KeyPair keyPair = generator.generateKeyPair();

    // Create and build the Content Signer
    final JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder("SHA256withECDSA");
    final ContentSigner contentSigner = contentSignerBuilder.build(keyPair.getPrivate());
    // Build the Certificate from the certificate builder
    final X509CertificateHolder builtCert = certBuilder.build(contentSigner);
    final X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X509")
            .generateCertificate(new ByteArrayInputStream(builtCert.getEncoded()));
    final String encodedCert = Base64.getEncoder().encodeToString(certificate.getEncoded());
    return encodedCert;
}
 
Example #17
Source File: TLSCertificateBuilder.java    From fabric-sdk-java with 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 #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: KeyStoreUtil.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public static KeyStore createTrustStore(String serverCert) throws Exception {
    try (Reader reader = new StringReader(serverCert)) {
        try (PEMParser pemParser = new PEMParser(reader)) {
            X509CertificateHolder certificateHolder = (X509CertificateHolder) pemParser.readObject();
            Certificate caCertificate = new JcaX509CertificateConverter().getCertificate(certificateHolder);

            KeyStore trustStore = KeyStore.getInstance("JKS");
            trustStore.load(null);
            trustStore.setCertificateEntry("ca", caCertificate);
            return trustStore;
        }
    }
}
 
Example #20
Source File: CertificateManagerTest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * {@link CertificateManager#getServerIdentities(X509Certificate)} should return:
 * <ul>
 *     <li>the DNS subjectAltName value</li>
 *     <li>explicitly not the Common Name</li>
 * </ul>
 *
 * when a certificate contains:
 * <ul>
 *     <li>a subjectAltName entry of type DNS </li>
 * </ul>
 */
@Test
public void testServerIdentitiesDNS() throws Exception
{
    // Setup fixture.
    final String subjectCommonName = "MySubjectCommonName";
    final String subjectAltNameDNS = "MySubjectAltNameDNS";

    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 GeneralNames generalNames = new GeneralNames(new GeneralName(GeneralName.dNSName, subjectAltNameDNS));

    builder.addExtension( Extension.subjectAlternativeName, false, generalNames );

    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( subjectAltNameDNS ) );
    assertFalse( serverIdentities.contains( subjectCommonName ) );
}
 
Example #21
Source File: TestHddsSecureDatanodeInit.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
  testDir = GenericTestUtils.getRandomizedTestDir();
  conf = new OzoneConfiguration();
  conf.set(HddsConfigKeys.OZONE_METADATA_DIRS, testDir.getPath());
  //conf.set(ScmConfigKeys.OZONE_SCM_NAMES, "localhost");
  String volumeDir = testDir + "/disk1";
  conf.set(DFSConfigKeysLegacy.DFS_DATANODE_DATA_DIR_KEY, volumeDir);

  conf.setBoolean(OZONE_SECURITY_ENABLED_KEY, true);
  conf.setClass(OzoneConfigKeys.HDDS_DATANODE_PLUGINS_KEY,
      TestHddsDatanodeService.MockService.class,
      ServicePlugin.class);
  securityConfig = new SecurityConfig(conf);

  service = HddsDatanodeService.createHddsDatanodeService(args);
  dnLogs = GenericTestUtils.LogCapturer.captureLogs(getLogger());
  callQuietly(() -> {
    service.start(conf);
    return null;
  });
  callQuietly(() -> {
    service.initializeCertificateClient(conf);
    return null;
  });
  certCodec = new CertificateCodec(securityConfig, DN_COMPONENT);
  keyCodec = new KeyCodec(securityConfig, DN_COMPONENT);
  dnLogs.clearOutput();
  privateKey = service.getCertificateClient().getPrivateKey();
  publicKey = service.getCertificateClient().getPublicKey();
  X509Certificate x509Certificate = null;

  x509Certificate = KeyStoreTestUtil.generateCertificate(
      "CN=Test", new KeyPair(publicKey, privateKey), 10,
      securityConfig.getSignatureAlgo());
  certHolder = new X509CertificateHolder(x509Certificate.getEncoded());

}
 
Example #22
Source File: DSSUtilsTest.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void loadEdDSACert() throws NoSuchAlgorithmException, IOException {

	// RFC 8410

	Security.addProvider(DSSSecurityProvider.getSecurityProvider());
	
	CertificateToken token = DSSUtils.loadCertificateFromBase64EncodedString(
			"MIIBLDCB36ADAgECAghWAUdKKo3DMDAFBgMrZXAwGTEXMBUGA1UEAwwOSUVURiBUZXN0IERlbW8wHhcNMTYwODAxMTIxOTI0WhcNNDAxMjMxMjM1OTU5WjAZMRcwFQYDVQQDDA5JRVRGIFRlc3QgRGVtbzAqMAUGAytlbgMhAIUg8AmJMKdUdIt93LQ+91oNvzoNJjga9OukqY6qm05qo0UwQzAPBgNVHRMBAf8EBTADAQEAMA4GA1UdDwEBAAQEAwIDCDAgBgNVHQ4BAQAEFgQUmx9e7e0EM4Xk97xiPFl1uQvIuzswBQYDK2VwA0EAryMB/t3J5v/BzKc9dNZIpDmAgs3babFOTQbs+BolzlDUwsPrdGxO3YNGhW7Ibz3OGhhlxXrCe1Cgw1AH9efZBw==");
	assertNotNull(token);
	logger.info("{}", token);
	logger.info("{}", token.getPublicKey());
	assertFalse(token.isSelfSigned());
	assertFalse(token.isSignedBy(token));
	assertEquals(SignatureAlgorithm.ED25519, token.getSignatureAlgorithm());
	assertTrue(token.checkKeyUsage(KeyUsageBit.KEY_AGREEMENT));
	assertEquals(EncryptionAlgorithm.X25519, EncryptionAlgorithm.forKey(token.getPublicKey()));

	X509CertificateHolder holder = new X509CertificateHolder(token.getEncoded());
	SubjectPublicKeyInfo subjectPublicKeyInfo = holder.getSubjectPublicKeyInfo();
	assertNotNull(subjectPublicKeyInfo);
	assertEquals(EncryptionAlgorithm.X25519.getOid(), subjectPublicKeyInfo.getAlgorithm().getAlgorithm().getId());

	token = DSSUtils
			.loadCertificateFromBase64EncodedString(
			"MIIBCDCBuwIUGW78zw0OL0GptJi++a91dBa7DsQwBQYDK2VwMCcxCzAJBgNVBAYTAkRFMRgwFgYDVQQDDA93d3cuZXhhbXBsZS5jb20wHhcNMTkwMzMxMTc1MTIyWhcNMjEwMjI4MTc1MTIyWjAnMQswCQYDVQQGEwJERTEYMBYGA1UEAwwPd3d3LmV4YW1wbGUuY29tMCowBQYDK2VwAyEAK87g0b8CC1eA5mvKXt9uezZwJYWEyg74Y0xTZEkqCcwwBQYDK2VwA0EAIIu/aa3Qtr3IE5to/nvWVY9y3ciwG5DnA70X3ALUhFs+U5aLtfY8sNT1Ng72ht+UBwByuze20UsL9qMsmknQCA==");
	assertNotNull(token);
	logger.info("{}", token);
	logger.info("{}", token.getPublicKey());
	assertEquals(SignatureAlgorithm.ED25519, token.getSignatureAlgorithm());
	assertEquals(EncryptionAlgorithm.ED25519, EncryptionAlgorithm.forKey(token.getPublicKey()));
	assertTrue(token.isSelfSigned());
	assertTrue(token.isSignedBy(token));
}
 
Example #23
Source File: CMSSignedDataWrapper.java    From Websocket-Smart-Card-Signer with GNU Affero General Public License v3.0 5 votes vote down vote up
public void addCert(Store<X509CertificateHolder> certStore) throws Exception {
    if (certStore == null)
        return;
    Collection<X509CertificateHolder> certStoreList = certStore.getMatches(null);
    for (X509CertificateHolder cert : certStoreList)
        addCert(cert.getEncoded());
}
 
Example #24
Source File: CertificateGenerator.java    From NetBare with 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 #25
Source File: HttpsHelper.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
public static KeyStore createTrustStore(final String certPath)
        throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException {
    Path caPath = Paths.get(certPath, "ca.pem");
    BufferedReader reader = Files.newBufferedReader(caPath, Charset.defaultCharset());

    PEMParser parser = new PEMParser(reader);
    X509CertificateHolder object = (X509CertificateHolder) parser.readObject();
    Certificate caCert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(object);

    KeyStore trustStore = KeyStore.getInstance("JKS");
    trustStore.load(null);
    trustStore.setCertificateEntry("ca", caCert);
    return trustStore;
}
 
Example #26
Source File: TestDefaultCAServer.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
@Test
public void testRequestCertificateWithInvalidSubjectFailure()
    throws Exception {
  KeyPair keyPair =
      new HDDSKeyGenerator(conf).generateKey();
  PKCS10CertificationRequest csr = new CertificateSignRequest.Builder()
      .addDnsName("hadoop.apache.org")
      .addIpAddress("8.8.8.8")
      .setCA(false)
      .setScmID("wrong one")
      .setClusterID("223432rf")
      .setSubject("Ozone Cluster")
      .setConfiguration(conf)
      .setKey(keyPair)
      .build();

  // Let us convert this to a string to mimic the common use case.
  String csrString = CertificateSignRequest.getEncodedString(csr);

  CertificateServer testCA = new DefaultCAServer("testCA",
      RandomStringUtils.randomAlphabetic(4),
      RandomStringUtils.randomAlphabetic(4), caStore);
  testCA.init(new SecurityConfig(conf),
      CertificateServer.CAType.SELF_SIGNED_CA);

  LambdaTestUtils.intercept(ExecutionException.class, "ScmId and " +
          "ClusterId in CSR subject are incorrect",
      () -> {
        Future<X509CertificateHolder> holder =
            testCA.requestCertificate(csrString,
                CertificateApprover.ApprovalType.TESTING_AUTOMATIC);
        holder.isDone();
        holder.get();
      });
}
 
Example #27
Source File: TestCommand.java    From Launcher with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void invoke(String... args) throws Exception {
    verifyArgs(args, 1);
    if (handler == null)
        handler = new NettyServerSocketHandler(server);
    if (args[0].equals("start")) {
        CommonHelper.newThread("Netty Server", true, handler).start();
    }
    if (args[0].equals("stop")) {
        handler.close();
    }
    if (args[0].equals("genCA")) {
        server.certificateManager.generateCA();
        server.certificateManager.writePrivateKey(Paths.get("ca.key"), server.certificateManager.caKey);
        server.certificateManager.writeCertificate(Paths.get("ca.crt"), server.certificateManager.ca);
    }
    if (args[0].equals("readCA")) {
        server.certificateManager.ca = server.certificateManager.readCertificate(Paths.get("ca.crt"));
        server.certificateManager.caKey = server.certificateManager.readPrivateKey(Paths.get("ca.key"));
    }
    if (args[0].equals("genCert")) {
        verifyArgs(args, 2);
        String name = args[1];
        KeyPair pair = server.certificateManager.generateKeyPair();
        X509CertificateHolder cert = server.certificateManager.generateCertificate(name, pair.getPublic());
        server.certificateManager.writePrivateKey(Paths.get(name.concat(".key")), pair.getPrivate());
        server.certificateManager.writeCertificate(Paths.get(name.concat(".crt")), cert);
    }
}
 
Example #28
Source File: TestDefaultCAServer.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * The most important test of this test suite. This tests that we are able
 * to create a Test CA, creates it own self-Signed CA and then issue a
 * certificate based on a CSR.
 * @throws SCMSecurityException - on ERROR.
 * @throws ExecutionException - on ERROR.
 * @throws InterruptedException - on ERROR.
 * @throws NoSuchProviderException - on ERROR.
 * @throws NoSuchAlgorithmException - on ERROR.
 */
@Test
public void testRequestCertificate() throws IOException,
    ExecutionException, InterruptedException,
    NoSuchProviderException, NoSuchAlgorithmException {
  String scmId =  RandomStringUtils.randomAlphabetic(4);
  String clusterId =  RandomStringUtils.randomAlphabetic(4);
  KeyPair keyPair =
      new HDDSKeyGenerator(conf).generateKey();
  PKCS10CertificationRequest csr = new CertificateSignRequest.Builder()
      .addDnsName("hadoop.apache.org")
      .addIpAddress("8.8.8.8")
      .addServiceName("OzoneMarketingCluster002")
      .setCA(false)
      .setClusterID(clusterId)
      .setScmID(scmId)
      .setSubject("Ozone Cluster")
      .setConfiguration(conf)
      .setKey(keyPair)
      .build();

  // Let us convert this to a string to mimic the common use case.
  String csrString = CertificateSignRequest.getEncodedString(csr);

  CertificateServer testCA = new DefaultCAServer("testCA",
      clusterId, scmId, caStore);
  testCA.init(new SecurityConfig(conf),
      CertificateServer.CAType.SELF_SIGNED_CA);

  Future<X509CertificateHolder> holder = testCA.requestCertificate(csrString,
      CertificateApprover.ApprovalType.TESTING_AUTOMATIC);
  // Right now our calls are synchronous. Eventually this will have to wait.
  assertTrue(holder.isDone());
  assertNotNull(holder.get());
}
 
Example #29
Source File: CertificateGeneratorTest.java    From credhub with Apache License 2.0 5 votes vote down vote up
private X509CertificateHolder makeCert(final KeyPair certKeyPair,
                                       final PrivateKey caPrivateKey,
                                       final X500Name caDn,
                                       final X500Name subjectDn,
                                       final boolean isCa) throws OperatorCreationException, NoSuchAlgorithmException, CertIOException {
  final SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(certKeyPair.getPublic()
    .getEncoded());
  final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256withRSA")
    .setProvider(BouncyCastleFipsProvider.PROVIDER_NAME)
    .build(caPrivateKey);

  final CurrentTimeProvider currentTimeProvider = new CurrentTimeProvider();

  final Instant now = Instant.from(currentTimeProvider.getInstant());

  final X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(
    caDn,
    BigInteger.TEN,
    Date.from(now),
    Date.from(now.plus(Duration.ofDays(365))),
    subjectDn,
    publicKeyInfo
  );
  x509v3CertificateBuilder
    .addExtension(Extension.basicConstraints, true, new BasicConstraints(isCa));
  return x509v3CertificateBuilder.build(contentSigner);
}
 
Example #30
Source File: KeystoreUtils.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public static KeyStore createTrustStore(final String serverCert) throws Exception {
    StringReader reader = new StringReader(serverCert);
    try (PEMParser pemParser = new PEMParser(reader)) {
        X509CertificateHolder certificateHolder = (X509CertificateHolder) pemParser.readObject();
        Certificate caCertificate = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);

        KeyStore trustStore = KeyStore.getInstance("JKS");
        trustStore.load(null);
        trustStore.setCertificateEntry("ca", caCertificate);
        return trustStore;
    }
}