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:com.vmware.identity.sts.auth.impl.UserCertAuthenticatorTest.java

@BeforeClass
public static void setUp() throws Exception {
    // create key pair and client private key, certificate
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(1024, new SecureRandom());
    KeyPair userKeyPair = keyGen.generateKeyPair();
    userPrivateKey = (RSAPrivateKey) userKeyPair.getPrivate();
    x509Certificate = generateCertificate(userKeyPair, "User");
}

From source file:org.psl.fidouaf.core.crypto.KeyCodec.java

public static KeyPair getKeyPair()
        throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException {
    // ECGenParameterSpec ecGenSpec = new ECGenParameterSpec("prime192v1");
    ECGenParameterSpec ecGenSpec = new ECGenParameterSpec("secp256r1");
    KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC");
    g.initialize(ecGenSpec, new SecureRandom());
    return g.generateKeyPair();
}

From source file:org.zaproxy.zap.extension.dynssl.SslCertificateUtils.java

/**
 * Creates a new Root CA certificate and returns private and public key as
 * {@link KeyStore}. The {@link KeyStore#getDefaultType()} is used.
 *
 * @return/* w w w.jav  a2  s  .c  o m*/
 * @throws NoSuchAlgorithmException If no providers are found
 * for 'RSA' key pair generator
 * or 'SHA1PRNG' Secure random number generator
 * @throws IllegalStateException in case of errors during assembling {@link KeyStore}
 */
public static final KeyStore createRootCA() throws NoSuchAlgorithmException {
    final Date startDate = Calendar.getInstance().getTime();
    final Date expireDate = new Date(startDate.getTime() + (DEFAULT_VALID_DAYS * 24L * 60L * 60L * 1000L));

    final KeyPairGenerator g = KeyPairGenerator.getInstance("RSA");
    g.initialize(2048, SecureRandom.getInstance("SHA1PRNG"));
    final KeyPair keypair = g.genKeyPair();
    final PrivateKey privKey = keypair.getPrivate();
    final PublicKey pubKey = keypair.getPublic();
    Security.addProvider(new BouncyCastleProvider());
    Random rnd = new Random();

    // using the hash code of the user's name and home path, keeps anonymity
    // but also gives user a chance to distinguish between each other
    X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE);
    namebld.addRDN(BCStyle.CN, "OWASP Zed Attack Proxy Root CA");
    namebld.addRDN(BCStyle.L, Integer.toHexString(System.getProperty("user.name").hashCode())
            + Integer.toHexString(System.getProperty("user.home").hashCode()));
    namebld.addRDN(BCStyle.O, "OWASP Root CA");
    namebld.addRDN(BCStyle.OU, "OWASP ZAP Root CA");
    namebld.addRDN(BCStyle.C, "xx");

    X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(namebld.build(),
            BigInteger.valueOf(rnd.nextInt()), startDate, expireDate, namebld.build(), pubKey);

    KeyStore ks = null;
    try {
        certGen.addExtension(Extension.subjectKeyIdentifier, false,
                new SubjectKeyIdentifier(pubKey.getEncoded()));
        certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
        certGen.addExtension(Extension.keyUsage, false,
                new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment
                        | KeyUsage.dataEncipherment | KeyUsage.cRLSign));

        KeyPurposeId[] eku = { KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth,
                KeyPurposeId.anyExtendedKeyUsage };
        certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(eku));

        final ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC")
                .build(privKey);
        final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC")
                .getCertificate(certGen.build(sigGen));

        ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null, null);
        ks.setKeyEntry(SslCertificateService.ZAPROXY_JKS_ALIAS, privKey, SslCertificateService.PASSPHRASE,
                new Certificate[] { cert });
    } catch (final Exception e) {
        throw new IllegalStateException("Errors during assembling root CA.", e);
    }
    return ks;
}

From source file:co.cask.cdap.security.tools.KeyStores.java

/**
 * Create a Java key store with a stored self-signed certificate.
 * @return Java keystore which has a self signed X.509 certificate
 *///from   w  ww  .  java 2 s.com
public static KeyStore generatedCertKeyStore(SConfiguration sConf, String password) {
    try {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance(KEY_PAIR_ALGORITHM);
        SecureRandom random = SecureRandom.getInstance(SECURE_RANDOM_ALGORITHM, SECURE_RANDOM_PROVIDER);
        keyGen.initialize(KEY_SIZE, random);
        // generate a key pair
        KeyPair pair = keyGen.generateKeyPair();
        int validity = sConf.getInt(Constants.Security.SSL.CERT_VALIDITY, VALIDITY);

        X509Certificate cert = getCertificate(DISTINGUISHED_NAME, pair, validity, SIGNATURE_ALGORITHM);

        KeyStore keyStore = KeyStore.getInstance(SSL_KEYSTORE_TYPE);
        keyStore.load(null, password.toCharArray());
        keyStore.setKeyEntry(CERT_ALIAS, pair.getPrivate(), password.toCharArray(),
                new java.security.cert.Certificate[] { cert });
        return keyStore;
    } catch (Exception e) {
        throw new RuntimeException(
                "SSL is enabled but a key store file could not be created. A keystore is required "
                        + "for SSL to be used.",
                e);
    }
}

From source file:net.solarnetwork.node.setup.test.DefaultSetupServiceTest.java

@BeforeClass
public static void setupClass() throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(2048, new SecureRandom());
    CA_KEY_PAIR = keyGen.generateKeyPair();
    CA_CERT = PKITestUtils.generateNewCACert(CA_KEY_PAIR.getPublic(), TEST_CA_DN, null,
            CA_KEY_PAIR.getPrivate(), TEST_CA_DN);
}

From source file:org.javaweb.utils.RSAUtils.java

/**
 * ?RSA?//from www . j  a  v a 2  s . c  o  m
 *
 * @param keySize
 * @return
 * @throws NoSuchAlgorithmException
 */
public static KeyPair generateKey(int keySize) throws NoSuchAlgorithmException {
    KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
    SecureRandom random = new SecureRandom();
    keygen.initialize(keySize, random);

    return keygen.generateKeyPair();
}

From source file:net.solarnetwork.node.setup.test.DefaultKeystoreServiceTest.java

@BeforeClass
public static void setupClass() throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(2048, new SecureRandom());
    CA_KEY_PAIR = keyGen.generateKeyPair();
    CA_CERT = PKITestUtils.generateNewCACert(CA_KEY_PAIR.getPublic(), TEST_CA_DN, null,
            CA_KEY_PAIR.getPrivate(), TEST_CA_DN);

    CA_SUB_KEY_PAIR = keyGen.generateKeyPair();
    CA_SUB_CERT = PKITestUtils.generateNewCACert(CA_SUB_KEY_PAIR.getPublic(), TEST_CA_SUB_DN, CA_CERT,
            CA_KEY_PAIR.getPrivate(), TEST_CA_DN);
}

From source file:com.aaasec.sigserv.cssigapp.KeyStoreFactory.java

private static KeyPair generateECDSAKeyPair()
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
    ECGenParameterSpec ecSpec = new ECGenParameterSpec("P-256");

    KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC");
    g.initialize(ecSpec, new SecureRandom());
    KeyPair pair = g.generateKeyPair();
    return pair;//  w  w  w .  j av  a 2 s.c  o m
}

From source file:com.aqnote.shared.cryptology.asymmetric.DSA.java

public static KeyPair genKeyPair(int bit) {
    try {/*  ww  w. j  a  v  a 2  s. c om*/
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(ALGORITHM, JCE_PROVIDER);
        keyPairGen.initialize(bit, new SecureRandom());
        return keyPairGen.generateKeyPair();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.apache.cloudstack.utils.auth.SAMLUtils.java

public static KeyPair generateRandomKeyPair() throws NoSuchProviderException, NoSuchAlgorithmException {
    Security.addProvider(new BouncyCastleProvider());
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
    keyPairGenerator.initialize(2048, new SecureRandom());
    return keyPairGenerator.generateKeyPair();
}