org.bouncycastle.crypto.util.PrivateKeyFactory Java Examples

The following examples show how to use org.bouncycastle.crypto.util.PrivateKeyFactory. 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: TestSslUtils.java    From li-apache-kafka-clients with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Create a self-signed X.509 Certificate.
 * From http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html.
 *
 * @param dn        the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
 * @param pair      the KeyPair
 * @param days      how many days from now the Certificate is valid for
 * @param algorithm the signing algorithm, eg "SHA1withRSA"
 * @return the self-signed certificate
 * @throws CertificateException thrown if a security error or an IO error occurred.
 */
public static X509Certificate generateCertificate(String dn, KeyPair pair,
                                                  int days, String algorithm)
    throws CertificateException {

  try {
    Security.addProvider(new BouncyCastleProvider());
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded());
    ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
    X500Name name = new X500Name(dn);
    Date from = new Date();
    Date to = new Date(from.getTime() + days * 86400000L);
    BigInteger sn = new BigInteger(64, new SecureRandom());

    X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(name, sn, from, to, name, subPubKeyInfo);
    X509CertificateHolder certificateHolder = v1CertGen.build(sigGen);
    return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
  } catch (CertificateException ce) {
    throw ce;
  } catch (Exception e) {
    throw new CertificateException(e);
  }
}
 
Example #2
Source File: TestSSLUtils.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Create a self-signed X.509 Certificate.
 * From http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html.
 *
 * @param dn the X.509 Distinguished Name, eg "CN(commonName)=Test, O(organizationName)=Org"
 * @param pair the KeyPair
 * @param days how many days from now the Certificate is valid for
 * @param algorithm the signing algorithm, eg "SHA1withRSA"
 * @return the self-signed certificate
 * @throws java.security.cert.CertificateException thrown if a security error or an IO error ocurred.
 */
public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm)
    throws CertificateException {
  try {
    Security.addProvider(new BouncyCastleProvider());
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded());
    ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
    X500Name name = new X500Name(dn);
    Date from = new Date();
    Date to = new Date(from.getTime() + days * 86400000L);
    BigInteger sn = new BigInteger(64, new SecureRandom());

    X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(name, sn, from, to, name, subPubKeyInfo);
    X509CertificateHolder certificateHolder = v1CertGen.build(sigGen);
    return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
  } catch (CertificateException ce) {
    throw ce;
  } catch (Exception e) {
    throw new CertificateException(e);
  }
}
 
Example #3
Source File: OcspHandler.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public OcspHandler(String responderCertPath, String responderKeyPath)
        throws OperatorCreationException, GeneralSecurityException, IOException {
    final Certificate certificate = CertificateFactory.getInstance("X509")
            .generateCertificate(X509OCSPResponderTest.class.getResourceAsStream(responderCertPath));

    chain = new X509CertificateHolder[] {new X509CertificateHolder(certificate.getEncoded())};

    final AsymmetricKeyParameter publicKey = PublicKeyFactory.createKey(certificate.getPublicKey().getEncoded());

    subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(publicKey);

    final InputStream keyPairStream = X509OCSPResponderTest.class.getResourceAsStream(responderKeyPath);

    try (final PEMParser keyPairReader = new PEMParser(new InputStreamReader(keyPairStream))) {
        final PEMKeyPair keyPairPem = (PEMKeyPair) keyPairReader.readObject();
        privateKey = PrivateKeyFactory.createKey(keyPairPem.getPrivateKeyInfo());
    }
}
 
Example #4
Source File: FTPAndSSHDUnitTest.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private X509Certificate generateCertificate(KeyPair keyPair) throws Exception {
  Date from = new Date();
  Date to = new GregorianCalendar(2037, Calendar.DECEMBER, 31).getTime();
  X500Name subject = new X500Name("CN=localhost");
  SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
  X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(
      subject,
      new BigInteger(64, new SecureRandom()),
      from,
      to,
      subject,
      subPubKeyInfo
  );
  AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA512WITHRSA");
  AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
  ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
      .build(PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded()));
  X509CertificateHolder certHolder = certBuilder.build(contentSigner);
  return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder);
}
 
Example #5
Source File: SSLKeyPairCerts.java    From vertx-tcp-eventbus-bridge with Apache License 2.0 6 votes vote down vote up
private X509Certificate generateSelfSignedCert(String certSub, KeyPair keyPair) throws Exception {
  final X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(
    new org.bouncycastle.asn1.x500.X500Name(certSub),
    BigInteger.ONE,
    new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
    new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)),
    new X500Name(certSub),
    SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded())
  );
  final GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.iPAddress, "127.0.0.1"));
  certificateBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.subjectAlternativeName, false, subjectAltNames);

  final AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithRSAEncryption");
  final AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
  final BcContentSignerBuilder signerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);
  final AsymmetricKeyParameter keyp = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded());
  final ContentSigner signer = signerBuilder.build(keyp);
  final X509CertificateHolder x509CertificateHolder = certificateBuilder.build(signer);
  final X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(x509CertificateHolder);
  certificate.checkValidity(new Date());
  certificate.verify(keyPair.getPublic());
  return certificate;
}
 
Example #6
Source File: BouncyCastleV1CryptoProvider.java    From paseto with MIT License 6 votes vote down vote up
private PSSSigner pssSha384(boolean forSigning, byte[] key) {
	try {
		byte[] salt = new byte[SHA384_OUT_LEN];
		new SecureRandom().nextBytes(salt);
		// RSA-PSS, SHA-384, MGF1(SHA-384), 48 byte salt length, 0xBC trailer
		PSSSigner pss = new PSSSigner(new RSABlindedEngine(), new SHA384Digest(), new SHA384Digest(),
				SHA384_OUT_LEN, (byte) 0xBC);

		if (forSigning) {
			pss.init(true, PrivateKeyFactory.createKey(key));
		} else {
			pss.init(false, PublicKeyFactory.createKey(key));
		}

		return pss;
	} catch (IOException e) {
		throw new CryptoProviderException("IOException", e);
	}
}
 
Example #7
Source File: CertificateManager.java    From Launcher with GNU General Public License v3.0 6 votes vote down vote up
public void generateCA() throws NoSuchAlgorithmException, IOException, OperatorCreationException, InvalidAlgorithmParameterException {
    ECGenParameterSpec ecGenSpec = new ECGenParameterSpec("secp384k1");
    KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
    generator.initialize(ecGenSpec, SecurityHelper.newRandom());
    KeyPair pair = generator.generateKeyPair();
    LocalDateTime startDate = LocalDate.now().atStartOfDay();

    X500NameBuilder subject = new X500NameBuilder();
    subject.addRDN(BCStyle.CN, orgName.concat(" CA"));
    subject.addRDN(BCStyle.O, orgName);

    X509v3CertificateBuilder builder = new X509v3CertificateBuilder(
            subject.build(),
            new BigInteger("0"),
            Date.from(startDate.atZone(ZoneId.systemDefault()).toInstant()),
            Date.from(startDate.plusDays(3650).atZone(ZoneId.systemDefault()).toInstant()),
            new X500Name("CN=ca"),
            SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded()));
    JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256WITHECDSA");
    ContentSigner signer = csBuilder.build(pair.getPrivate());
    ca = builder.build(signer);
    caKey = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
}
 
Example #8
Source File: Certificates.java    From icure-backend with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a Master certificate for ICure.
 */
public static X509Certificate createMasterCertificateV3(PublicKey publicKey, PrivateKey privateKey) throws Exception {
	X500Name 	issuer = new X500Name("C=BE, O=Taktik, OU=ICureCloud, CN=ICureCloud");
	X500Name 	subject = new X500Name("C=BE, O=Taktik, OU=ICureCloud, CN=ICureCloud"); // self signed
	BigInteger 	serial = BigInteger.valueOf(RSAKeysUtils.random.nextLong());
	Date 		notBefore = new Date(System.currentTimeMillis() - 10000);
	Date		notAfter = new Date(System.currentTimeMillis() + 24L * 3600 * 1000);
	
	SubjectPublicKeyInfo spki = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
	
	X509v3CertificateBuilder x509v3CertBuilder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, spki);
	x509v3CertBuilder.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(true)); // icure is CA

	// Create a content signer
	AlgorithmIdentifier signatureAlgorithmId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA");
	AlgorithmIdentifier digestAlgorithmId = new DefaultDigestAlgorithmIdentifierFinder().find(signatureAlgorithmId);
	AsymmetricKeyParameter akp = PrivateKeyFactory.createKey(privateKey.getEncoded());
	ContentSigner contentSigner =  new BcRSAContentSignerBuilder(signatureAlgorithmId, digestAlgorithmId).build(akp);

	X509CertificateHolder holder = x509v3CertBuilder.build(contentSigner);
	Certificate certificateStructure = holder.toASN1Structure();
	X509Certificate certificate = convertToJavaCertificate(certificateStructure);
	
	certificate.verify(publicKey);

	return certificate;
}
 
Example #9
Source File: CertificateUtils.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the content signer for generation of Version 1 {@link java.security.cert.X509Certificate}.
 *
 * @param privateKey the private key
 *
 * @return the content signer
 */
public static ContentSigner createSigner(PrivateKey privateKey) {
    try {
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256WithRSAEncryption");
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);

        return new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
                .build(PrivateKeyFactory.createKey(privateKey.getEncoded()));
    } catch (Exception e) {
        throw new RuntimeException("Could not create content signer.", e);
    }
}
 
Example #10
Source File: ElasticsearchCluster.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private static ContentSigner newSigner(PrivateKey privateKey, String algo) {
    try {
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algo);
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);

        return new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
                .build(PrivateKeyFactory.createKey(privateKey.getEncoded()));
    } catch (OperatorCreationException | IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #11
Source File: PkiUtil.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private static X509Certificate selfsign(PKCS10CertificationRequest inputCSR, String publicAddress, KeyPair signKey)
        throws Exception {

    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder()
            .find("SHA256withRSA");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder()
            .find(sigAlgId);

    AsymmetricKeyParameter akp = PrivateKeyFactory.createKey(signKey.getPrivate()
            .getEncoded());

    Calendar cal = Calendar.getInstance();
    Date currentTime = cal.getTime();
    cal.add(Calendar.YEAR, CERT_VALIDITY_YEAR);
    Date expiryTime = cal.getTime();

    X509v3CertificateBuilder myCertificateGenerator = new X509v3CertificateBuilder(
            new X500Name(String.format("cn=%s", publicAddress)), new BigInteger("1"), currentTime, expiryTime, inputCSR.getSubject(),
            inputCSR.getSubjectPublicKeyInfo());

    ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
            .build(akp);

    X509CertificateHolder holder = myCertificateGenerator.build(sigGen);

    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    return (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(holder.toASN1Structure().getEncoded()));
}
 
Example #12
Source File: TestKeyStoreGenerator.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@NotNull
private ContentSigner createRSAContentSigner(final KeyPair keyPair) throws Exception {
    final AlgorithmIdentifier signatureAlgorithmId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA");
    final AlgorithmIdentifier digestAlgorithmId = new DefaultDigestAlgorithmIdentifierFinder().find(signatureAlgorithmId);

    final byte[] encoded = keyPair.getPrivate().getEncoded();
    final AsymmetricKeyParameter privateKey = PrivateKeyFactory.createKey(encoded);

    return new BcRSAContentSignerBuilder(signatureAlgorithmId, digestAlgorithmId).build(privateKey);
}
 
Example #13
Source File: CertificateManager.java    From Launcher with GNU General Public License v3.0 5 votes vote down vote up
public AsymmetricKeyParameter readPrivateKey(Reader reader) throws IOException {
    AsymmetricKeyParameter ret;
    try (PemReader reader1 = new PemReader(reader)) {
        byte[] bytes = reader1.readPemObject().getContent();
        try (ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes)) {

            ret = PrivateKeyFactory.createKey(inputStream);
        }
    }
    return ret;
}
 
Example #14
Source File: Certificates.java    From vertx-config with Apache License 2.0 5 votes vote down vote up
/**
 * See http://www.programcreek.com/java-api-examples/index.php?api=org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder
 *
 * @param keyPair The RSA keypair with which to generate the certificate
 * @param issuer  The issuer (and subject) to use for the certificate
 * @return An X509 certificate
 * @throws IOException
 * @throws OperatorCreationException
 * @throws CertificateException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws SignatureException
 */
private static X509Certificate generateCert(final KeyPair keyPair, final String issuer) throws IOException, OperatorCreationException,
  CertificateException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException,
  SignatureException {
  final String subject = issuer;
  final X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(
    new X500Name(issuer),
    BigInteger.ONE,
    new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
    new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)),
    new X500Name(subject),
    SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded())
  );

  final GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.iPAddress, "127.0.0.1"));
  certificateBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.subjectAlternativeName, false, subjectAltNames);

  final AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithRSAEncryption");
  final AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
  final BcContentSignerBuilder signerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);
  final AsymmetricKeyParameter keyp = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded());
  final ContentSigner signer = signerBuilder.build(keyp);
  final X509CertificateHolder x509CertificateHolder = certificateBuilder.build(signer);

  final X509Certificate certificate = new JcaX509CertificateConverter()
    .getCertificate(x509CertificateHolder);
  certificate.checkValidity(new Date());
  certificate.verify(keyPair.getPublic());
  return certificate;
}
 
Example #15
Source File: TestKeyStoreGenerator.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@NotNull
private ContentSigner createECContentSigner(final KeyPair keyPair) throws Exception {
    final AlgorithmIdentifier signatureAlgorithmId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withECDSA");
    final AlgorithmIdentifier digestAlgorithmId = new DefaultDigestAlgorithmIdentifierFinder().find(signatureAlgorithmId);

    final byte[] encoded = keyPair.getPrivate().getEncoded();
    final AsymmetricKeyParameter privateKey = PrivateKeyFactory.createKey(encoded);

    return new BcECContentSignerBuilder(signatureAlgorithmId, digestAlgorithmId).build(privateKey);
}
 
Example #16
Source File: CreateSignature.java    From testarea-pdfbox2 with Apache License 2.0 4 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/41767351/create-pkcs7-signature-from-file-digest">
 * Create pkcs7 signature from file digest
 * </a>
 * <p>
 * The OP's <code>sign</code> method after fixing some errors. The
 * OP's original method is {@link #signBySnox(InputStream)}. The
 * errors were
 * </p>
 * <ul>
 * <li>multiple attempts at reading the {@link InputStream} parameter;
 * <li>convoluted creation of final CMS container.
 * </ul>
 * <p>
 * Additionally this method uses SHA256 instead of SHA-1.
 * </p>
 */
public byte[] signWithSeparatedHashing(InputStream content) throws IOException
{
    try
    {
        // Digest generation step
        MessageDigest md = MessageDigest.getInstance("SHA256", "BC");
        byte[] digest = md.digest(IOUtils.toByteArray(content));

        // Separate signature container creation step
        List<Certificate> certList = Arrays.asList(chain);
        JcaCertStore certs = new JcaCertStore(certList);

        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();

        Attribute attr = new Attribute(CMSAttributes.messageDigest,
                new DERSet(new DEROctetString(digest)));

        ASN1EncodableVector v = new ASN1EncodableVector();

        v.add(attr);

        SignerInfoGeneratorBuilder builder = new SignerInfoGeneratorBuilder(new BcDigestCalculatorProvider())
                .setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(new AttributeTable(v)));

        AlgorithmIdentifier sha256withRSA = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA");

        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        InputStream in = new ByteArrayInputStream(chain[0].getEncoded());
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in);

        gen.addSignerInfoGenerator(builder.build(
                new BcRSAContentSignerBuilder(sha256withRSA,
                        new DefaultDigestAlgorithmIdentifierFinder().find(sha256withRSA))
                                .build(PrivateKeyFactory.createKey(pk.getEncoded())),
                new JcaX509CertificateHolder(cert)));

        gen.addCertificates(certs);

        CMSSignedData s = gen.generate(new CMSAbsentContent(), false);
        return s.getEncoded();
    }
    catch (Exception e)
    {
        e.printStackTrace();
        throw new IOException(e);
    }
}
 
Example #17
Source File: CA.java    From PacketProxy with Apache License 2.0 4 votes vote down vote up
protected ContentSigner createSigner() throws Exception {
	AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA");
	AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
	return new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(PrivateKeyFactory.createKey(keyStoreCAPrivateKey.getEncoded()));
}
 
Example #18
Source File: PacketProxyCAPerUser.java    From PacketProxy with Apache License 2.0 4 votes vote down vote up
private void generateKeyStore(String ksPath) throws Exception {
	KeyStore ks;
	KeyPair CAKeyPair = super.genRSAKeyPair();
	
	// 各ユーザ用のキーストアを作るためのテンプレートを取得
	try (InputStream input = this.getClass().getResourceAsStream("/certificates/user.ks")) {
		ks = KeyStore.getInstance("JKS");
		ks.load(input, password);
	}
	
	int serialNumber = 0;
	do {
		serialNumber = SecureRandom.getInstance("SHA1PRNG").nextInt();
	} while (serialNumber <= 0);

	String x500Name = String.format("C=PacketProxy, ST=PacketProxy, L=PacketProxy, O=PacketProxy, OU=PacketProxy CA, CN=PacketProxy per-user CA (%x)", serialNumber);
	Date from = new Date();
	Calendar cal = Calendar.getInstance();
	cal.setTime(from);
	cal.add(Calendar.YEAR, 30);
	Date to = cal.getTime();

	X509v3CertificateBuilder caRootBuilder = new X509v3CertificateBuilder(
			new X500Name(x500Name),
			BigInteger.valueOf(serialNumber),
			from,
			to,
			new X500Name(x500Name),
			SubjectPublicKeyInfo.getInstance(CAKeyPair.getPublic().getEncoded()));
       
	/* CA: X509 Extensionsの設定(CA:true, pathlen:0) */
	caRootBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(0)); 
	
       AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA");
       AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
       ContentSigner signer = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(PrivateKeyFactory.createKey(CAKeyPair.getPrivate().getEncoded()));
       X509CertificateHolder signedRoot = caRootBuilder.build(signer);
	
	// 新しいKeyStoreの生成
	KeyStore newks = KeyStore.getInstance("JKS");
	newks.load(null, password);
	
	// 証明書と秘密鍵の登録
	CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
	newks.setKeyEntry(
			"root",
			CAKeyPair.getPrivate(),
			password,
			new Certificate[]{ certFactory.generateCertificate(new ByteArrayInputStream(signedRoot.getEncoded())) });
	
	File newksfile = new File(ksPath);
	newksfile.getParentFile().mkdirs();
	newksfile.createNewFile();
	newksfile.setWritable(false, false);
	newksfile.setWritable(true);
	newksfile.setReadable(false, false);
	newksfile.setReadable(true);
	try (FileOutputStream fos = new FileOutputStream(ksPath)) {
	    newks.store(fos, password);
	}
}
 
Example #19
Source File: BCCryptoHelper.java    From OpenAs2App with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public MimeBodyPart decrypt(MimeBodyPart part, Certificate cert, Key key) throws GeneralSecurityException, MessagingException, CMSException, IOException, SMIMEException {
    // Make sure the data is encrypted
    if (!isEncrypted(part)) {
        throw new GeneralSecurityException("Content-Type indicates data isn't encrypted");
    }

    // Cast parameters to what BC needs
    X509Certificate x509Cert = castCertificate(cert);

    // Parse the MIME body into an SMIME envelope object
    SMIMEEnveloped envelope = new SMIMEEnveloped(part);

    // Get the recipient object for decryption
    if (logger.isDebugEnabled()) {
        logger.debug("Extracted X500 info::  PRINCIPAL : " + x509Cert.getIssuerX500Principal() + " ::  NAME : " + x509Cert.getIssuerX500Principal().getName());
    }

    X500Name x500Name = new X500Name(x509Cert.getIssuerX500Principal().getName());
    KeyTransRecipientId certRecId = new KeyTransRecipientId(x500Name, x509Cert.getSerialNumber());
    RecipientInformationStore recipientInfoStore = envelope.getRecipientInfos();

    Collection<RecipientInformation> recipients = recipientInfoStore.getRecipients();

    if (recipients == null) {
        throw new GeneralSecurityException("Certificate recipients could not be extracted");
    }
    //RecipientInformation recipientInfo  = recipientInfoStore.get(recId);
    //Object recipient = null;        

    boolean foundRecipient = false;
    for (Iterator<RecipientInformation> iterator = recipients.iterator(); iterator.hasNext(); ) {
        RecipientInformation recipientInfo = iterator.next();
        //recipient = iterator.next();
        if (recipientInfo instanceof KeyTransRecipientInformation) {
            // X509CertificateHolder x509CertHolder = new X509CertificateHolder(x509Cert.getEncoded());

            //RecipientId rid = recipientInfo.getRID();
            if (certRecId.match(recipientInfo) && !foundRecipient) {
                foundRecipient = true;
                // byte[] decryptedData = recipientInfo.getContent(new JceKeyTransEnvelopedRecipient((PrivateKey)key).setProvider("BC"));
                byte[] decryptedData = recipientInfo.getContent(new BcRSAKeyTransEnvelopedRecipient(PrivateKeyFactory.createKey(PrivateKeyInfo.getInstance(key.getEncoded()))));

                return SMIMEUtil.toMimeBodyPart(decryptedData);
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("Failed match on recipient ID's:\n     RID from msg:" + recipientInfo.getRID().toString() + "    \n     RID from priv cert: " + certRecId.toString());
                }
            }
        }
    }
    throw new GeneralSecurityException("Matching certificate recipient could not be found");
}
 
Example #20
Source File: CreateSignature.java    From testarea-pdfbox2 with Apache License 2.0 4 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/41767351/create-pkcs7-signature-from-file-digest">
 * Create pkcs7 signature from file digest
 * </a>
 * <p>
 * The OP's own <code>sign</code> method which has some errors. These
 * errors are fixed in {@link #signWithSeparatedHashing(InputStream)}.
 * </p>
 */
public byte[] signBySnox(InputStream content) throws IOException {
    // testSHA1WithRSAAndAttributeTable
    try {
        MessageDigest md = MessageDigest.getInstance("SHA1", "BC");
        List<Certificate> certList = new ArrayList<Certificate>();
        CMSTypedData msg = new CMSProcessableByteArray(IOUtils.toByteArray(content));

        certList.addAll(Arrays.asList(chain));

        Store<?> certs = new JcaCertStore(certList);

        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();

        Attribute attr = new Attribute(CMSAttributes.messageDigest,
                new DERSet(new DEROctetString(md.digest(IOUtils.toByteArray(content)))));

        ASN1EncodableVector v = new ASN1EncodableVector();

        v.add(attr);

        SignerInfoGeneratorBuilder builder = new SignerInfoGeneratorBuilder(new BcDigestCalculatorProvider())
                .setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(new AttributeTable(v)));

        AlgorithmIdentifier sha1withRSA = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA");

        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        InputStream in = new ByteArrayInputStream(chain[0].getEncoded());
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in);

        gen.addSignerInfoGenerator(builder.build(
                new BcRSAContentSignerBuilder(sha1withRSA,
                        new DefaultDigestAlgorithmIdentifierFinder().find(sha1withRSA))
                                .build(PrivateKeyFactory.createKey(pk.getEncoded())),
                new JcaX509CertificateHolder(cert)));

        gen.addCertificates(certs);

        CMSSignedData s = gen.generate(new CMSAbsentContent(), false);
        return new CMSSignedData(msg, s.getEncoded()).getEncoded();

    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e);
    }
}
 
Example #21
Source File: X509Util.java    From logback-gelf with GNU Lesser General Public License v2.1 4 votes vote down vote up
X509Certificate build(final String commonName, final String... subjectAltName)
    throws IOException, OperatorCreationException, CertificateException,
    NoSuchAlgorithmException {

    final AlgorithmIdentifier sigAlgId =
        new DefaultSignatureAlgorithmIdentifierFinder().find(SIG_ALGORITHM);
    final AlgorithmIdentifier digAlgId =
        new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    final AsymmetricKeyParameter privateKeyAsymKeyParam =
        PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded());
    final SubjectPublicKeyInfo subPubKeyInfo =
        SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    final ContentSigner sigGen;

    final X500Name issuer = new X500Name(CA_NAME);
    final X500NameBuilder x500NameBuilder = new X500NameBuilder();
    if (commonName != null) {
        x500NameBuilder.addRDN(BCStyle.CN, commonName);
    }
    x500NameBuilder.addRDN(BCStyle.O, "snakeoil");
    final X500Name name = x500NameBuilder.build();

    final Date from = Date.valueOf(validFrom);
    final Date to = Date.valueOf(validTo);
    final BigInteger sn = new BigInteger(64, new SecureRandom());
    final X509v3CertificateBuilder v3CertGen =
        new X509v3CertificateBuilder(issuer, sn, from, to, name, subPubKeyInfo);

    if (caCertificate != null) {
        sigGen = new JcaContentSignerBuilder(SIG_ALGORITHM).build(caPrivateKey);

        final JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
        v3CertGen.addExtension(Extension.authorityKeyIdentifier, false,
            extUtils.createAuthorityKeyIdentifier(caCertificate));
    } else {
        sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
            .build(privateKeyAsymKeyParam);
    }

    if (subjectAltName != null) {
        final GeneralName[] generalNames = Arrays.stream(subjectAltName)
            .map(s -> new GeneralName(GeneralName.dNSName, s))
            .toArray(GeneralName[]::new);

        v3CertGen.addExtension(Extension.subjectAlternativeName, false,
            new GeneralNames(generalNames).getEncoded());
    }

    final X509CertificateHolder certificateHolder = v3CertGen.build(sigGen);
    return new JcaX509CertificateConverter()
        .setProvider(BouncyCastleProvider.PROVIDER_NAME)
        .getCertificate(certificateHolder);
}
 
Example #22
Source File: DefaultApprover.java    From hadoop-ozone with Apache License 2.0 4 votes vote down vote up
/**
 * Sign function signs a Certificate.
 * @param config - Security Config.
 * @param caPrivate - CAs private Key.
 * @param caCertificate - CA Certificate.
 * @param validFrom - Begin Da te
 * @param validTill - End Date
 * @param certificationRequest - Certification Request.
 * @param scmId - SCM id.
 * @param clusterId - Cluster id.
 * @return Signed Certificate.
 * @throws IOException - On Error
 * @throws OperatorCreationException - on Error.
 */
@SuppressWarnings("ParameterNumber")
public  X509CertificateHolder sign(
    SecurityConfig config,
    PrivateKey caPrivate,
    X509CertificateHolder caCertificate,
    Date validFrom,
    Date validTill,
    PKCS10CertificationRequest certificationRequest,
    String scmId,
    String clusterId) throws IOException, OperatorCreationException {

  AlgorithmIdentifier sigAlgId = new
      DefaultSignatureAlgorithmIdentifierFinder().find(
      config.getSignatureAlgo());
  AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder()
      .find(sigAlgId);

  AsymmetricKeyParameter asymmetricKP = PrivateKeyFactory.createKey(caPrivate
      .getEncoded());
  SubjectPublicKeyInfo keyInfo =
      certificationRequest.getSubjectPublicKeyInfo();

  // Get scmId and cluster Id from subject name.
  X500Name x500Name = certificationRequest.getSubject();
  String csrScmId = x500Name.getRDNs(BCStyle.OU)[0].getFirst().getValue().
      toASN1Primitive().toString();
  String csrClusterId = x500Name.getRDNs(BCStyle.O)[0].getFirst().getValue().
      toASN1Primitive().toString();

  if (!scmId.equals(csrScmId) || !clusterId.equals(csrClusterId)) {
    if (csrScmId.equalsIgnoreCase("null") &&
        csrClusterId.equalsIgnoreCase("null")) {
      // Special case to handle DN certificate generation as DN might not know
      // scmId and clusterId before registration. In secure mode registration
      // will succeed only after datanode has a valid certificate.
      String cn = x500Name.getRDNs(BCStyle.CN)[0].getFirst().getValue()
          .toASN1Primitive().toString();
      x500Name = SecurityUtil.getDistinguishedName(cn, scmId, clusterId);
    } else {
      // Throw exception if scmId and clusterId doesn't match.
      throw new SCMSecurityException("ScmId and ClusterId in CSR subject" +
          " are incorrect.");
    }
  }

  RSAKeyParameters rsa =
      (RSAKeyParameters) PublicKeyFactory.createKey(keyInfo);
  if (rsa.getModulus().bitLength() < config.getSize()) {
    throw new SCMSecurityException("Key size is too small in certificate " +
        "signing request");
  }
  X509v3CertificateBuilder certificateGenerator =
      new X509v3CertificateBuilder(
          caCertificate.getSubject(),
          // Serial is not sequential but it is monotonically increasing.
          BigInteger.valueOf(Time.monotonicNowNanos()),
          validFrom,
          validTill,
          x500Name, keyInfo);

  ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
      .build(asymmetricKP);

  return certificateGenerator.build(sigGen);

}
 
Example #23
Source File: Certificates.java    From icure-backend with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Creates a certificate for a healthcare party.
 */
public static X509Certificate createCertificateV3(PublicKey hcpartyPublicKey, HealthcareParty hcparty, String hcPartyEmail, PublicKey icurePublicKey, PrivateKey icurePrivateKey) throws Exception {
	//
	// Signers
	//
	Hashtable<org.bouncycastle.asn1.ASN1ObjectIdentifier, String> sAttrs = new Hashtable<>();
	Vector<org.bouncycastle.asn1.ASN1ObjectIdentifier> sOrder = new Vector<>();

	sAttrs.put(X509Principal.C, "BE");
	sAttrs.put(X509Principal.O, "Taktik");
	sAttrs.put(X509Principal.OU, "ICureCloud");
	sAttrs.put(X509Principal.EmailAddress, "[email protected]");
	sOrder.addElement(X509Principal.C);
	sOrder.addElement(X509Principal.O);
	sOrder.addElement(X509Principal.OU);
	sOrder.addElement(X509Principal.EmailAddress);

	X509Principal issuerX509Principal = new X509Principal(sOrder, sAttrs);
	X500Name issuer = new X500Name(issuerX509Principal.getName());

	//
	// Subjects
	//
	Hashtable<org.bouncycastle.asn1.ASN1ObjectIdentifier, String> attrs = new Hashtable<>();
	Vector<org.bouncycastle.asn1.ASN1ObjectIdentifier> order = new Vector<>();

	attrs.put(X509Principal.C, "BE");
	attrs.put(X509Principal.O, "organization-" + hcparty.getCompanyName());
	attrs.put(X509Principal.L, "location-" + hcparty.getId());
	attrs.put(X509Principal.CN, "cn-" + hcparty.getId());
	attrs.put(X509Principal.EmailAddress, hcPartyEmail);
	order.addElement(X509Principal.C);
	order.addElement(X509Principal.O);
	order.addElement(X509Principal.L);
	order.addElement(X509Principal.CN);
	order.addElement(X509Principal.EmailAddress);

	X509Principal subjectX509Principal = new X509Principal(order, attrs);
	X500Name subject = new X500Name(subjectX509Principal.getName());

	//
	// Other attrs
	//
	BigInteger 	serial = BigInteger.valueOf(RSAKeysUtils.random.nextLong());
	Date 		notBefore = new Date(System.currentTimeMillis() - 10000);
	Date		notAfter = new Date(System.currentTimeMillis() + 24L * 3600 * 1000);
	SubjectPublicKeyInfo spki = SubjectPublicKeyInfo.getInstance(hcpartyPublicKey.getEncoded());
	

	X509v3CertificateBuilder x509v3CertBuilder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, spki);
	x509v3CertBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false)); // hcparty is not CA
	x509v3CertBuilder.addExtension(Extension.subjectKeyIdentifier, true, new SubjectKeyIdentifier(hcpartyPublicKey.getEncoded()));
	x509v3CertBuilder.addExtension(Extension.authorityKeyIdentifier, true, new AuthorityKeyIdentifierStructure(icurePublicKey));

	//
	// Create a content signer
	//
	AlgorithmIdentifier signatureAlgorithmId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA");
	AlgorithmIdentifier digestAlgorithmId = new DefaultDigestAlgorithmIdentifierFinder().find(signatureAlgorithmId);
	AsymmetricKeyParameter akp = PrivateKeyFactory.createKey(icurePrivateKey.getEncoded());
	ContentSigner contentSigner =  new BcRSAContentSignerBuilder(signatureAlgorithmId, digestAlgorithmId).build(akp);

	//
	// Build the certificate
	//
	X509CertificateHolder holder = x509v3CertBuilder.build(contentSigner);
	Certificate certificateStructure = holder.toASN1Structure();
	X509Certificate certificate = convertToJavaCertificate(certificateStructure);
	
	certificate.verify(icurePublicKey);

	return certificate;
}
 
Example #24
Source File: CertGen.java    From snowblossom with Apache License 2.0 4 votes vote down vote up
/**
 * @param key_pair Key pair to use to sign the cert inner signed message, the node key
 * @param tls_wkp The temporary key to use just for this cert and TLS sessions
 * @param spec Address for 'key_pair'
 */
public static X509Certificate generateSelfSignedCert(WalletKeyPair key_pair, WalletKeyPair tls_wkp, AddressSpec spec)
  throws Exception
{

  AddressSpecHash address_hash = AddressUtil.getHashForSpec(spec);
  String address = AddressUtil.getAddressString(Globals.NODE_ADDRESS_STRING, address_hash);


  byte[] encoded_pub= tls_wkp.getPublicKey().toByteArray();
  SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(
    ASN1Sequence.getInstance(encoded_pub));

  String dn=String.format("CN=%s, O=Snowblossom", address);
  X500Name issuer = new X500Name(dn);
  BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());
  Date notBefore = new Date(System.currentTimeMillis());
  Date notAfter = new Date(System.currentTimeMillis() + 86400000L * 365L * 10L);
  X500Name subject = issuer;

  X509v3CertificateBuilder cert_builder = new X509v3CertificateBuilder(
    issuer, serial, notBefore, notAfter, subject, subjectPublicKeyInfo);

  //System.out.println(org.bouncycastle.asn1.x509.Extension.subjectAlternativeName);
  ASN1ObjectIdentifier snow_claim_oid = new ASN1ObjectIdentifier("2.5.29.134");

  //System.out.println(spec);

  SignedMessagePayload payload = SignedMessagePayload.newBuilder().setTlsPublicKey(tls_wkp.getPublicKey()).build();
  SignedMessage sm = MsgSigUtil.signMessage(spec, key_pair, payload);

  byte[] sm_data = sm.toByteString().toByteArray();

  cert_builder.addExtension(snow_claim_oid, true, sm_data);

  String algorithm = "SHA256withRSA";

  AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(tls_wkp.getPrivateKey().toByteArray());

  AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
  AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);

  //ContentSigner sigGen = new BcECContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
  ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);

  X509CertificateHolder certificateHolder = cert_builder.build(sigGen);

  X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
  return cert;
}