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) throws InvalidAlgorithmParameterException 

Source Link

Document

Initializes the key pair generator using the specified parameter set and the SecureRandom implementation of the highest-priority installed provider as the source of randomness.

Usage

From source file:oscar.oscarLab.ca.all.util.KeyPairGen.java

/**
 *  Create a key pair for the specified service and store it in the database
 *//*from   w  w  w .  j a  v  a2  s .  c  o  m*/
public static String createKeys(String name, String type) {
    byte[] pubKey;
    byte[] privKey;
    Base64 base64 = new Base64();

    // Generate an RSA key
    try {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(1024);
        KeyPair key = keyGen.generateKeyPair();

        pubKey = base64.encode(key.getPublic().getEncoded());
        privKey = base64.encode(key.getPrivate().getEncoded());

        if (name.equals("oscar")) {
            // the primary key is name, therefore this statement will only
            // be able to run once and the oscar key pair will not be overwritten

            OscarKeyDao oscarKeyDao = (OscarKeyDao) SpringUtils.getBean("oscarKeyDao");
            OscarKey oscarKey = new OscarKey();
            oscarKey.setName("oscar");
            oscarKey.setPublicKey(new String(pubKey, MiscUtils.ENCODING));
            oscarKey.setPrivateKey(new String(privKey, MiscUtils.ENCODING));

            oscarKeyDao.persist(oscarKey);

            // no keys need to be returned so return "success" instead to 
            // indicate the operation completed successfully
            return ("success");
        } else {

            PublicKeyDao publicKeyDao = (PublicKeyDao) SpringUtils.getBean("publicKeyDao");
            PublicKey publicKeyObject = new PublicKey();
            publicKeyObject.setService(name);
            publicKeyObject.setType(type);
            publicKeyObject.setBase64EncodedPublicKey(new String(pubKey, MiscUtils.ENCODING));
            publicKeyObject.setBase64EncodedPrivateKey(new String(privKey, MiscUtils.ENCODING));

            publicKeyDao.persist(publicKeyObject);

            return (publicKeyObject.getBase64EncodedPrivateKey());
        }

    } catch (NoSuchAlgorithmException e) {
        logger.error("Could not create RSA key", e);
        return null;
    } catch (Exception e) {
        logger.error("Could not save keys", e);
        return null;
    }

}

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.  jav a  2  s.  co  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:net.padlocksoftware.padlock.KeyManager.java

/**
 * Create a 1024 bit DSA KeyPair.//from   w  w  w. 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.ebayopensource.fido.uaf.crypto.KeyCodec.java

public static KeyPair getRSAKeyPair()
        throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException {
    KeyPairGenerator g = KeyPairGenerator.getInstance("RSA", "SC");
    g.initialize(2048);
    return g.generateKeyPair();
}

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

public static KeyPair generateKeyPair() {
    try {//from   www .  j  a va2s .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.wisdom.framework.vertx.ssl.FakeKeyStore.java

private static void generateAndStoreKeyStore(KeyStore keyStore, File keyStoreFile) throws Exception {
    FileOutputStream out = null;/*from   w w w.  j  a v a 2 s  .c  o  m*/
    try {
        LOGGER.info("Generating HTTPS key pair in " + keyStoreFile.getAbsolutePath() + " - this may take some"
                + " time. If nothing happens, try moving the mouse/typing on the keyboard to generate some entropy.");

        // Generate the key pair
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        // Generate a self signed certificate
        X509Certificate cert = createSelfSignedCertificate(keyPair);

        // Create the key store, first set the store pass
        keyStore.load(null, "".toCharArray());
        keyStore.setKeyEntry("wisdom-generated", keyPair.getPrivate(), "".toCharArray(),
                new X509Certificate[] { cert });

        keyStoreFile.getParentFile().mkdirs();
        out = new FileOutputStream(keyStoreFile);
        keyStore.store(out, "".toCharArray());

        LOGGER.info("Key Store generated in " + keyStoreFile.getAbsoluteFile());
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:org.wisdom.engine.ssl.FakeKeyStore.java

private static void generateAndStoreKeyStore(KeyStore keyStore, File keyStoreFile) throws Exception {
    FileOutputStream out = null;/*from w w w .  j  a va 2s .c  o m*/
    try {
        LOGGER.info("Generating HTTPS key pair in " + keyStoreFile.getAbsolutePath() + " - this may take some"
                + " time. If nothing happens, try moving the mouse/typing on the keyboard to generate some entropy.");

        // Generate the key pair
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        // Generate a self signed certificate
        X509Certificate cert = createSelfSignedCertificate(keyPair);

        // Create the key store, first set the store pass
        keyStore.load(null, "".toCharArray());
        keyStore.setKeyEntry("wisdom-generated", keyPair.getPrivate(), "".toCharArray(),
                new X509Certificate[] { cert });

        out = new FileOutputStream(keyStoreFile);
        keyStore.store(out, "".toCharArray());

        LOGGER.info("Key Store generated in " + keyStoreFile.getAbsoluteFile());
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:hh.learnj.test.license.test.rsacoder.RSACoder.java

/**
 * ?/*w w w  .  j a v a2 s .c  om*/
 * 
 * @return Map Map
 */
public static Map<String, Object> initKey() throws Exception {
    // ?
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
    // ??
    keyPairGenerator.initialize(KEY_SIZE);
    // ?
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    // 
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    // ?
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    // map
    Map<String, Object> keyMap = new HashMap<String, Object>();
    keyMap.put(PUBLIC_KEY, publicKey);
    keyMap.put(PRIVATE_KEY, privateKey);
    return keyMap;

}

From source file:org.apache.nifi.toolkit.tls.util.TlsHelper.java

private static KeyPairGenerator createKeyPairGenerator(String algorithm, int keySize)
        throws NoSuchAlgorithmException {
    KeyPairGenerator instance = KeyPairGenerator.getInstance(algorithm);
    instance.initialize(keySize);
    return instance;
}

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

public static KeyPair getRSAKeyPair()
        throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException {
    KeyPairGenerator g = KeyPairGenerator.getInstance("RSA", "BC");
    g.initialize(2048);
    return g.generateKeyPair();
}