Example usage for java.security KeyPairGenerator initialize

List of usage examples for java.security KeyPairGenerator initialize

Introduction

In this page you can find the example usage for java.security KeyPairGenerator initialize.

Prototype

public void initialize(AlgorithmParameterSpec params, SecureRandom random)
        throws InvalidAlgorithmParameterException 

Source Link

Document

Initializes the key pair generator with the given parameter set and source of randomness.

Usage

From source file:test.be.fedict.eid.applet.RSATest.java

@Test
public void testManualEncryption() throws Exception {
    while (true) {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA",
                BouncyCastleProvider.PROVIDER_NAME);
        SecureRandom random = new SecureRandom();
        int keySize = 128;
        keyPairGenerator.initialize(new RSAKeyGenParameterSpec(keySize, RSAKeyGenParameterSpec.F0), random);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        PrivateKey privateKey = keyPair.getPrivate();
        PublicKey publicKey = keyPair.getPublic();
        RSAPrivateCrtKey rsaPrivateKey = (RSAPrivateCrtKey) privateKey;
        LOG.debug("private key modulus: " + rsaPrivateKey.getModulus());
        RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
        LOG.debug("public key modulus: " + rsaPublicKey.getModulus());
        LOG.debug("public key exponent: " + rsaPublicKey.getPublicExponent());
        LOG.debug("modulus size: " + rsaPublicKey.getModulus().toByteArray().length);

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);

        int dataSize = keySize / 8 - 11;
        byte[] data1 = new byte[dataSize];
        for (int i = 0; i < data1.length; i++) {
            data1[i] = 0x00;//from   w w w. j ava2  s  .c  o  m
        }
        byte[] data2 = new byte[dataSize];
        for (int i = 0; i < data2.length; i++) {
            data2[i] = 0x00;
        }
        data2[data2.length - 1] = 0x07;

        byte[] signatureValue1 = cipher.doFinal(data1);

        LOG.debug("signature size: " + signatureValue1.length);

        cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        byte[] signatureValue2 = cipher.doFinal(data2);

        BigInteger sigBigInt1 = new BigInteger(signatureValue1);
        BigInteger sigBigInt2 = new BigInteger(signatureValue2);
        BigInteger msgBigInt1 = sigBigInt1.modPow(rsaPublicKey.getPublicExponent(), rsaPublicKey.getModulus());
        BigInteger msgBigInt2 = sigBigInt2.modPow(rsaPublicKey.getPublicExponent(), rsaPublicKey.getModulus());
        LOG.debug("msg big int: " + msgBigInt1);
        byte[] msgBytes1 = msgBigInt1.toByteArray();
        LOG.debug("original message size: " + msgBytes1.length);
        LOG.debug("original message1: " + new String(Hex.encodeHex(msgBytes1)));
        LOG.debug("original message2: " + new String(Hex.encodeHex(msgBigInt2.toByteArray())));

        LOG.debug("msg1 prime: " + msgBigInt1.isProbablePrime(100));
        LOG.debug("msg2 prime: " + msgBigInt2.isProbablePrime(100));

        // BigInteger.pow offers a very naive implementation
        LOG.debug("calculating s1^e...");
        BigInteger s1_e = sigBigInt1.pow(rsaPublicKey.getPublicExponent().intValue());
        LOG.debug("s1^e: " + s1_e);
        LOG.debug("calculating s2^e...");
        BigInteger s2_e = sigBigInt2.pow(rsaPublicKey.getPublicExponent().intValue());
        LOG.debug("s2^e: " + s2_e);

        LOG.debug("calculating GCD...");
        LOG.debug("msg1: " + msgBigInt1);
        LOG.debug("msg2: " + msgBigInt2);
        BigInteger a = s1_e.subtract(msgBigInt1);
        BigInteger b = s2_e.subtract(msgBigInt2);
        LOG.debug("a: " + a);
        LOG.debug("b: " + b);
        BigInteger candidateModulus = a.gcd(b);
        LOG.debug("candidate modulus: " + candidateModulus);
        LOG.debug("candidate modulus size: " + candidateModulus.toByteArray().length);
        BigInteger s_e = s1_e.multiply(s2_e);
        BigInteger m = msgBigInt1.multiply(msgBigInt2);
        while (false == rsaPublicKey.getModulus().equals(candidateModulus)) {
            LOG.error("incorrect candidate modulus");
            LOG.debug("modulus | candidate modulus: "
                    + candidateModulus.remainder(rsaPublicKey.getModulus()).equals(BigInteger.ZERO));
            s_e = s_e.multiply(s1_e);
            m = m.multiply(msgBigInt1);
            BigInteger n1 = s_e.subtract(m).gcd(a);
            BigInteger n2 = s_e.subtract(m).gcd(b);
            candidateModulus = n1.gcd(n2);
            // try / 2
            LOG.debug("new modulus:       " + n1);
            LOG.debug("new modulus:       " + n2);
            LOG.debug("candidate modulus: " + candidateModulus);
            LOG.debug("actual mod:        " + rsaPublicKey.getModulus());
        }
    }
}

From source file:org.apache.drill.cv.exec.server.rest.CvDrillWebServer.java

/**
 * Create an HTTPS connector for given jetty server instance. If the admin has specified
 * keystore/truststore settings they will be used else a self-signed certificate is generated and
 * used.//from ww w .ja  v  a  2s .  c o  m
 *
 * @return Initialized {@link ServerConnector} for HTTPS connectios.
 * @throws Exception
 */
private ServerConnector createHttpsConnector() throws Exception {
    CvDrillWebServer.logger.info("Setting up HTTPS connector for web server");

    final SslContextFactory sslContextFactory = new SslContextFactory();

    if (config.hasPath(ExecConstants.HTTP_KEYSTORE_PATH)
            && !Strings.isNullOrEmpty(config.getString(ExecConstants.HTTP_KEYSTORE_PATH))) {
        CvDrillWebServer.logger.info("Using configured SSL settings for web server");
        sslContextFactory.setKeyStorePath(config.getString(ExecConstants.HTTP_KEYSTORE_PATH));
        sslContextFactory.setKeyStorePassword(config.getString(ExecConstants.HTTP_KEYSTORE_PASSWORD));

        // TrustStore and TrustStore password are optional
        if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PATH)) {
            sslContextFactory.setTrustStorePath(config.getString(ExecConstants.HTTP_TRUSTSTORE_PATH));
            if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)) {
                sslContextFactory
                        .setTrustStorePassword(config.getString(ExecConstants.HTTP_TRUSTSTORE_PASSWORD));
            }
        }
    } else {
        CvDrillWebServer.logger.info("Using generated self-signed SSL settings for web server");
        final SecureRandom random = new SecureRandom();

        // Generate a private-public key pair
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024, random);
        final KeyPair keyPair = keyPairGenerator.generateKeyPair();

        final DateTime now = DateTime.now();

        // Create builder for certificate attributes
        final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE)
                .addRDN(BCStyle.OU, "Apache Drill (auth-generated)")
                .addRDN(BCStyle.O, "Apache Software Foundation (auto-generated)")
                .addRDN(BCStyle.CN, workManager.getContext().getEndpoint().getAddress());

        final Date notBefore = now.minusMinutes(1).toDate();
        final Date notAfter = now.plusYears(5).toDate();
        final BigInteger serialNumber = new BigInteger(128, random);

        // Create a certificate valid for 5years from now.
        final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), // attributes
                serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic());

        // Sign the certificate using the private key
        final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
                .build(keyPair.getPrivate());
        final X509Certificate certificate = new JcaX509CertificateConverter()
                .getCertificate(certificateBuilder.build(contentSigner));

        // Check the validity
        certificate.checkValidity(now.toDate());

        // Make sure the certificate is self-signed.
        certificate.verify(certificate.getPublicKey());

        // Generate a random password for keystore protection
        final String keyStorePasswd = RandomStringUtils.random(20);
        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null, null);
        keyStore.setKeyEntry("DrillAutoGeneratedCert", keyPair.getPrivate(), keyStorePasswd.toCharArray(),
                new java.security.cert.Certificate[] { certificate });

        sslContextFactory.setKeyStore(keyStore);
        sslContextFactory.setKeyStorePassword(keyStorePasswd);
    }

    final HttpConfiguration httpsConfig = new HttpConfiguration();
    httpsConfig.addCustomizer(new SecureRequestCustomizer());

    // SSL Connector
    final ServerConnector sslConnector = new ServerConnector(embeddedJetty,
            new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
            new HttpConnectionFactory(httpsConfig));
    sslConnector.setPort(getWebserverPort());

    return sslConnector;
}

From source file:org.guanxi.idp.Bootstrap.java

public boolean createSelfSignedKeystore(String cn, String keystoreFile, String keystorePassword,
        String privateKeyPassword, String privateKeyAlias) {
    KeyStore ks = null;/*ww  w .  ja v  a 2  s  .c o m*/

    try {
        ks = KeyStore.getInstance("JKS");
        ks.load(null, null);

        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
        keyGen.initialize(1024, new SecureRandom());
        KeyPair keypair = keyGen.generateKeyPair();
        PrivateKey privkey = keypair.getPrivate();
        PublicKey pubkey = keypair.getPublic();

        Hashtable<DERObjectIdentifier, String> attrs = new Hashtable<DERObjectIdentifier, String>();
        Vector<DERObjectIdentifier> ordering = new Vector<DERObjectIdentifier>();
        ordering.add(X509Name.CN);
        attrs.put(X509Name.CN, cn);
        X509Name issuerDN = new X509Name(ordering, attrs);
        X509Name subjectDN = new X509Name(ordering, attrs);

        Date validFrom = new Date();
        validFrom.setTime(validFrom.getTime() - (10 * 60 * 1000));
        Date validTo = new Date();
        validTo.setTime(validTo.getTime() + (20 * (24 * 60 * 60 * 1000)));

        X509V3CertificateGenerator x509 = new X509V3CertificateGenerator();
        x509.setSignatureAlgorithm("SHA1withDSA");
        x509.setIssuerDN(issuerDN);
        x509.setSubjectDN(subjectDN);
        x509.setPublicKey(pubkey);
        x509.setNotBefore(validFrom);
        x509.setNotAfter(validTo);
        x509.setSerialNumber(new BigInteger(128, new Random()));

        X509Certificate[] cert = new X509Certificate[1];
        cert[0] = x509.generate(privkey, "BC");
        java.security.cert.Certificate[] chain = new java.security.cert.Certificate[1];
        chain[0] = cert[0];

        ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), cert);
        ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), chain);
        ks.store(new FileOutputStream(keystoreFile), keystorePassword.toCharArray());

        String IDP_RFC_CERT = "WEB-INF/guanxi_idp/keystore/guanxi_idp_cert.txt";

        PEMWriter pemWriter = new PEMWriter(new FileWriter(servletContext.getRealPath(IDP_RFC_CERT)));
        pemWriter.writeObject(cert[0]);
        pemWriter.close();

        return true;
    } catch (Exception se) {
        return false;
    }
}

From source file:com.POLIS.licensing.frontend.AnnotationEnabledFrontendTest.java

@Before
public void setUp()
        throws NoSuchAlgorithmException, NoSuchProviderException, SystemStateException, OperationException {
    frontend = new AnnotationEnabledFrontend<>(new TestFactory(), new TestConnector(), new TestDecorator());

    SecureRandom random = new SecureRandom();
    KeyPairGenerator rsagenerator = KeyPairGenerator.getInstance("RSA", "BC");
    rsagenerator.initialize(1024, random);
    KeyPair pair = rsagenerator.generateKeyPair();
    serverPubKey = pair.getPublic();/*  w  w  w  .j a v  a  2s .com*/
    serverPrivKey = pair.getPrivate();
    frontend.initialize(serverPubKey);
}

From source file:test.unit.be.agiv.security.handler.WSSecurityHandlerTest.java

private KeyPair generateKeyPair(int keySize) throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    SecureRandom random = new SecureRandom();
    keyPairGenerator.initialize(new RSAKeyGenParameterSpec(keySize, RSAKeyGenParameterSpec.F4), random);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    return keyPair;
}

From source file:com.cellngine.crypto.RSACipher.java

@Override
public void generateKeypair(final int keyLength) {
    if (keyLength <= 0) {
        throw new IllegalArgumentException("Key length must be positive and nonzero");
    }/*from   w w  w. ja v a  2s . co  m*/

    final KeyPairGenerator generator;
    try {
        generator = KeyPairGenerator.getInstance(ALGORITHM);
    } catch (final NoSuchAlgorithmException e) {
        LOG.error("Unable to get key generator instance (" + ALGORITHM + ")", e);
        return;
    }

    try {
        generator.initialize(keyLength, this.random);
    } catch (final InvalidParameterException e) {
        throw new IllegalArgumentException("Unsupported key length");
    }

    final KeyPair pair = generator.generateKeyPair();
    this.publicKey = pair.getPublic();
    this.privateKey = pair.getPrivate();
}

From source file:org.wso2.carbon.device.mgt.iot.agent.firealarm.enrollment.EnrollmentManager.java

/**
 * This method creates the Public-Private Key pair for the current client.
 *
 * @return the generated KeyPair object/*from  www .j  a v  a2s .co m*/
 * @throws AgentCoreOperationException when the given Security Provider does not exist or the Algorithmn used to
 *                                     generate the key pair is invalid.
 */
private KeyPair generateKeyPair() throws AgentCoreOperationException {

    // Generate our key pair
    KeyPairGenerator keyPairGenerator;
    try {
        keyPairGenerator = KeyPairGenerator.getInstance(KEY_PAIR_ALGORITHM, PROVIDER);
        keyPairGenerator.initialize(KEY_SIZE, new SecureRandom(SEED));
    } catch (NoSuchAlgorithmException e) {
        String errorMsg = "Algorithm [" + KEY_PAIR_ALGORITHM + "] provided for KeyPairGenerator is invalid.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    } catch (NoSuchProviderException e) {
        String errorMsg = "Provider [" + PROVIDER + "] provided for KeyPairGenerator does not exist.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    }

    return keyPairGenerator.genKeyPair();
}

From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.enrollment.EnrollmentManager.java

/**
 * This method creates the Public-Private Key pair for the current client.
 *
 * @return the generated KeyPair object/*from  w w  w . j ava2  s. co m*/
 * @throws AgentCoreOperationException when the given Security Provider does not exist or the Algorithmn used to
 *                                     generate the key pair is invalid.
 */
private KeyPair generateKeyPair() throws AgentCoreOperationException {

    // Generate key pair
    KeyPairGenerator keyPairGenerator;
    try {
        keyPairGenerator = KeyPairGenerator.getInstance(KEY_PAIR_ALGORITHM, PROVIDER);
        keyPairGenerator.initialize(KEY_SIZE, new SecureRandom(SEED));
    } catch (NoSuchAlgorithmException e) {
        String errorMsg = "Algorithm [" + KEY_PAIR_ALGORITHM + "] provided for KeyPairGenerator is invalid.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    } catch (NoSuchProviderException e) {
        String errorMsg = "Provider [" + PROVIDER + "] provided for KeyPairGenerator does not exist.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    }

    return keyPairGenerator.genKeyPair();
}

From source file:org.apache.drill.yarn.appMaster.http.WebServer.java

/**
 * Create an HTTPS connector for given jetty server instance. If the admin has
 * specified keystore/truststore settings they will be used else a self-signed
 * certificate is generated and used.//from  w  w  w . j  a v a2  s .  c  om
 * <p>
 * This is a shameless copy of
 * {@link org.apache.drill.exec.server.rest.Webserver#createHttpsConnector( )}.
 * The two should be merged at some point. The primary issue is that the Drill
 * version is tightly coupled to Drillbit configuration.
 *
 * @return Initialized {@link ServerConnector} for HTTPS connections.
 * @throws Exception
 */

private ServerConnector createHttpsConnector(Config config) throws Exception {
    LOG.info("Setting up HTTPS connector for web server");

    final SslContextFactory sslContextFactory = new SslContextFactory();

    // if (config.hasPath(ExecConstants.HTTP_KEYSTORE_PATH) &&
    // !Strings.isNullOrEmpty(config.getString(ExecConstants.HTTP_KEYSTORE_PATH)))
    // {
    // LOG.info("Using configured SSL settings for web server");
    // sslContextFactory.setKeyStorePath(config.getString(ExecConstants.HTTP_KEYSTORE_PATH));
    // sslContextFactory.setKeyStorePassword(config.getString(ExecConstants.HTTP_KEYSTORE_PASSWORD));
    //
    // // TrustStore and TrustStore password are optional
    // if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PATH)) {
    // sslContextFactory.setTrustStorePath(config.getString(ExecConstants.HTTP_TRUSTSTORE_PATH));
    // if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)) {
    // sslContextFactory.setTrustStorePassword(config.getString(ExecConstants.HTTP_TRUSTSTORE_PASSWORD));
    // }
    // }
    // } else {
    LOG.info("Using generated self-signed SSL settings for web server");
    final SecureRandom random = new SecureRandom();

    // Generate a private-public key pair
    final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024, random);
    final KeyPair keyPair = keyPairGenerator.generateKeyPair();

    final DateTime now = DateTime.now();

    // Create builder for certificate attributes
    final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE)
            .addRDN(BCStyle.OU, "Apache Drill (auth-generated)")
            .addRDN(BCStyle.O, "Apache Software Foundation (auto-generated)").addRDN(BCStyle.CN, "Drill AM");

    final Date notBefore = now.minusMinutes(1).toDate();
    final Date notAfter = now.plusYears(5).toDate();
    final BigInteger serialNumber = new BigInteger(128, random);

    // Create a certificate valid for 5years from now.
    final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), // attributes
            serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic());

    // Sign the certificate using the private key
    final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
            .build(keyPair.getPrivate());
    final X509Certificate certificate = new JcaX509CertificateConverter()
            .getCertificate(certificateBuilder.build(contentSigner));

    // Check the validity
    certificate.checkValidity(now.toDate());

    // Make sure the certificate is self-signed.
    certificate.verify(certificate.getPublicKey());

    // Generate a random password for keystore protection
    final String keyStorePasswd = RandomStringUtils.random(20);
    final KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(null, null);
    keyStore.setKeyEntry("DrillAutoGeneratedCert", keyPair.getPrivate(), keyStorePasswd.toCharArray(),
            new java.security.cert.Certificate[] { certificate });

    sslContextFactory.setKeyStore(keyStore);
    sslContextFactory.setKeyStorePassword(keyStorePasswd);
    // }

    final HttpConfiguration httpsConfig = new HttpConfiguration();
    httpsConfig.addCustomizer(new SecureRequestCustomizer());

    // SSL Connector
    final ServerConnector sslConnector = new ServerConnector(jettyServer,
            new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
            new HttpConnectionFactory(httpsConfig));
    sslConnector.setPort(config.getInt(DrillOnYarnConfig.HTTP_PORT));

    return sslConnector;
}

From source file:com.wandrell.util.ksgen.BouncyCastleKeyStoreFactory.java

/**
 * Creates a key pair.//from  www  .  j  ava2  s . c o m
 *
 * @return the key pair
 * @throws NoSuchAlgorithmException
 *             if the required algorithm for the key pair does not exist
 */
private final KeyPair getKeyPair() throws NoSuchAlgorithmException {
    final KeyPairGenerator keyPairGenerator; // Key pair generator
    final KeyPair keypair; // Key pair

    keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024, new SecureRandom());

    keypair = keyPairGenerator.generateKeyPair();

    LOGGER.debug("Created key pair with private key {} {} and public key {} {}",
            keypair.getPrivate().getAlgorithm(), Arrays.asList(keypair.getPrivate().getEncoded()),
            keypair.getPublic().getAlgorithm(), Arrays.asList(keypair.getPublic().getEncoded()));

    return keypair;
}