org.bouncycastle.crypto.params.AsymmetricKeyParameter Java Examples

The following examples show how to use org.bouncycastle.crypto.params.AsymmetricKeyParameter. 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: 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 #5
Source File: KeyPairUtil.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
/**
 * Get the key size of a key represented by key parameters.
 * 
 * @param keyParams The key parameters
 * @return The key size, {@link #UNKNOWN_KEY_SIZE} if not known
 */
public static int getKeyLength(AsymmetricKeyParameter keyParams)
{
	if (keyParams instanceof RSAKeyParameters)
	{
		return ((RSAKeyParameters) keyParams).getModulus().bitLength();
	}
	else if (keyParams instanceof DSAKeyParameters)
	{
		return ((DSAKeyParameters) keyParams).getParameters().getP().bitLength();
	}
	else if (keyParams instanceof DHKeyParameters)
	{
		return ((DHKeyParameters) keyParams).getParameters().getP().bitLength();
	}
	else if (keyParams instanceof ECKeyParameters)
	{
		// TODO: how to get key length from these?
		return UNKNOWN_KEY_SIZE;
	}

	_logger.warn("Don't know how to get key size from parameters " + keyParams);
	return UNKNOWN_KEY_SIZE;
}
 
Example #6
Source File: KeyPairUtil.java    From portecle with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get the key size of a key represented by key parameters.
 *
 * @param keyParams The key parameters
 * @return The key size, {@link #UNKNOWN_KEY_SIZE} if not known
 */
public static int getKeyLength(AsymmetricKeyParameter keyParams)
{
	if (keyParams instanceof RSAKeyParameters)
	{
		return ((RSAKeyParameters) keyParams).getModulus().bitLength();
	}
	else if (keyParams instanceof DSAKeyParameters)
	{
		return ((DSAKeyParameters) keyParams).getParameters().getP().bitLength();
	}
	else if (keyParams instanceof DHKeyParameters)
	{
		return ((DHKeyParameters) keyParams).getParameters().getP().bitLength();
	}
	else if (keyParams instanceof ECKeyParameters)
	{
		// TODO: how to get key length from these?
		return UNKNOWN_KEY_SIZE;
	}

	LOG.warning("Don't know how to get key size from parameters " + keyParams);
	return UNKNOWN_KEY_SIZE;
}
 
Example #7
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 #8
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 #9
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 #10
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 #11
Source File: CaEmulator.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static AsymmetricKeyParameter generatePublicKeyParameter(PublicKey key)
    throws InvalidKeyException {
  Args.notNull(key, "key");

  if (key instanceof RSAPublicKey) {
    RSAPublicKey rsaKey = (RSAPublicKey) key;
    return new RSAKeyParameters(false, rsaKey.getModulus(), rsaKey.getPublicExponent());
  } else if (key instanceof ECPublicKey) {
    return ECUtil.generatePublicKeyParameter(key);
  } else if (key instanceof DSAPublicKey) {
    return DSAUtil.generatePublicKeyParameter(key);
  } else {
    throw new InvalidKeyException("unknown key " + key.getClass().getName());
  }
}
 
Example #12
Source File: CaEmulator.java    From xipki with Apache License 2.0 5 votes vote down vote up
public ContentVerifierProvider getContentVerifierProvider(PublicKey publicKey)
    throws InvalidKeyException {
  Args.notNull(publicKey, "publicKey");

  String keyAlg = publicKey.getAlgorithm().toUpperCase();
  if ("EC".equals(keyAlg)) {
    keyAlg = "ECDSA";
  }

  BcContentVerifierProviderBuilder builder = VERIFIER_PROVIDER_BUILDER.get(keyAlg);
  if (builder == null) {
    if ("RSA".equals(keyAlg)) {
      builder = new BcRSAContentVerifierProviderBuilder(DFLT_DIGESTALG_IDENTIFIER_FINDER);
    } else if ("DSA".equals(keyAlg)) {
      builder = new BcDSAContentVerifierProviderBuilder(DFLT_DIGESTALG_IDENTIFIER_FINDER);
    } else if ("ECDSA".equals(keyAlg)) {
      builder = new BcECContentVerifierProviderBuilder(DFLT_DIGESTALG_IDENTIFIER_FINDER);
    } else {
      throw new InvalidKeyException("unknown key algorithm of the public key " + keyAlg);
    }
    VERIFIER_PROVIDER_BUILDER.put(keyAlg, builder);
  }

  AsymmetricKeyParameter keyParam = generatePublicKeyParameter(publicKey);
  try {
    return builder.build(keyParam);
  } catch (OperatorCreationException ex) {
    throw new InvalidKeyException("could not build ContentVerifierProvider: " + ex.getMessage(),
        ex);
  }
}
 
Example #13
Source File: KeyUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static AsymmetricKeyParameter generatePublicKeyParameter(PublicKey key)
    throws InvalidKeyException {
  Args.notNull(key, "key");

  if (key instanceof RSAPublicKey) {
    RSAPublicKey rsaKey = (RSAPublicKey) key;
    return new RSAKeyParameters(false, rsaKey.getModulus(), rsaKey.getPublicExponent());
  } else if (key instanceof ECPublicKey) {
    return ECUtil.generatePublicKeyParameter(key);
  } else if (key instanceof DSAPublicKey) {
    return DSAUtil.generatePublicKeyParameter(key);
  } else if (key instanceof XDHKey || key instanceof EdDSAKey) {
    byte[] encoded = key.getEncoded();
    String algorithm = key.getAlgorithm().toUpperCase();
    if (EdECConstants.X25519.equals(algorithm)) {
      return new X25519PublicKeyParameters(encoded, encoded.length - 32);
    } else if (EdECConstants.ED25519.equals(algorithm)) {
      return new Ed25519PublicKeyParameters(encoded, encoded.length - 32);
    } else if (EdECConstants.X448.equals(algorithm)) {
      return new X448PublicKeyParameters(encoded, encoded.length - 56);
    } else if (EdECConstants.ED448.equals(algorithm)) {
      return new Ed448PublicKeyParameters(encoded, encoded.length - 57);
    } else {
      throw new InvalidKeyException("unknown Edwards key " + algorithm);
    }
  } else {
    throw new InvalidKeyException("unknown key " + key.getClass().getName());
  }
}
 
Example #14
Source File: SignerUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static ContentVerifierProvider getContentVerifierProvider(PublicKey publicKey,
    DHSigStaticKeyCertPair ownerKeyAndCert) throws InvalidKeyException {
  Args.notNull(publicKey, "publicKey");

  String keyAlg = publicKey.getAlgorithm().toUpperCase();
  if ("ED25519".equals(keyAlg) || "ED448".equals(keyAlg)) {
    return new XiEdDSAContentVerifierProvider(publicKey);
  } else if ("X25519".equals(keyAlg) || "X448".equals(keyAlg)) {
    if (ownerKeyAndCert == null) {
      throw new InvalidKeyException("ownerKeyAndCert is required but absent");
    }
    return new XiXDHContentVerifierProvider(publicKey, ownerKeyAndCert);
  }

  BcContentVerifierProviderBuilder builder = VERIFIER_PROVIDER_BUILDER.get(keyAlg);

  if (builder == null) {
    if ("RSA".equals(keyAlg)) {
      builder = new XiRSAContentVerifierProviderBuilder(DIGESTALG_IDENTIFIER_FINDER);
    } else if ("DSA".equals(keyAlg)) {
      builder = new BcDSAContentVerifierProviderBuilder(DIGESTALG_IDENTIFIER_FINDER);
    } else if ("EC".equals(keyAlg) || "ECDSA".equals(keyAlg)) {
      builder = new XiECContentVerifierProviderBuilder(DIGESTALG_IDENTIFIER_FINDER);
    } else {
      throw new InvalidKeyException("unknown key algorithm of the public key " + keyAlg);
    }
    VERIFIER_PROVIDER_BUILDER.put(keyAlg, builder);
  }

  AsymmetricKeyParameter keyParam = KeyUtil.generatePublicKeyParameter(publicKey);
  try {
    return builder.build(keyParam);
  } catch (OperatorCreationException ex) {
    throw new InvalidKeyException("could not build ContentVerifierProvider: "
        + ex.getMessage(), ex);
  }
}
 
Example #15
Source File: DSAPlainDigestSigner.java    From xipki with Apache License 2.0 5 votes vote down vote up
@Override
public void init(boolean forSigning, CipherParameters parameters) {
  this.forSigning = forSigning;

  AsymmetricKeyParameter param = (parameters instanceof ParametersWithRandom)
      ? (AsymmetricKeyParameter) ((ParametersWithRandom) parameters).getParameters()
      : (AsymmetricKeyParameter) parameters;

  Args.notNull(param, "param");
  if (param instanceof ECPublicKeyParameters) {
    keyBitLen = ((ECPublicKeyParameters) param).getParameters().getCurve().getFieldSize();
  } else if (param instanceof ECPrivateKeyParameters) {
    keyBitLen = ((ECPrivateKeyParameters) param).getParameters().getCurve().getFieldSize();
  } else if (param instanceof DSAPublicKeyParameters) {
    keyBitLen = ((DSAPublicKeyParameters) param).getParameters().getQ().bitLength();
  } else if (param instanceof DSAPrivateKeyParameters) {
    keyBitLen = ((DSAPrivateKeyParameters) param).getParameters().getQ().bitLength();
  } else {
    throw new IllegalArgumentException("unknown parameters: " + param.getClass().getName());
  }

  if (forSigning && !param.isPrivate()) {
    throw new IllegalArgumentException("Signing Requires Private Key.");
  }

  if (!forSigning && param.isPrivate()) {
    throw new IllegalArgumentException("Verification Requires Public Key.");
  }

  reset();
  dsaSigner.init(forSigning, parameters);
}
 
Example #16
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 #17
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 #18
Source File: CertificateManager.java    From Launcher with GNU General Public License v3.0 4 votes vote down vote up
public void writePrivateKey(Path file, AsymmetricKeyParameter key) throws IOException {
    writePrivateKey(IOHelper.newWriter(file), key);
}
 
Example #19
Source File: CertificateManager.java    From Launcher with GNU General Public License v3.0 4 votes vote down vote up
public void writePrivateKey(Writer writer, AsymmetricKeyParameter key) throws IOException {
    PrivateKeyInfo info = PrivateKeyInfoFactory.createPrivateKeyInfo(key);
    try (PemWriter writer1 = new PemWriter(writer)) {
        writer1.writeObject(new PemObject("PRIVATE KEY", info.getEncoded()));
    }
}
 
Example #20
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 #21
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 #22
Source File: CertificateManager.java    From Launcher with GNU General Public License v3.0 4 votes vote down vote up
public AsymmetricKeyParameter readPrivateKey(Path file) throws IOException {
    return readPrivateKey(IOHelper.newReader(file));
}
 
Example #23
Source File: DViewCSR.java    From portecle with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Populate the dialog with the currently selected certificate request's details.
 *
 * @throws CryptoException A problem was encountered getting the certificate request's details
 */
private void populateDialog()
    throws CryptoException
{
	// Version
	m_jtfVersion.setText(m_req.toASN1Structure().getCertificationRequestInfo().getVersion().getValue().toString());
	m_jtfVersion.setCaretPosition(0);

	// Subject
	X500Name subject = m_req.getSubject();
	m_jtfSubject.setText(subject.toString());
	m_jtfSubject.setCaretPosition(0);

	m_basename = NameUtil.getCommonName(subject);

	// Public Key (algorithm and keysize)
	SubjectPublicKeyInfo keyInfo = m_req.getSubjectPublicKeyInfo();

	AsymmetricKeyParameter keyParams;
	try
	{
		keyParams = PublicKeyFactory.createKey(keyInfo);
	}
	catch (IOException e)
	{
		throw new CryptoException(RB.getString("DViewCSR.NoGetKeyInfo.exception.message"), e);
	}

	m_jtfPublicKey.setText(AlgorithmType.toString(keyInfo.getAlgorithm().getAlgorithm().toString()));

	int iKeySize = KeyPairUtil.getKeyLength(keyParams);
	if (iKeySize != KeyPairUtil.UNKNOWN_KEY_SIZE)
	{
		m_jtfPublicKey.setText(
		    MessageFormat.format(RB.getString("DViewCSR.m_jtfPublicKey.text"), m_jtfPublicKey.getText(), iKeySize));
	}
	m_jtfPublicKey.setCaretPosition(0);

	// Signature Algorithm
	String sigAlgName = SignatureType.toString(m_req.getSignatureAlgorithm().getAlgorithm().toString());
	m_jtfSignatureAlgorithm.setText(sigAlgName);
	m_jtfSignatureAlgorithm.setCaretPosition(0);

	// TODO: attributes, requested extensions
}
 
Example #24
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 #25
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;
}