Java Code Examples for org.bouncycastle.cert.X509CertificateHolder

The following examples show how to use org.bouncycastle.cert.X509CertificateHolder. 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: netty-4.1.22   Source File: OcspServerExample.java    License: 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 2
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 3
Source Project: hadoop-ozone   Source File: DefaultCAServer.java    License: 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 4
/**
 * 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 5
/**
 * 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 6
Source Project: nomulus   Source File: SslInitializerTestUtils.java    License: 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 7
Source Project: hadoop-ozone   Source File: TestDefaultCAServer.java    License: 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 8
Source Project: ph-commons   Source File: KeyStoreHelperTest.java    License: 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 9
Source Project: Spark   Source File: IdentityController.java    License: 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 10
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 11
Source Project: cloudstack   Source File: CertUtils.java    License: 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 12
Source Project: snowflake-jdbc   Source File: SFTrustManager.java    License: 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 13
Source Project: Launcher   Source File: CertificateManager.java    License: 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 14
Source Project: hadoop-ozone   Source File: TestHddsSecureDatanodeInit.java    License: 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 15
Source Project: xipki   Source File: ScepUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void addCmsCertSet(CMSSignedDataGenerator generator, X509Cert[] cmsCertSet)
    throws CertificateEncodingException, CMSException {
  if (cmsCertSet == null || cmsCertSet.length == 0) {
    return;
  }
  Args.notNull(generator, "geneator");
  Collection<X509CertificateHolder> certColl = new LinkedList<>();
  for (X509Cert m : cmsCertSet) {
    certColl.add(m.toBcCert());
  }

  JcaCertStore certStore = new JcaCertStore(certColl);
  generator.addCertificates(certStore);
}
 
Example 16
Source Project: ranger   Source File: AzureKeyVaultClientAuthenticator.java    License: Apache License 2.0 5 votes vote down vote up
private KeyCert readPem(String path, String password) throws IOException, CertificateException, OperatorCreationException, PKCSException {
	Security.addProvider(new BouncyCastleProvider());
	PEMParser pemParser = new PEMParser(new FileReader(new File(path)));
	PrivateKey privateKey = null;
	X509Certificate cert = null;
	Object object = pemParser.readObject();
	
	while (object != null) {
		JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
		if (object instanceof X509CertificateHolder) {
			cert = new JcaX509CertificateConverter().getCertificate((X509CertificateHolder) object);
		}
		if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
			PKCS8EncryptedPrivateKeyInfo pinfo = (PKCS8EncryptedPrivateKeyInfo) object;
			InputDecryptorProvider provider = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(password.toCharArray());
			PrivateKeyInfo info = pinfo.decryptPrivateKeyInfo(provider);
			privateKey = converter.getPrivateKey(info);
		} 
		if (object instanceof PrivateKeyInfo) {
			privateKey = converter.getPrivateKey((PrivateKeyInfo) object);
		}
		object = pemParser.readObject();
	}
	KeyCert keycert = new KeyCert();
	keycert.setCertificate(cert);
	keycert.setKey(privateKey);
	pemParser.close();
	return keycert;
}
 
Example 17
Source Project: xipki   Source File: DecodedPkiMessage.java    License: Apache License 2.0 5 votes vote down vote up
public static DecodedPkiMessage decode(CMSSignedData pkiMessage, PrivateKey recipientKey,
    X509Cert recipientCert, CollectionStore<X509CertificateHolder> certStore)
    throws MessageDecodingException {
  EnvelopedDataDecryptorInstance decInstance = new EnvelopedDataDecryptorInstance(
      recipientCert, recipientKey);
  EnvelopedDataDecryptor recipient = new EnvelopedDataDecryptor(decInstance);
  return decode(pkiMessage, recipient, certStore);
}
 
Example 18
Source Project: hadoop-ozone   Source File: CertificateCodec.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Helper function to read certificate.
 *
 * @param certificateFile - Full path to certificate file.
 * @return X509CertificateHolder
 * @throws IOException          - On Error.
 * @throws CertificateException - On Error.
 */
private X509CertificateHolder getX509CertificateHolder(File certificateFile)
    throws IOException, CertificateException {
  if (!certificateFile.exists()) {
    throw new IOException("Unable to find the requested certificate. Path: "
        + certificateFile.toString());
  }
  CertificateFactory fact = CertificateFactory.getInstance("X.509");
  try (FileInputStream is = new FileInputStream(certificateFile)) {
    return getCertificateHolder(
        (X509Certificate) fact.generateCertificate(is));
  }
}
 
Example 19
Source Project: nifi   Source File: OcspCertificateValidatorTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generates a signed certificate with a specific keypair.
 *
 * @param dn      the DN
 * @param keyPair the public key will be included in the certificate and the the private key is used to sign the certificate
 * @return the certificate
 * @throws IOException               if an exception occurs
 * @throws NoSuchAlgorithmException  if an exception occurs
 * @throws CertificateException      if an exception occurs
 * @throws NoSuchProviderException   if an exception occurs
 * @throws SignatureException        if an exception occurs
 * @throws InvalidKeyException       if an exception occurs
 * @throws OperatorCreationException if an exception occurs
 */
private static X509Certificate generateCertificate(String dn, KeyPair keyPair) throws IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException, SignatureException,
        InvalidKeyException, OperatorCreationException {
    PrivateKey privateKey = keyPair.getPrivate();
    ContentSigner sigGen = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(PROVIDER).build(privateKey);
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    Date startDate = new Date(YESTERDAY);
    Date endDate = new Date(ONE_YEAR_FROM_NOW);

    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(
            new X500Name(dn),
            BigInteger.valueOf(System.currentTimeMillis()),
            startDate, endDate,
            new X500Name(dn),
            subPubKeyInfo);

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

    // (2) extendedKeyUsage extension
    Vector<KeyPurposeId> ekUsages = new Vector<>();
    ekUsages.add(KeyPurposeId.id_kp_clientAuth);
    ekUsages.add(KeyPurposeId.id_kp_serverAuth);
    certBuilder.addExtension(X509Extension.extendedKeyUsage, false, new ExtendedKeyUsage(ekUsages));

    // Sign the certificate
    X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
    return new JcaX509CertificateConverter().setProvider(PROVIDER)
            .getCertificate(certificateHolder);
}
 
Example 20
Source Project: dss   Source File: TimestampToken.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected SignatureValidity checkIsSignedBy(final CertificateToken candidate) {

	final X509CertificateHolder x509CertificateHolder = DSSASN1Utils.getX509CertificateHolder(candidate);
	if (timeStamp.getSID().match(x509CertificateHolder)) {
		SignerInformationVerifier signerInformationVerifier = getSignerInformationVerifier(candidate);

		// Try firstly to validate as a Timestamp and if that fails try to validate the
		// timestamp as a CMSSignedData
		if (isValidTimestamp(signerInformationVerifier) || isValidCMSSignedData(signerInformationVerifier)) {
			signatureValidity = SignatureValidity.VALID;
			this.tsaX500Principal = candidate.getSubject().getPrincipal();
			SignerInformation signerInformation = timeStamp.toCMSSignedData().getSignerInfos().get(timeStamp.getSID());

			if (SignatureAlgorithm.RSA_SSA_PSS_SHA1_MGF1.getOid().equals(signerInformation.getEncryptionAlgOID())) {
				signatureAlgorithm = SignatureAlgorithm.forOidAndParams(signerInformation.getEncryptionAlgOID(),
						signerInformation.getEncryptionAlgParams());
			} else {
				EncryptionAlgorithm encryptionAlgorithm = EncryptionAlgorithm.forName(candidate.getPublicKey().getAlgorithm());
				final AlgorithmIdentifier hashAlgorithm = signerInformation.getDigestAlgorithmID();
				final DigestAlgorithm digestAlgorithm = DigestAlgorithm.forOID(hashAlgorithm.getAlgorithm().getId());
				signatureAlgorithm = SignatureAlgorithm.getAlgorithm(encryptionAlgorithm, digestAlgorithm);
			}
		} else {
			signatureValidity = SignatureValidity.INVALID;
		}

		return signatureValidity;
	}
	return SignatureValidity.INVALID;
}
 
Example 21
Source Project: littleca   Source File: CertUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 创建ca私钥签名证书
 *
 * @param publicKey
 * @param privateKey
 * @param issuerDN
 * @param userDN
 * @param notBefore
 * @param notAfter
 * @param serialNumber
 * @param signAlg
 * @return
 * @throws CertException
 */
public static X509Certificate makeUserCert(PublicKey publicKey, PublicKey caPublicKey, PrivateKey caPrivateKey, String issuerDN,
                                           String userDN, Date notBefore, Date notAfter, BigInteger serialNumber, String signAlg)
        throws CertException {
    try {
        if (null == signAlg) {
            throw new CertException(signAlg + " can't be null");
        }

        X500Name issuer = new X500Name(issuerDN);
        //1. 创建签名
        ContentSigner signer = new JcaContentSignerBuilder(signAlg)
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(caPrivateKey);
        //2. 创建证书请求
        PKCS10CertificationRequestBuilder pkcs10CertificationRequestBuilder = new JcaPKCS10CertificationRequestBuilder(new X500Name(userDN), publicKey);
        PKCS10CertificationRequest pkcs10CertificationRequest = pkcs10CertificationRequestBuilder.build(signer);
        //3. 创建证书
        //SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());

        SubjectPublicKeyInfo subPubKeyInfo = pkcs10CertificationRequest.getSubjectPublicKeyInfo();
        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, serialNumber,
                notBefore, notAfter, pkcs10CertificationRequest.getSubject(), subPubKeyInfo);
        //添加扩展信息 见 X509CertExtensions
        X509CertExtensions.buildAllExtensions(certBuilder, publicKey, caPublicKey);
        X509CertificateHolder holder = certBuilder.build(signer);
        return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME)
                .getCertificate(holder);
    } catch (Exception e) {
        throw new CertException("makeUserCert failed", e);
    }
}
 
Example 22
Source Project: hadoop-ozone   Source File: DefaultCAServer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public X509CertificateHolder getCACertificate() throws IOException {
  CertificateCodec certificateCodec =
      new CertificateCodec(config, componentName);
  try {
    return certificateCodec.readCertificate();
  } catch (CertificateException e) {
    throw new IOException(e);
  }
}
 
Example 23
Source Project: hadoop-ozone   Source File: DefaultCAServer.java    License: Apache License 2.0 5 votes vote down vote up
private X509CertificateHolder signAndStoreCertificate(LocalDate beginDate,
    LocalDate endDate, PKCS10CertificationRequest csr) throws IOException,
    OperatorCreationException, CertificateException {
  X509CertificateHolder xcert = approver.sign(config,
      getCAKeys().getPrivate(),
      getCACertificate(), java.sql.Date.valueOf(beginDate),
      java.sql.Date.valueOf(endDate), csr, scmID, clusterID);
  store.storeValidCertificate(xcert.getSerialNumber(),
      CertificateCodec.getX509Certificate(xcert));
  return xcert;
}
 
Example 24
Source Project: dss   Source File: DSSASN1UtilsTest.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void getCertificateHolder() {
	CertificateToken token = DSSUtils.loadCertificate(new File("src/test/resources/ec.europa.eu.crt"));
	X509CertificateHolder certificateHolder = DSSASN1Utils.getX509CertificateHolder(token);
	assertNotNull(certificateHolder);
	CertificateToken token2 = DSSASN1Utils.getCertificate(certificateHolder);
	assertEquals(token, token2);
}
 
Example 25
public static boolean verifyAllSignatures(CMSSignedData cmsSignedData) {
    try {
        if (Security.getProvider("BC") == null)
            Security.addProvider(new BouncyCastleProvider());

        Collection<SignerInformation> signers = cmsSignedData.getSignerInfos().getSigners();

        for (SignerInformation si : signers) {
            @SuppressWarnings("unchecked")
            Collection<X509CertificateHolder> certList = cmsSignedData.getCertificates().getMatches(si.getSID());
            if (certList.size() == 0)
                throw new Exception("ERROR: Impossible to find a Certificate using the Signer ID: " + si.getSID());

            X509CertificateHolder cert = certList.iterator().next(); // Take only the first certificate of the chain

            if (!si.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert)))
                throw new Exception("ATTENTION: At least a signature is invalid!");

            boolean certOK = true;
            String msg = "";
            try {
                X509Utils.checkAllOnCertificate(X509Utils.getX509Certificate(cert.getEncoded()));
            } catch (Exception ex) {
                msg = ex.getMessage();
                certOK = false;
            }
            if (!certOK)
                throw new Exception("ATTENTION: The certificate is invalid:\n" + msg);
        }

        return true;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return false;
}
 
Example 26
Source Project: oxAuth   Source File: OxAuthCryptoProvider.java    License: MIT License 5 votes vote down vote up
public X509Certificate generateV3Certificate(KeyPair keyPair, String issuer, String signatureAlgorithm, Long expirationTime) throws CertIOException, OperatorCreationException, CertificateException {
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();

    // Signers name
    X500Name issuerName = new X500Name(issuer);

    // Subjects name - the same as we are self signed.
    X500Name subjectName = new X500Name(issuer);

    // Serial
    BigInteger serial = new BigInteger(256, new SecureRandom());

    // Not before
    Date notBefore = new Date(System.currentTimeMillis() - 10000);
    Date notAfter = new Date(expirationTime);

    // Create the certificate - version 3
    JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerName, serial, notBefore, notAfter, subjectName, publicKey);

    ASN1EncodableVector purposes = new ASN1EncodableVector();
    purposes.add(KeyPurposeId.id_kp_serverAuth);
    purposes.add(KeyPurposeId.id_kp_clientAuth);
    purposes.add(KeyPurposeId.anyExtendedKeyUsage);

    ASN1ObjectIdentifier extendedKeyUsage = new ASN1ObjectIdentifier("2.5.29.37").intern();
    builder.addExtension(extendedKeyUsage, false, new DERSequence(purposes));

    ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).setProvider("BC").build(privateKey);
    X509CertificateHolder holder = builder.build(signer);
    X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(holder);

    return cert;
}
 
Example 27
Source Project: nexus-public   Source File: CertificateUtil.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Decodes a PEM formatted certificate.
 *
 * @param pemFormattedCertificate text to be decoded as a PEM certificate.
 * @return the Certificate decoded from the input text.
 * @throws CertificateParsingException
 *          thrown if the PEM formatted string cannot be parsed into a Certificate.
 */
public static Certificate decodePEMFormattedCertificate(final String pemFormattedCertificate)
    throws CertificateException
{
  log.trace("Parsing PEM formatted certificate string:\n{}", pemFormattedCertificate);

  // make sure we have something to parse
  if (pemFormattedCertificate != null) {
    StringReader stringReader = new StringReader(pemFormattedCertificate);

    try (PEMParser pemReader = new PEMParser(stringReader)) {
      Object object = pemReader.readObject();
      log.trace("Object found while paring PEM formatted string: {}", object);

      if (object instanceof X509CertificateHolder) {
        X509CertificateHolder holder = (X509CertificateHolder)object;
        JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
        return converter.getCertificate(holder);
      }
    }
    catch (IOException e) {
      throw new CertificateParsingException(
          "Failed to parse valid certificate from expected PEM formatted certificate:\n"
              + pemFormattedCertificate, e);
    }
  }

  // cert was not a valid object
  throw new CertificateParsingException(
      "Failed to parse valid certificate from expected PEM formatted certificate:\n" + pemFormattedCertificate);
}
 
Example 28
Source Project: docker-maven-plugin   Source File: HttpsHelper.java    License: Apache License 2.0 5 votes vote down vote up
private static Certificate loadCertificate(final String certPath) throws IOException, CertificateException {
    Path cert = Paths.get(certPath, "cert.pem");
    BufferedReader reader = Files.newBufferedReader(cert, Charset.defaultCharset());
    PEMParser parser = new PEMParser(reader);

    X509CertificateHolder object = (X509CertificateHolder) parser.readObject();
    return new JcaX509CertificateConverter().setProvider("BC").getCertificate(object);
}
 
Example 29
private void extractChain(SignatureVerificationResult result, CMSSignedData signedData) throws CertificateException {
   Store<X509CertificateHolder> certs = signedData.getCertificates();
   Collection<X509CertificateHolder> certCollection = certs.getMatches(new CmsSignatureBuilder.X509CertifcateSelector());
   Iterator iterator = certCollection.iterator();

   while(iterator.hasNext()) {
      result.getCertChain().add(converter.getCertificate((X509CertificateHolder)iterator.next()));
   }

}
 
Example 30
Source Project: hadoop-ozone   Source File: TestCertificateCodec.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This test converts a X509Certificate Holder object to a PEM encoded String,
 * then creates a new X509Certificate object to verify that we are able to
 * serialize and deserialize correctly. we follow up with converting these
 * objects to standard JCA x509Certificate objects.
 *
 * @throws NoSuchProviderException  - on Error.
 * @throws NoSuchAlgorithmException - on Error.
 * @throws IOException              - on Error.
 * @throws SCMSecurityException     - on Error.
 * @throws CertificateException     - on Error.
 */
@Test
public void testGetPEMEncodedString()
    throws NoSuchProviderException, NoSuchAlgorithmException,
    IOException, SCMSecurityException, CertificateException {
  HDDSKeyGenerator keyGenerator =
      new HDDSKeyGenerator(conf);
  X509CertificateHolder cert =
      SelfSignedCertificate.newBuilder()
          .setSubject(RandomStringUtils.randomAlphabetic(4))
          .setClusterID(RandomStringUtils.randomAlphabetic(4))
          .setScmID(RandomStringUtils.randomAlphabetic(4))
          .setBeginDate(LocalDate.now())
          .setEndDate(LocalDate.now().plus(1, ChronoUnit.DAYS))
          .setConfiguration(keyGenerator.getSecurityConfig()
              .getConfiguration())
          .setKey(keyGenerator.generateKey())
          .makeCA()
          .build();
  CertificateCodec codec = new CertificateCodec(securityConfig, COMPONENT);
  String pemString = codec.getPEMEncodedString(cert);
  assertTrue(pemString.startsWith(CertificateCodec.BEGIN_CERT));
  assertTrue(pemString.endsWith(CertificateCodec.END_CERT + "\n"));

  // Read back the certificate and verify that all the comparisons pass.
  X509CertificateHolder newCert =
      codec.getCertificateHolder(codec.getX509Certificate(pemString));
  assertEquals(cert, newCert);

  // Just make sure we can decode both these classes to Java Std. lIb classes.
  X509Certificate firstCert = CertificateCodec.getX509Certificate(cert);
  X509Certificate secondCert = CertificateCodec.getX509Certificate(newCert);
  assertEquals(firstCert, secondCert);
}