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.iterzp.momo.utils.RSAUtils.java

/**
 * ?//from  ww w  . j  a  v  a 2s.  c om
 * 
 * @return 
 */
public static KeyPair generateKeyPair() {
    try {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", PROVIDER);
        keyPairGenerator.initialize(KEY_SIZE, new SecureRandom());
        return keyPairGenerator.generateKeyPair();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:Main.java

public static KeyPair generateKeyPair(int keySize) throws NoSuchAlgorithmException, NoSuchProviderException {
    KeyPairGenerator generator = KeyPairGenerator.getInstance(KEYGEN_ALGORITHM/* , PROVIDER_NAME */);
    SecureRandom secureRandom = SecureRandom.getInstance(SECURE_RANDOM_ALGORITHM/* , PROVIDER_NAME */);
    generator.initialize(keySize, secureRandom);
    return generator.generateKeyPair();
}

From source file:com.vimukti.accounter.developer.api.PublicKeyGenerator.java

private static void generate() throws NoSuchAlgorithmException, NoSuchProviderException,
        InvalidKeySpecException, KeyStoreException, CertificateException, IOException, URISyntaxException {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed("VimTech".getBytes("UTF-8"));
    keyGen.initialize(1024, random);

    KeyPair pair = keyGen.generateKeyPair();
    PrivateKey priv = pair.getPrivate();
    PublicKey pub = pair.getPublic();
    System.out.println(priv);/*  w  ww . j a  v  a 2 s . co  m*/
    System.out.println(pub);

    byte[] encoded = pub.getEncoded();
    byte[] encodeBase64 = Base64.encodeBase64(encoded);
    System.out.println("Public Key:" + new String(encodeBase64));

    byte[] encodedPrv = priv.getEncoded();
    byte[] encodeBase64Prv = Base64.encodeBase64(encodedPrv);
    System.out.println("Private Key:" + new String(encodeBase64Prv));

    byte[] decodeBase64 = Base64.decodeBase64(encodeBase64);
    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(decodeBase64);
    KeyFactory keyFactory = KeyFactory.getInstance("DSA");

    System.out.println(keyFactory.generatePublic(pubKeySpec).equals(pub));
}

From source file:org.apache.abdera.security.util.KeyHelper.java

public static KeyPair generateKeyPair(String type, int size)
        throws NoSuchAlgorithmException, NoSuchProviderException {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(type);
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    keyGen.initialize(size, random);
    random.setSeed(System.currentTimeMillis());
    return keyGen.generateKeyPair();
}

From source file:org.ebayopensource.fido.uaf.crypto.KeyCodec.java

public static KeyPair generate() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    SecureRandom random = new SecureRandom();
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp256r1");
    KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA");
    g.initialize(ecSpec, random);
    return g.generateKeyPair();
}

From source file:org.computerist.ssltools.zap.ZapSslCertificateUtils.java

/**
 * Creates a new Root CA certificate and returns private and public key as
 * {@link KeyStore}. The {@link KeyStore#getDefaultType()} is used.
 *
 * @return//from   www.ja va  2 s  . co  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();
    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(X509Extension.subjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(pubKey));
        certGen.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(true));
        certGen.addExtension(X509Extension.keyUsage, false,
                new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment
                        | KeyUsage.dataEncipherment | KeyUsage.cRLSign));

        Vector<DERObject> eku = new Vector<>(3, 1);
        eku.add(KeyPurposeId.id_kp_serverAuth);
        eku.add(KeyPurposeId.id_kp_clientAuth);
        eku.add(KeyPurposeId.anyExtendedKeyUsage);
        certGen.addExtension(X509Extension.extendedKeyUsage, false, new ExtendedKeyUsage(eku));

        final ContentSigner sigGen = new JcaContentSignerBuilder("SHA1WithRSAEncryption").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(FixedSslCertificateService.ZAPROXY_JKS_ALIAS, privKey,
                FixedSslCertificateService.PASSPHRASE, new Certificate[] { cert });
    } catch (final Exception e) {
        throw new IllegalStateException("Errors during assembling root CA.", e);
    }
    return ks;
}

From source file:org.ebayopensource.fido.uaf.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", "SC");
    g.initialize(ecGenSpec, new SecureRandom());
    return g.generateKeyPair();
}

From source file:org.wso2.carbon.identity.test.common.testng.utils.ReadCertStoreSampleUtil.java

public static KeyPair getSampleKeyPair() throws CertificateException, NoSuchAlgorithmException, IOException,
        InvalidKeyException, KeyStoreException, NoSuchProviderException, SignatureException {
    KeyStore keyStore = KeyStore.getInstance("JKS");
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "SHA1WithRSA");
    SecureRandom random = SecureRandom.getInstance("RSA", "SHA1WithRSA");
    keyGen.initialize(1024, random);
    KeyPair keypair = keyGen.generateKeyPair();
    return keypair;
}

From source file:org.apache.abdera.security.util.KeyHelper.java

public static KeyPair generateKeyPair(String type, int size, String provider)
        throws NoSuchAlgorithmException, NoSuchProviderException {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(type, provider);
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG", provider);
    keyGen.initialize(size, random);
    random.setSeed(System.currentTimeMillis());
    return keyGen.generateKeyPair();
}

From source file:org.excalibur.core.util.SecurityUtils2.java

public static UserKey generateUserKey() throws Exception {
    KeyPairGenerator kpg = SecurityUtils.getKeyPairGenerator("RSA");

    kpg.initialize(1024, new SecureRandom());
    java.security.KeyPair kp = kpg.generateKeyPair();

    String priv = getKeyMaterial(kp.getPrivate());

    byte[] encoded = encode((RSAPublicKey) kp.getPublic());

    //        String pub = getKeyMaterial(kp.getPublic()).replaceAll(PUBLIC_KEY_START, "").replaceAll(PUBLIC_KEY_END, "").trim();

    return new UserKey().setPrivateKeyMaterial(priv).setPublicKeyMaterial(new String(Base64.encode(encoded)))
            .setFingerPrint(getFingerPrint((RSAPublicKey) kp.getPublic()));
}