Example usage for java.security KeyPairGenerator getInstance

List of usage examples for java.security KeyPairGenerator getInstance

Introduction

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

Prototype

public static KeyPairGenerator getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a KeyPairGenerator object that generates public/private key pairs for the specified algorithm.

Usage

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 w w.  j  a v  a 2  s . 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:oscar.oscarLab.ca.all.util.KeyPairGen.java

/**
 *  Create a key pair for the specified service and store it in the database
 *//*  w w w  .  jav a2 s. c  om*/
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:cn.util.RSAUtils.java

/**
 * ??//ww w .  ja  va 2 s. co  m
 * @throws NoSuchAlgorithmException 
 *
 */
public static HashMap<String, Object> getKeys() throws NoSuchAlgorithmException {
    HashMap<String, Object> map = new HashMap<String, Object>();
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
    keyPairGen.initialize(1024);
    KeyPair keyPair = keyPairGen.generateKeyPair();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    map.put("public", publicKey);
    map.put("private", privateKey);
    return map;
}

From source file:cloudeventbus.pki.CertificateUtils.java

public static KeyPair generateKeyPair() {
    try {//w w w . j a va 2s  .  c  o m
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(KEY_SIZE);
        return keyPairGenerator.generateKeyPair();
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:net.link.util.test.pkix.PkiTestUtils.java

public static KeyPair generateKeyPair(String algorithm)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {

    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
    SecureRandom random = new SecureRandom();
    if ("RSA".equals(keyPairGenerator.getAlgorithm()))
        keyPairGenerator.initialize(new RSAKeyGenParameterSpec(RSA_KEYSIZE, RSAKeyGenParameterSpec.F4), random);
    else if (keyPairGenerator instanceof DSAKeyPairGenerator) {
        DSAKeyPairGenerator dsaKeyPairGenerator = (DSAKeyPairGenerator) keyPairGenerator;
        dsaKeyPairGenerator.initialize(DSA_MODLEN, false, random);
    }//from   w  w  w .jav  a 2 s .  co  m
    return keyPairGenerator.generateKeyPair();
}

From source file:org.opentravel.schemacompiler.security.GenerateEncryptionKeys.java

/**
 * Generates the public and private key files used for encrypting and decrypting passwords.
 *///from   w  w  w  .j av  a2 s .  c om
public static void generateKeyFiles() throws Exception {
    File publicKeyFile = new File(System.getProperty("user.dir"),
            "/src/main/resources" + PasswordHelper.PUBLIC_KEYFILE);
    File privateKeyFile = new File(System.getProperty("user.dir"),
            "/src/main/resources" + PasswordHelper.PRIVATE_KEYFILE);
    KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(PasswordHelper.ENCRYPTION_ALGORITHM);

    keyGenerator.initialize(ENCRYPTION_KEY_SIZE);

    KeyPair keyPair = keyGenerator.generateKeyPair();
    KeyFactory fact = KeyFactory.getInstance(PasswordHelper.ENCRYPTION_ALGORITHM);
    RSAPublicKeySpec publicKeySpec = fact.getKeySpec(keyPair.getPublic(), RSAPublicKeySpec.class);
    RSAPrivateKeySpec privateKeySpec = fact.getKeySpec(keyPair.getPrivate(), RSAPrivateKeySpec.class);

    System.out
            .println("Public Key : " + publicKeySpec.getModulus() + " / " + publicKeySpec.getPublicExponent());
    System.out.println(
            "Private Key: " + privateKeySpec.getModulus() + " / " + privateKeySpec.getPrivateExponent());

    writeKeyFile(publicKeyFile, publicKeySpec.getModulus(), publicKeySpec.getPublicExponent());
    writeKeyFile(privateKeyFile, privateKeySpec.getModulus(), privateKeySpec.getPrivateExponent());
}

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

/**
 * Create a 1024 bit DSA KeyPair./*ww  w  .  j a v  a  2s .  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.springframework.security.oauth.common.signature.TestRSA_SHA1SignatureMethod.java

/**
 * tests signing and verifying./*from w w  w . j a v  a2 s. c o  m*/
 */
public void testSignAndVerify() throws Exception {
    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
    generator.initialize(1024);
    KeyPair keyPair = generator.generateKeyPair();
    String baseString = "thisismysignaturebasestringthatshouldbemuchlongerthanthisbutitdoesnthavetobeandherearesomestrangecharacters!@#$%^&*)(*";

    byte[] signatureBytes;
    {
        Signature signer = Signature.getInstance("SHA1withRSA");
        signer.initSign(keyPair.getPrivate());
        signer.update(baseString.getBytes("UTF-8"));
        signatureBytes = signer.sign();
    }

    {
        Signature signer = Signature.getInstance("SHA1withRSA");
        signer.initVerify(keyPair.getPublic());
        signer.update(baseString.getBytes("UTF-8"));
        assertTrue(signer.verify(signatureBytes));
    }

    RSA_SHA1SignatureMethod signatureMethod = new RSA_SHA1SignatureMethod(keyPair.getPrivate(),
            keyPair.getPublic());
    String signature = signatureMethod.sign(baseString);
    signatureMethod.verify(baseString, signature);
}

From source file:cherry.foundation.crypto.RSASignatureSupportTest.java

private RSASignatureSupport createCrypto() throws Exception {
    KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
    keygen.initialize(2048);//  ww w . j  a  v a2  s.co m
    KeyPair key = keygen.generateKeyPair();
    RSASignatureSupport crypto = new RSASignatureSupport();
    crypto.setAlgorithm("SHA256withRSA");
    crypto.setPublicKeyResource(new InMemoryResource(key.getPublic().getEncoded()));
    crypto.setPrivateKeyResource(new InMemoryResource(key.getPrivate().getEncoded()));
    crypto.afterPropertiesSet();
    return crypto;
}

From source file:cherry.foundation.crypto.RSACryptoSupportTest.java

private RSACryptoSupport createCrypto() throws Exception {
    KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
    keygen.initialize(2048);/*from  ww  w .  j  a  v a 2 s .  c  o m*/
    KeyPair key = keygen.generateKeyPair();
    RSACryptoSupport crypto = new RSACryptoSupport();
    crypto.setAlgorithm("RSA/ECB/PKCS1Padding");
    crypto.setPublicKeyResource(new InMemoryResource(key.getPublic().getEncoded()));
    crypto.setPrivateKeyResource(new InMemoryResource(key.getPrivate().getEncoded()));
    crypto.afterPropertiesSet();
    return crypto;
}