Example usage for java.security KeyPairGenerator genKeyPair

List of usage examples for java.security KeyPairGenerator genKeyPair

Introduction

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

Prototype

public final KeyPair genKeyPair() 

Source Link

Document

Generates a key pair.

Usage

From source file:net.padlocksoftware.padlock.KeyManager.java

/**
 * Create a 1024 bit DSA KeyPair./*from  w ww  .  j  a v a2s.c o m*/
 * @return A newly created DSA KeyPair.
 */
public static KeyPair createKeyPair() {
    KeyPair pair = null;

    try {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
        keyGen.initialize(1024);
        pair = keyGen.genKeyPair();
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(KeyManager.class.getName()).log(Level.SEVERE, null, ex);
    }

    return pair;
}

From source file:org.kde.kdeconnect.Helpers.SecurityHelpers.RsaHelper.java

public static void initialiseRsaKeys(Context context) {
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);

    if (!settings.contains("publicKey") || !settings.contains("privateKey")) {

        KeyPair keyPair;// w  ww .  j  a v  a2s  .c  o  m
        try {
            KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
            keyGen.initialize(2048);
            keyPair = keyGen.genKeyPair();
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("KDE/initializeRsaKeys", "Exception");
            return;
        }

        byte[] publicKey = keyPair.getPublic().getEncoded();
        byte[] privateKey = keyPair.getPrivate().getEncoded();

        SharedPreferences.Editor edit = settings.edit();
        edit.putString("publicKey", Base64.encodeToString(publicKey, 0).trim() + "\n");
        edit.putString("privateKey", Base64.encodeToString(privateKey, 0));
        edit.apply();

    }

}

From source file:edu.stanford.mobisocial.dungbeetle.DBIdentityProvider.java

public static KeyPair generateKeyPair() {
    try {/* w w  w. jav  a2  s  .c  om*/
        // Generate a 1024-bit Digital Signature Algorithm (RSA) key pair
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(1024);
        return keyGen.genKeyPair();
    } catch (java.security.NoSuchAlgorithmException e) {
        throw new IllegalStateException("Failed to generate key pair! " + e);
    }
}

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 w w  w .j  a v  a2s  .  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();
    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:io.vertx.config.vault.utils.Certificates.java

/**
 * See https://www.cryptoworkshop.com/guide/, chapter 3
 *
 * @return A 4096-bit RSA keypair//from  w ww  .ja  v  a2s.  c  om
 * @throws NoSuchAlgorithmException
 */
private static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
    final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", new BouncyCastleProvider());
    keyPairGenerator.initialize(4096);
    return keyPairGenerator.genKeyPair();
}

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 .j av  a2 s.  c  om*/
 * @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:org.kaaproject.kaa.common.endpoint.security.KeyUtil.java

/**
 * Generates a key pair.//from  w w  w .j  av a 2  s  .co m
 *
 * @return key pair
 * @throws NoSuchAlgorithmException no such algorithm
 */
public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
    KeyPairGenerator clientKeyGen = KeyPairGenerator.getInstance(RSA);
    clientKeyGen.initialize(2048);
    return clientKeyGen.genKeyPair();
}

From source file:br.edu.ufcg.lsd.commune.network.signature.Util.java

public static KeyPair generateKeyPair() {
    KeyPairGenerator keyGen;
    try {//from   www .j av  a  2  s.  co  m
        keyGen = KeyPairGenerator.getInstance(SignatureConstants.KEY_GEN_ALGORITHM);
    } catch (NoSuchAlgorithmException e) {
        //We're assuming that we are always using a valid algorithm
        throw new CommuneRuntimeException(e);
    }
    keyGen.initialize(SignatureConstants.KEYSIZE);
    return keyGen.genKeyPair();
}

From source file:im.whistle.crypt.Crypt.java

/**
 * Generates a private/public key pair.//from  w  w w .  j a v  a  2  s  .c  om
 * @param args Arguments, element at 0 is the key size
 * @param callback Callback
 */
public static void genkeys(JSONArray args, AsyncCallback<JSONArray> callback) {
    try {
        Log.i("whistle", "Generating key pair ...");
        PRNGProvider.init(); // Ensure OpenSSL fix
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        int bits = args.getInt(0);
        int exp = args.getInt(1);
        keyPairGenerator.initialize(new RSAKeyGenParameterSpec(bits, BigInteger.valueOf(exp)));
        KeyPair keyPair = keyPairGenerator.genKeyPair();
        String priv = "-----BEGIN RSA PRIVATE KEY-----\n"
                + Base64.encodeToString(keyPair.getPrivate().getEncoded(), Base64.DEFAULT).trim()
                + "\n-----END RSA PRIVATE KEY-----";
        String pub = "-----BEGIN PUBLIC KEY-----\n"
                + Base64.encodeToString(keyPair.getPublic().getEncoded(), Base64.DEFAULT).trim()
                + "\n-----END PUBLIC KEY-----";
        JSONArray res = new JSONArray();
        res.put(priv);
        res.put(pub);
        callback.success(res);
    } catch (Exception ex) {
        Log.w("whistle", "Key pair generation failed: " + ex.getMessage());
        callback.error(ex);
    }
}

From source file:info.magnolia.cms.security.SecurityUtil.java

public static MgnlKeyPair generateKeyPair(int keyLength) throws NoSuchAlgorithmException {
    KeyPairGenerator kgen = KeyPairGenerator.getInstance(ALGORITHM);
    kgen.initialize(keyLength);//from w w w.  ja  v a 2 s.c om
    KeyPair key = kgen.genKeyPair();
    return new MgnlKeyPair(byteArrayToHex(key.getPrivate().getEncoded()),
            byteArrayToHex(key.getPublic().getEncoded()));
}