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:pepperim.util.IMCrypt.java

/**
 * Generates a new 2048 bit RSA keypair.
 * @return String array containing: [Base64-encoded public key, Base64-encoded private key]
 *///from  w  ww.j a  va  2  s .  co  m
public static String[] RSA_genKeypair() {
    try {
        KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA");
        SecureRandom random = new SecureRandom();
        pairgen.initialize(2048, random);
        KeyPair keyPair = pairgen.generateKeyPair();
        String[] keypair = new String[2];
        keypair[0] = B64_Enc(keyPair.getPublic().getEncoded());
        keypair[1] = B64_Enc(keyPair.getPrivate().getEncoded());
        return keypair;
    } catch (GeneralSecurityException e) {
        Main.log(e.getMessage());
        return null;
    }
}

From source file:com.intuit.s3encrypt.S3Encrypt.java

private static KeyPair createKeyFile(String filename)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {

    KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA");
    keyGenerator.initialize(2048, new SecureRandom());
    KeyPair myKeyPair = keyGenerator.generateKeyPair();

    PublicKey publicKey = myKeyPair.getPublic();
    PrivateKey privateKey = myKeyPair.getPrivate();

    System.out.println("keys created... " + filename);

    saveKeyPair(filename, myKeyPair);/*  w  w w .  ja  v a2  s.c  o  m*/
    return myKeyPair;
}

From source file:com.znsx.util.licence.LicenceUtil.java

/**
 * ??/*from ww  w .j  a v a  2s .c  om*/
 * 
 * @param seed
 *            ??
 * @return
 * @throws Exception
 */
public static Map<String, String> generateKey(String seed) throws Exception {
    Map<String, String> map = new HashMap<String, String>(2);
    KeyPairGenerator keygen = KeyPairGenerator.getInstance("DSA");
    SecureRandom random = new SecureRandom();
    random.setSeed(seed.getBytes("utf8"));
    keygen.initialize(1024, random);

    KeyPair keyPair = keygen.generateKeyPair();
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();

    Base64 base64 = new Base64();
    String publicKeyString = new String(base64.encode(publicKey.getEncoded()), "utf8");
    String privateKeyString = new String(base64.encode(privateKey.getEncoded()), "utf8");
    // BASE64Encoder encoder = new BASE64Encoder();
    // map.put("public", encoder.encode(publicKey.getEncoded()));
    // map.put("private", encoder.encode(privateKey.getEncoded()));
    map.put("public", publicKeyString);
    map.put("private", privateKeyString);

    System.out.println("publicKey: " + map.get("public"));
    System.out.println("privateKey: " + map.get("private"));
    return map;
}

From source file:com.security.ch08_rsa.RSACoderTextKey.java

/**
 * ?/*  w  w  w . ja  v  a 2 s  . com*/
 *
 * @return Map Map
 * @throws Exception
 */
public static Map<String, String> initKey(UUID licenseCode) throws Exception {
    // ?
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);

    // ??
    //        keyPairGen.initialize(KEY_SIZE);
    keyPairGen.initialize(KEY_SIZE, new SecureRandom(licenseCode.toString().getBytes(UTF_8)));

    // ?
    KeyPair keyPair = keyPairGen.generateKeyPair();

    // 
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

    // ?
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

    // ?
    Map<String, String> keyMap = new HashMap<String, String>();

    keyMap.put(PUBLIC_KEY, Base64.encodeBase64String(publicKey.getEncoded()));
    keyMap.put(PRIVATE_KEY, Base64.encodeBase64String(privateKey.getEncoded()));
    keyMap.put(LICENSE_CODE, licenseCode.toString());

    return keyMap;
}

From source file:com.znsx.util.licence.LicenceUtil.java

/**
 * ?DSA??p,q,g,j,x,y//from   w  w w .ja va 2s.  c o m
 * 
 * @param seed
 *            ??
 * @throws Exception
 * @author huangbuji
 *         <p />
 *         Create at 2014-2-8 ?4:45:26
 */
@SuppressWarnings("restriction")
public static void genKey(String seed) throws Exception {
    KeyPairGenerator keygen = KeyPairGenerator.getInstance("DSA");
    SecureRandom random = new SecureRandom();
    random.setSeed(seed.getBytes("utf8"));
    keygen.initialize(1024, random);

    KeyPair keyPair = keygen.generateKeyPair();
    DSAPublicKeyImpl publicKey = (DSAPublicKeyImpl) keyPair.getPublic();
    DSAPrivateKey privateKey = (DSAPrivateKey) keyPair.getPrivate();
    DSAParams dsaParams = privateKey.getParams();
    Base64 base64 = new Base64();
    String p = new String(base64.encode(dsaParams.getP().toByteArray()), "utf8");
    String q = new String(base64.encode(dsaParams.getQ().toByteArray()), "utf8");
    String g = new String(base64.encode(dsaParams.getG().toByteArray()), "utf8");
    String x = new String(base64.encode(privateKey.getX().toByteArray()), "utf8");
    String y = new String(base64.encode(publicKey.getY().toByteArray()), "utf8");
    System.out.println("P: " + p);
    System.out.println("Q: " + q);
    System.out.println("G: " + g);
    System.out.println("X: " + x);
    System.out.println("Y: " + y);

    String publicKeyString = new String(base64.encode(publicKey.getEncoded()), "utf8");
    String privateKeyString = new String(base64.encode(privateKey.getEncoded()), "utf8");
    System.err.println("public: " + publicKeyString);
    System.err.println("private: " + privateKeyString);

    File publicFile = new File("D:/binPublic.ky");
    File privateFile = new File("D:/binPrivate.ky");
    FileOutputStream out = new FileOutputStream(publicFile);
    out.write(publicKey.getEncoded());
    out.flush();
    out.close();
    out = new FileOutputStream(privateFile);
    out.write(privateKey.getEncoded());
    out.flush();
    out.close();
}

From source file:net.jmhertlein.mcanalytics.api.auth.SSLUtil.java

/**
 * Generates a new Elliptic Curve Digital Signature Algorithm (ECDSA) public/private key pair.
 *
 * System's default SecureRandom is used
 *
 * @param curveName the name of a pre-defined elliptic curve (e.g. secp521r1)
 * @param provider the JCE provider to use
 * @return a new ECDSA key pair/* w  w w . j ava2s  .  c  o  m*/
 */
public static KeyPair newECDSAKeyPair(String curveName, String provider) {
    KeyPair ret;
    try {
        ECGenParameterSpec ecGenSpec = new ECGenParameterSpec(curveName);
        KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", provider);
        g.initialize(ecGenSpec, new SecureRandom());
        ret = g.generateKeyPair();
    } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | NoSuchProviderException ex) {
        Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace(System.err);
        ret = null;
    }

    return ret;
}

From source file:net.firejack.platform.web.security.x509.KeyUtils.java

public static KeyPair generate(File keystore) {
    if (keystore == null) {
        throw new IllegalArgumentException("Key Store file should not be null.");
    }//  w w  w .jav a2 s .  c  om

    try {
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        if (keystore.exists()) {
            FileInputStream stream = new FileInputStream(keystore);
            ks.load(stream, SECRET);
            IOUtils.closeQuietly(stream);
        } else {
            ks.load(null, SECRET);
        }

        if (ks.containsAlias(ALIAS)) {
            PrivateKey privateKey = (PrivateKey) ks.getKey(ALIAS, SECRET);
            PublicKey publicKey = ks.getCertificate(ALIAS).getPublicKey();
            return new KeyPair(publicKey, privateKey);
        } else {
            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
            generator.initialize(KEYSIZE, new SecureRandom());
            return generator.generateKeyPair();
        }
    } catch (Throwable th) {
        logger.error("Failed to initialize key store");
        throw new OpenFlameRuntimeException(th.getMessage(), th);
    }
}

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  . j a v  a 2 s.c  o  m*/
    return keyPairGenerator.generateKeyPair();
}

From source file:com.aqnote.shared.cryptology.asymmetric.dsa.DSAKeyPairGenTest.java

public static void generator() throws NoSuchAlgorithmException, FileNotFoundException, IOException {
    KeyPairGenerator keygen = KeyPairGenerator.getInstance(ALGORITHM);

    // ???//from www  .j  a  v  a2 s  . c  o m
    SecureRandom secrand = new SecureRandom();
    secrand.setSeed(seed); // ??
    // ??, ??keysize ?. 512  1024  64 ?
    keygen.initialize(512, secrand);
    // ?pubkey?prikey
    KeyPair keys = keygen.generateKeyPair(); // ?
    PublicKey pubkey = keys.getPublic();
    PrivateKey prikey = keys.getPrivate();

    byte[] pubkeyByteArray = Base64.encodeBase64(pubkey.getEncoded());
    OutputStream os = new FileOutputStream(new File(PUBKEY_FILE_NAME));
    ByteArrayInputStream bais = new ByteArrayInputStream(pubkeyByteArray);
    StreamUtil.io(bais, os);
    bais.close();
    os.close();

    byte[] prikeyByteArray = Base64.encodeBase64(prikey.getEncoded());
    os = new FileOutputStream(new File(PRIKEY_FILE_NAME));
    bais = new ByteArrayInputStream(prikeyByteArray);
    StreamUtil.io(bais, os);
    bais.close();
    os.close();
}

From source file:net.jmhertlein.core.crypto.Keys.java

/**
 * Generates a new Elliptic Curve Digital Signature Algorithm (ECDSA) public/private key pair.
 *
 * System's default SecureRandom is used
 * @param curveName the name of a pre-defined elliptic curve (e.g. secp521r1)
 * @param provider the JCE provider to use
 * @return a new ECDSA key pair//from  w  ww . j  a va2  s .c o  m
 */
public static KeyPair newECDSAKeyPair(String curveName, String provider) {
    KeyPair ret;
    try {
        ECGenParameterSpec ecGenSpec = new ECGenParameterSpec(curveName);
        KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", provider);
        g.initialize(ecGenSpec, new SecureRandom());
        ret = g.generateKeyPair();
    } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | NoSuchProviderException ex) {
        Logger.getLogger(Keys.class.getName()).log(Level.SEVERE, null, ex);
        ret = null;
    }

    return ret;
}