Java Code Examples for org.bouncycastle.operator.jcajce.JcaContentSignerBuilder

The following examples show how to use org.bouncycastle.operator.jcajce.JcaContentSignerBuilder. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: hadoop-ozone   Source File: TestDefaultProfile.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Generates an CSR with the extension specified.
 * This function is used to get an Invalid CSR and test that PKI profile
 * rejects these invalid extensions, Hence the function name, by itself it
 * is a well formed CSR, but our PKI profile will treat it as invalid CSR.
 *
 * @param kPair - Key Pair.
 * @return CSR  - PKCS10CertificationRequest
 * @throws OperatorCreationException - on Error.
 */
private PKCS10CertificationRequest getInvalidCSR(KeyPair kPair,
    Extensions extensions) throws OperatorCreationException {
  X500NameBuilder namebuilder =
      new X500NameBuilder(X500Name.getDefaultStyle());
  namebuilder.addRDN(BCStyle.CN, "invalidCert");
  PKCS10CertificationRequestBuilder p10Builder =
      new JcaPKCS10CertificationRequestBuilder(namebuilder.build(),
          keyPair.getPublic());
  p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
      extensions);
  JcaContentSignerBuilder csBuilder =
      new JcaContentSignerBuilder(this.securityConfig.getSignatureAlgo());
  ContentSigner signer = csBuilder.build(keyPair.getPrivate());
  return p10Builder.build(signer);
}
 
Example 2
Source Project: Hands-On-Cryptography-with-Java   Source File: KeyStoreDemo.java    License: MIT License 6 votes vote down vote up
/**
 * It's annoying to have to wrap KeyPairs with Certificates, but this is
 * "easier" for you to know who the key belongs to.
 *
 * @param keyPair A KeyPair to wrap
 * @return A wrapped certificate with constant name
 * @throws CertificateException
 * @throws OperatorCreationException
 */
public static Certificate generateCertificate(KeyPair keyPair) throws CertificateException, OperatorCreationException {
    X500Name name = new X500Name("cn=Annoying Wrapper");
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    final Date start = new Date();
    final Date until = Date.from(LocalDate.now().plus(365, ChronoUnit.DAYS).atStartOfDay().toInstant(ZoneOffset.UTC));
    final X509v3CertificateBuilder builder = new X509v3CertificateBuilder(name,
            new BigInteger(10, new SecureRandom()), //Choose something better for real use
            start,
            until,
            name,
            subPubKeyInfo
    );
    ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA").setProvider(new BouncyCastleProvider()).build(keyPair.getPrivate());
    final X509CertificateHolder holder = builder.build(signer);

    Certificate cert = new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider()).getCertificate(holder);
    return cert;
}
 
Example 3
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 4
Source Project: nifi   Source File: OcspCertificateValidatorTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Generates a certificate with a specific public key signed by the issuer key.
 *
 * @param dn        the subject DN
 * @param publicKey the subject public key
 * @param issuerDn  the issuer DN
 * @param issuerKey the issuer private key
 * @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 generateIssuedCertificate(String dn, PublicKey publicKey, String issuerDn, PrivateKey issuerKey) throws IOException, NoSuchAlgorithmException,
        CertificateException, NoSuchProviderException, SignatureException, InvalidKeyException, OperatorCreationException {
    ContentSigner sigGen = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(PROVIDER).build(issuerKey);
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
    Date startDate = new Date(YESTERDAY);
    Date endDate = new Date(ONE_YEAR_FROM_NOW);

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

    X509CertificateHolder certificateHolder = v3CertGen.build(sigGen);
    return new JcaX509CertificateConverter().setProvider(PROVIDER)
            .getCertificate(certificateHolder);
}
 
Example 5
Source Project: littleca   Source File: CAImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public PKCS10CertificationRequest makeUserCertReq(PublicKey publicKey, String userDN, String signAlg) throws CertException {
    try {
        PKCS10CertificationRequestBuilder builder = new PKCS10CertificationRequestBuilder(new X500Name(userDN)
                ,SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()));
        if(null==signAlg) {
        	signAlg=DEFAULT_SIGN_ALG;
        }
        JcaContentSignerBuilder jcaBuilder = new JcaContentSignerBuilder(signAlg);
        jcaBuilder.setProvider(BouncyCastleProvider.PROVIDER_NAME);
        ContentSigner contentSigner = jcaBuilder.build(privateKey);
        PKCS10CertificationRequest certificationRequest = builder.build(contentSigner);
        return certificationRequest;
    } catch (Exception e) {
    	throw new CertException("makeUserCertReq failed",e);
    } 
}
 
Example 6
/**
 * Generates a certificate with a specific public key signed by the issuer key.
 *
 * @param dn        the subject DN
 * @param publicKey the subject public key
 * @param issuerDn  the issuer DN
 * @param issuerKey the issuer private key
 * @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 generateIssuedCertificate(String dn, PublicKey publicKey, String issuerDn, PrivateKey issuerKey) throws IOException, NoSuchAlgorithmException,
        CertificateException, NoSuchProviderException, SignatureException, InvalidKeyException, OperatorCreationException {
    ContentSigner sigGen = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(PROVIDER).build(issuerKey);
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
    Date startDate = new Date(YESTERDAY);
    Date endDate = new Date(ONE_YEAR_FROM_NOW);

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

    X509CertificateHolder certificateHolder = v3CertGen.build(sigGen);
    return new JcaX509CertificateConverter().setProvider(PROVIDER)
            .getCertificate(certificateHolder);
}
 
Example 7
Source Project: java-11-examples   Source File: JCEUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static X509Certificate createSignedCertificate(String issuerName, String subjectName, Date notBefore, Long duration, TimeUnit timeUnit, PublicKey publicKey, PrivateKey privateKey) throws PKIException {
    try {
        X500Name issuer = new X500Name(CN_NAME + issuerName);
        BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());
        Date notAfter = new Date(notBefore.getTime() + timeUnit.toMillis(duration));
        X500Name subject = new X500Name(CN_NAME + subjectName);
        SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, publicKeyInfo);
        JcaContentSignerBuilder jcaContentSignerBuilder = new JcaContentSignerBuilder(SHA256_RSA);
        ContentSigner signer = jcaContentSignerBuilder.build(privateKey);
        CertificateFactory certificateFactory = CertificateFactory.getInstance(X509, BC_PROVIDER);
        byte[] certBytes = certBuilder.build(signer).getEncoded();
        return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certBytes));
    } catch (Exception e) {
        throw new PKIException(e);
    }
}
 
Example 8
Source Project: spring-cloud-gcp   Source File: RSAKeyGeneratorUtils.java    License: Apache License 2.0 6 votes vote down vote up
public RSAKeyGeneratorUtils() throws Exception {
	KeyStore keyStore = KeyStore.getInstance("JKS");
	keyStore.load(null, null);
	KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance("RSA");
	kpGenerator.initialize(2048);
	KeyPair keyPair = kpGenerator.generateKeyPair();

	X500Name issuerName = new X500Name("OU=spring-cloud-gcp,CN=firebase-auth-integration-test");
	this.privateKey =  keyPair.getPrivate();

	JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
			issuerName,
			BigInteger.valueOf(System.currentTimeMillis()),
			Date.from(Instant.now()), Date.from(Instant.now().plusMillis(1096 * 24 * 60 * 60)),
			issuerName, keyPair.getPublic());
	ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA").build(privateKey);
	X509CertificateHolder certHolder = builder.build(signer);
	this.certificate = new JcaX509CertificateConverter().getCertificate(certHolder);
	this.publicKey = this.certificate.getPublicKey();
}
 
Example 9
private X509Certificate generateVersion1(X500Name subject, X500Name issuer, Date validityStart, Date validityEnd, PublicKey publicKey,
		PrivateKey privateKey, SignatureType signatureType, BigInteger serialNumber) throws CryptoException {
	Date notBefore = validityStart == null ? new Date() : validityStart;
	Date notAfter = validityEnd == null ? new Date(notBefore.getTime() + TimeUnit.DAYS.toMillis(365)) : validityEnd;

	JcaX509v1CertificateBuilder certBuilder = new JcaX509v1CertificateBuilder(issuer, serialNumber, notBefore,
			notAfter, subject, publicKey);

	try {
		ContentSigner certSigner = new JcaContentSignerBuilder(signatureType.jce()).setProvider("BC").build(
				privateKey);
		return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certBuilder.build(certSigner));
	} catch (CertificateException | IllegalStateException | OperatorCreationException ex) {
		throw new CryptoException(res.getString("CertificateGenFailed.exception.message"), ex);
	}
}
 
Example 10
Source Project: logback-gelf   Source File: X509Util.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
private X509Certificate build() throws NoSuchAlgorithmException,
    CertIOException, OperatorCreationException, CertificateException {

    final X500Principal issuer = new X500Principal("CN=MyCA");
    final BigInteger sn = new BigInteger(64, new SecureRandom());
    final Date from = Date.valueOf(LocalDate.now());
    final Date to = Date.valueOf(LocalDate.now().plusYears(1));
    final X509v3CertificateBuilder v3CertGen =
        new JcaX509v3CertificateBuilder(issuer, sn, from, to, issuer, keyPair.getPublic());
    final JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
    v3CertGen.addExtension(Extension.authorityKeyIdentifier, false,
        extUtils.createAuthorityKeyIdentifier(keyPair.getPublic()));
    v3CertGen.addExtension(Extension.subjectKeyIdentifier, false,
        extUtils.createSubjectKeyIdentifier(keyPair.getPublic()));
    v3CertGen.addExtension(Extension.basicConstraints, true,
        new BasicConstraints(0));
    v3CertGen.addExtension(Extension.keyUsage, true,
        new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));
    final ContentSigner signer = new JcaContentSignerBuilder(SIG_ALGORITHM)
        .build(keyPair.getPrivate());
    return new JcaX509CertificateConverter()
        .setProvider(BouncyCastleProvider.PROVIDER_NAME)
        .getCertificate(v3CertGen.build(signer));
}
 
Example 11
Source Project: xipki   Source File: CaClientExample.java    License: Apache License 2.0 5 votes vote down vote up
protected static ContentSigner buildSigner(PrivateKey signingKey, String hashAlgo)
    throws OperatorCreationException {
  String keyAlgo = signingKey.getAlgorithm();
  String sigAlgo;
  if ("EC".equalsIgnoreCase(keyAlgo)) {
    sigAlgo = hashAlgo + "WITHECDSA";
  } else {
    sigAlgo = hashAlgo + "WITH" + keyAlgo;
  }
  return new JcaContentSignerBuilder(sigAlgo).build(signingKey);
}
 
Example 12
Source Project: hadoop-ozone   Source File: TestCRLCodec.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetX509CRL() throws IOException,
    OperatorCreationException, CertificateException, CRLException {

  X500Name issuer = x509CertificateHolder.getIssuer();
  Date now = new Date();
  X509v2CRLBuilder builder = new X509v2CRLBuilder(issuer, now);
  builder.addCRLEntry(x509CertificateHolder.getSerialNumber(), now,
                      CRLReason.cACompromise);

  JcaContentSignerBuilder contentSignerBuilder =
      new JcaContentSignerBuilder(securityConfig.getSignatureAlgo());

  contentSignerBuilder.setProvider(securityConfig.getProvider());
  PrivateKey privateKey = keyPair.getPrivate();
  X509CRLHolder cRLHolder =
      builder.build(contentSignerBuilder.build(privateKey));

  CRLCodec crlCodec = new CRLCodec(securityConfig);
  crlCodec.writeCRL(cRLHolder, this.securityConfig.getCrlName(), true);

  X509CRLEntryHolder entryHolder =
      cRLHolder.getRevokedCertificate(BigInteger.ONE);
  assertNotNull(entryHolder);

  String pemEncodedString = crlCodec.getPEMEncodedString(cRLHolder);
  assertNotNull(pemEncodedString);

  // Verify header and footer of PEM encoded String
  String header = "-----BEGIN X509 CRL-----";
  String footer = "-----END X509 CRL-----";
  assertTrue(pemEncodedString.contains(header));
  assertTrue(pemEncodedString.contains(footer));
}
 
Example 13
Source Project: Dream-Catcher   Source File: BouncyCastleSecurityProviderTool.java    License: MIT License 5 votes vote down vote up
/**
 * Creates a ContentSigner that can be used to sign certificates with the given private key and signature algorithm.
 *
 * @param certAuthorityPrivateKey the private key to use to sign certificates
 * @param signatureAlgorithm      the algorithm to use to sign certificates
 * @return a ContentSigner
 */
private static ContentSigner getCertificateSigner(PrivateKey certAuthorityPrivateKey, String signatureAlgorithm) {
    try {
        return new JcaContentSignerBuilder(signatureAlgorithm)
                .build(certAuthorityPrivateKey);
    } catch (OperatorCreationException e) {
        throw new CertificateCreationException("Unable to create ContentSigner using signature algorithm: " + signatureAlgorithm, e);
    }
}
 
Example 14
Source Project: PowerTunnel   Source File: CertificateHelper.java    License: MIT License 5 votes vote down vote up
private static X509Certificate signCertificate(
        X509v3CertificateBuilder certificateBuilder,
        PrivateKey signedWithPrivateKey) throws OperatorCreationException,
        CertificateException {
    ContentSigner signer = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM)
            .setProvider(PROVIDER_NAME).build(signedWithPrivateKey);
    return new JcaX509CertificateConverter().setProvider(
            PROVIDER_NAME).getCertificate(certificateBuilder.build(signer));
}
 
Example 15
Source Project: besu   Source File: SelfSignedP12Certificate.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("JdkObsolete") // JcaX509v3CertificateBuilder requires java.util.Date.
private static Certificate generateSelfSignedCertificate(final KeyPair keyPair)
    throws CertIOException, GeneralSecurityException, OperatorCreationException {
  final X500Name issuer = new X500Name(distinguishedName);
  final X500Name subject = new X500Name(distinguishedName);
  final BigInteger serialNumber = new BigInteger(String.valueOf(Instant.now().toEpochMilli()));
  final X509v3CertificateBuilder v3CertificateBuilder =
      new JcaX509v3CertificateBuilder(
          issuer,
          serialNumber,
          Date.from(Instant.now()),
          Date.from(Instant.now().plus(Period.ofDays(90))),
          subject,
          keyPair.getPublic());

  // extensions
  v3CertificateBuilder.addExtension(
      Extension.basicConstraints, true, new BasicConstraints(IS_CA));
  v3CertificateBuilder.addExtension(
      Extension.subjectAlternativeName, false, getSubjectAlternativeNames());

  final ContentSigner contentSigner =
      new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(keyPair.getPrivate());

  return new JcaX509CertificateConverter()
      .setProvider(BOUNCY_CASTLE_PROVIDER)
      .getCertificate(v3CertificateBuilder.build(contentSigner));
}
 
Example 16
Source Project: ofdrw   Source File: PKCGenerate.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 生成SM2密钥对的证书请求(pkcs10格式)
 *
 * @param kp      SM2密钥对
 * @param subject 证书使用者
 * @return 证书请求
 * @throws OperatorCreationException
 */
public static PKCS10CertificationRequest CertRequest(KeyPair kp, X500Name subject) throws OperatorCreationException {
    // 构造请求信息,主要是由“实体”的DN和公钥构成
    PKCS10CertificationRequestBuilder requestBuilder =
            new JcaPKCS10CertificationRequestBuilder(subject, kp.getPublic());
    // 使用“实体”私钥对请求的信息进行签名,然后组装成ASN.1对象
    return requestBuilder.build(
            new JcaContentSignerBuilder("SM3withSM2")
                    .setProvider("BC")
                    .build(kp.getPrivate()));

}
 
Example 17
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 18
public static byte[] createCSR(DistinguishedName distingueshedName, KeyPair keyPair) {
   String csrSignatureAlgorithm = RaPropertiesLoader.getProperty("csr.signature.algorithm");

   try {
      X500Principal x500Principal = new X500Principal(distingueshedName.asNormalizedEhealthDN());
      JcaPKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(x500Principal, keyPair.getPublic());
      PKCS10CertificationRequest csr = csrBuilder.build((new JcaContentSignerBuilder(csrSignatureAlgorithm)).setProvider(new BouncyCastleProvider()).build(keyPair.getPrivate()));
      return csr.getEncoded();
   } catch (OperatorCreationException var6) {
      throw new IllegalArgumentException(var6);
   } catch (IOException var7) {
      throw new IllegalArgumentException(var7);
   }
}
 
Example 19
public static byte[] createCSR(String dn, KeyPair keyPair) {
   String csrSignatureAlgorithm = RaPropertiesLoader.getProperty("csr.signature.algorithm");

   try {
      X500Principal x500Principal = new X500Principal(dn);
      JcaPKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(x500Principal, keyPair.getPublic());
      PKCS10CertificationRequest csr = csrBuilder.build((new JcaContentSignerBuilder(csrSignatureAlgorithm)).setProvider(new BouncyCastleProvider()).build(keyPair.getPrivate()));
      return csr.getEncoded();
   } catch (OperatorCreationException var6) {
      throw new IllegalArgumentException(var6);
   } catch (IOException var7) {
      throw new IllegalArgumentException(var7);
   }
}
 
Example 20
public byte[] sign(Credential signatureCredential, byte[] byteToSign, Map<String, Object> options) throws TechnicalConnectorException {
   byte[] contentToSign = ArrayUtils.clone(byteToSign);
   Map<String, Object> optionMap = new HashMap();
   if (options != null) {
      optionMap.putAll(options);
   }

   this.validateInput(signatureCredential, contentToSign);

   try {
      CMSTypedData content = new CMSProcessableByteArray(contentToSign);
      CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
      String signatureAlgorithm = (String)SignatureUtils.getOption("signatureAlgorithm", optionMap, "Sha1WithRSA");
      JcaSignerInfoGeneratorBuilder signerInfoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder((new JcaDigestCalculatorProviderBuilder()).build());
      ContentSigner contentSigner = (new JcaContentSignerBuilder(signatureAlgorithm)).build(signatureCredential.getPrivateKey());
      CMSAttributeTableGenerator cmsAttributeTableGenerator = (CMSAttributeTableGenerator)SignatureUtils.getOption("signedAttributeGenerator", optionMap, new DefaultSignedAttributeTableGenerator());
      signerInfoGeneratorBuilder.setSignedAttributeGenerator(cmsAttributeTableGenerator);
      generator.addSignerInfoGenerator(signerInfoGeneratorBuilder.build(contentSigner, signatureCredential.getCertificate()));
      Certificate[] certificateChain = signatureCredential.getCertificateChain();
      if (certificateChain != null && certificateChain.length > 0) {
         generator.addCertificates(new JcaCertStore(Arrays.asList(certificateChain)));
      }

      boolean encapsulate = (Boolean)SignatureUtils.getOption("encapsulate", optionMap, Boolean.FALSE);
      return generator.generate(content, encapsulate).getEncoded();
   } catch (Exception var14) {
      LOG.error(var14.getMessage(), var14);
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_SIGNATURE, var14, new Object[]{var14.getClass().getSimpleName() + " : " + var14.getMessage()});
   }
}
 
Example 21
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 22
public static byte[] createCSR(String dn, KeyPair keyPair) {
   String csrSignatureAlgorithm = RaPropertiesLoader.getProperty("csr.signature.algorithm");

   try {
      X500Principal x500Principal = new X500Principal(dn);
      JcaPKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(x500Principal, keyPair.getPublic());
      PKCS10CertificationRequest csr = csrBuilder.build((new JcaContentSignerBuilder(csrSignatureAlgorithm)).setProvider(new BouncyCastleProvider()).build(keyPair.getPrivate()));
      return csr.getEncoded();
   } catch (OperatorCreationException var6) {
      throw new IllegalArgumentException(var6);
   } catch (IOException var7) {
      throw new IllegalArgumentException(var7);
   }
}
 
Example 23
public byte[] sign(Credential signatureCredential, byte[] byteToSign, Map<String, Object> options) throws TechnicalConnectorException {
   byte[] contentToSign = ArrayUtils.clone(byteToSign);
   Map<String, Object> optionMap = new HashMap();
   if (options != null) {
      optionMap.putAll(options);
   }

   this.validateInput(signatureCredential, contentToSign);

   try {
      CMSTypedData content = new CMSProcessableByteArray(contentToSign);
      CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
      String signatureAlgorithm = (String)SignatureUtils.getOption("signatureAlgorithm", optionMap, "Sha1WithRSA");
      JcaSignerInfoGeneratorBuilder signerInfoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder((new JcaDigestCalculatorProviderBuilder()).build());
      ContentSigner contentSigner = (new JcaContentSignerBuilder(signatureAlgorithm)).build(signatureCredential.getPrivateKey());
      CMSAttributeTableGenerator cmsAttributeTableGenerator = (CMSAttributeTableGenerator)SignatureUtils.getOption("signedAttributeGenerator", optionMap, new DefaultSignedAttributeTableGenerator());
      signerInfoGeneratorBuilder.setSignedAttributeGenerator(cmsAttributeTableGenerator);
      generator.addSignerInfoGenerator(signerInfoGeneratorBuilder.build(contentSigner, signatureCredential.getCertificate()));
      Certificate[] certificateChain = signatureCredential.getCertificateChain();
      if (certificateChain != null && certificateChain.length > 0) {
         generator.addCertificates(new JcaCertStore(Arrays.asList(certificateChain)));
      }

      boolean encapsulate = (Boolean)SignatureUtils.getOption("encapsulate", optionMap, Boolean.FALSE);
      return generator.generate(content, encapsulate).getEncoded();
   } catch (Exception var14) {
      LOG.error(var14.getMessage(), var14);
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_SIGNATURE, var14, new Object[]{var14.getClass().getSimpleName() + " : " + var14.getMessage()});
   }
}
 
Example 24
private Certificate generateSelfSignedCertChain(KeyPair kp, X500Name subject, String hostname)
        throws CertificateException, OperatorCreationException, IOException {
    SecureRandom rand = new SecureRandom();
    PrivateKey privKey = kp.getPrivate();
    PublicKey pubKey = kp.getPublic();
    ContentSigner sigGen = new JcaContentSignerBuilder(DEFAULT_SIG_ALG).build(privKey);

    SubjectPublicKeyInfo subPubKeyInfo = new SubjectPublicKeyInfo(
            ASN1Sequence.getInstance(pubKey.getEncoded()));

    Date now = new Date(); // now

    /* force it to use a English/Gregorian dates for the cert, hardly anyone
       ever looks at the cert metadata anyway, and its very likely that they
       understand English/Gregorian dates */
    Calendar c = new GregorianCalendar(Locale.ENGLISH);
    c.setTime(now);
    c.add(Calendar.YEAR, 1);
    Time startTime = new Time(now, Locale.ENGLISH);
    Time endTime = new Time(c.getTime(), Locale.ENGLISH);

    X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(
            subject,
            BigInteger.valueOf(rand.nextLong()),
            startTime,
            endTime,
            subject,
            subPubKeyInfo);

    if (hostname != null) {
        GeneralNames subjectAltName = new GeneralNames(
                new GeneralName(GeneralName.iPAddress, hostname));
        v3CertGen.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
    }

    X509CertificateHolder certHolder = v3CertGen.build(sigGen);
    return new JcaX509CertificateConverter().getCertificate(certHolder);
}
 
Example 25
public static byte[] createCSR(DistinguishedName distingueshedName, KeyPair keyPair) {
   String csrSignatureAlgorithm = RaPropertiesLoader.getProperty("csr.signature.algorithm");

   try {
      X500Principal x500Principal = new X500Principal(distingueshedName.asNormalizedEhealthDN());
      JcaPKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(x500Principal, keyPair.getPublic());
      PKCS10CertificationRequest csr = csrBuilder.build((new JcaContentSignerBuilder(csrSignatureAlgorithm)).setProvider(new BouncyCastleProvider()).build(keyPair.getPrivate()));
      return csr.getEncoded();
   } catch (OperatorCreationException var6) {
      throw new IllegalArgumentException(var6);
   } catch (IOException var7) {
      throw new IllegalArgumentException(var7);
   }
}
 
Example 26
Source Project: xipki   Source File: MyUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static X509Cert issueSubCaCert(PrivateKey rcaKey, X500Name issuer,
    SubjectPublicKeyInfo pubKeyInfo, X500Name subject, BigInteger serialNumber,
    Date startTime) throws CertIOException, OperatorCreationException {
  Date notAfter = new Date(startTime.getTime() + CaEmulator.DAY_IN_MS * 3650);
  X509v3CertificateBuilder certGenerator = new X509v3CertificateBuilder(issuer, serialNumber,
      startTime, notAfter, subject, pubKeyInfo);
  X509KeyUsage ku = new X509KeyUsage(X509KeyUsage.keyCertSign | X509KeyUsage.cRLSign);
  certGenerator.addExtension(Extension.keyUsage, true, ku);
  BasicConstraints bc = new BasicConstraints(0);
  certGenerator.addExtension(Extension.basicConstraints, true, bc);

  String signatureAlgorithm = ScepUtil.getSignatureAlgorithm(rcaKey, HashAlgo.SHA256);
  ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).build(rcaKey);
  return new X509Cert(certGenerator.build(contentSigner));
}
 
Example 27
public static byte[] createCSR(String dn, KeyPair keyPair) {
   String csrSignatureAlgorithm = RaPropertiesLoader.getProperty("csr.signature.algorithm");

   try {
      X500Principal x500Principal = new X500Principal(dn);
      JcaPKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(x500Principal, keyPair.getPublic());
      PKCS10CertificationRequest csr = csrBuilder.build((new JcaContentSignerBuilder(csrSignatureAlgorithm)).setProvider(new BouncyCastleProvider()).build(keyPair.getPrivate()));
      return csr.getEncoded();
   } catch (OperatorCreationException | IOException ex) {
      throw new IllegalArgumentException(ex);
   }
}
 
Example 28
protected X509Certificate createCertificate(PrivateKey privateKey, X509v3CertificateBuilder x509v3CertificateBuilder)
    throws OperatorCreationException, CertificateException {
  ContentSigner contentSigner =
      new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(BouncyCastleProvider.PROVIDER_NAME)
          .build(privateKey);
  X509Certificate x509Certificate = new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME)
      .getCertificate(x509v3CertificateBuilder.build(contentSigner));
  return x509Certificate;
}
 
Example 29
public static X509Certificate generateCert(KeyPair pair) {
   try {
      X500Principal principal = new X500Principal(RaPropertiesLoader.getProperty("dummycert.subject"));
      Date notBefore = (new DateTime()).minusDays(1).toDate();
      Date notAfter = (new DateTime()).minusDays(1).plusMinutes(1).toDate();
      X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(principal, BigInteger.ZERO, notBefore, notAfter, principal, pair.getPublic());
      int keyUsageDetails = 16 + 32;
      builder.addExtension(Extension.keyUsage, true, new KeyUsage(keyUsageDetails));
      ContentSigner signer = (new JcaContentSignerBuilder(RaPropertiesLoader.getProperty("dummycert.signature.algorithm"))).build(pair.getPrivate());
      X509CertificateHolder holder = builder.build(signer);
      return (new JcaX509CertificateConverter()).setProvider("BC").getCertificate(holder);
   } catch (OperatorCreationException | IOException | CertificateException ex) {
      throw new IllegalArgumentException(ex);
   }
}
 
Example 30
Source Project: gmhelper   Source File: CommonUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static PKCS10CertificationRequest createCSR(X500Name subject, SM2PublicKey pubKey, PrivateKey priKey,
    String signAlgo) throws OperatorCreationException {
    PKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(subject, pubKey);
    ContentSigner signerBuilder = new JcaContentSignerBuilder(signAlgo)
        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(priKey);
    return csrBuilder.build(signerBuilder);
}