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.red5.server.net.rtmp.RTMPHandshake.java

/**
 * Creates a Diffie-Hellman key pair.//from w  ww  . j  a v a2  s.c  o m
 * 
 * @return dh keypair
 */
protected KeyPair generateKeyPair() {
    KeyPair keyPair = null;
    DHParameterSpec keySpec = new DHParameterSpec(DH_MODULUS, DH_BASE);
    try {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH");
        keyGen.initialize(keySpec);
        keyPair = keyGen.generateKeyPair();
        keyAgreement = KeyAgreement.getInstance("DH");
        keyAgreement.init(keyPair.getPrivate());
    } catch (Exception e) {
        log.error("Error generating keypair", e);
    }
    return keyPair;
}

From source file:net.sourceforge.msscodefactory.cflib.v2_1.CFLib.Tip.CFTipEnvelopeHandler.java

public void initServerKeys() throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException,
        IllegalBlockSizeException {
    if (serverKeyPair == null) {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(2048, new SecureRandom());
        serverKeyPair = kpg.generateKeyPair();
    }//from w  ww.j ava2  s  .c  o m

    byte encodedPKey[] = getEncodedServerPublicKey();
    String encoded = new String(Base64.encodeBase64(encodedPKey));
    serverInfo.setServerLoginKey(encoded);
}

From source file:net.nicholaswilliams.java.licensing.encryption.TestKeyFileUtilities.java

@Test
public void testPublicKeyEncryption04() throws Throwable {
    PublicKey publicKey = KeyPairGenerator.getInstance(KeyFileUtilities.keyAlgorithm).generateKeyPair()
            .getPublic();/*from  w w w .j  a v a2  s  .c o  m*/

    PublicKey otherKey = KeyPairGenerator.getInstance(KeyFileUtilities.keyAlgorithm).generateKeyPair()
            .getPublic();

    assertFalse("The keys should not be equal (1).", otherKey.equals(publicKey));

    byte[] publicKeyData = KeyFileUtilities.writeEncryptedPublicKey(publicKey,
            "yourTestPassword02".toCharArray());

    assertNotNull("The key data should not be null.", publicKeyData);
    assertTrue("The key data should have length.", publicKeyData.length > 0);

    PublicKey publicKey2 = KeyFileUtilities.readEncryptedPublicKey(publicKeyData,
            "yourTestPassword02".toCharArray());

    assertNotNull("The key should not be null.", publicKey2);
    assertFalse("The objects should not be the same.", publicKey == publicKey2);
    assertEquals("The keys should be the same.", publicKey, publicKey2);

    assertFalse("The keys should not be equal (2).", otherKey.equals(publicKey2));
}

From source file:fi.okm.mpass.idp.authn.impl.ValidateOIDCIDTokenSignatureTest.java

protected static KeyPair generateKeyPair(final int keysize) throws NoSuchAlgorithmException {
    final KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA");
    keyGenerator.initialize(keysize);//from  w  w w  . j av a2  s. c  o m
    return keyGenerator.generateKeyPair();
}

From source file:org.guanxi.sp.engine.form.RegisterGuardFormController.java

/**
 * Creates an authenticated certificate chain for the specified X509 name
 *
 * @param x509DN X509 name to for which to create a certificate chain
 * @param keyType The type of the key, e.g. "RSA", "DSA"
 * @return Returns a CABean instance encapsulating certificate chain and key information
 * or null if an error occurred/*from   w w w. ja v a 2s  .  co  m*/
 */
private CABean createSignedCertificateChain(String x509DN, String keyType) {
    try {
        // Create a public/private keypair...
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance(keyType);
        keyGen.initialize(1024, new SecureRandom());
        KeyPair keypair = keyGen.generateKeyPair();
        PrivateKey clientPrivateKey = keypair.getPrivate();
        PublicKey clientPublicKey = keypair.getPublic();

        // ...and a CSR from them...
        PKCS10CertificationRequest csr = generateRequest(x509DN, clientPublicKey, clientPrivateKey, keyType);

        // ...sign it
        KeyStore rootKS = loadRootKeyStore();
        X509Certificate rootCert = (X509Certificate) rootKS.getCertificate(rootCAKeystoreAlias);
        if (rootCert == null) {
            logger.error("Can't get root certificate from CA keystore");
            return null;
        }
        PrivateKey rootPrivKey = (PrivateKey) rootKS.getKey(rootCAKeystoreAlias,
                rootCAKeystorePassword.toCharArray());
        X509Certificate[] signedChain = createSignedCert(rootCert, rootPrivKey, csr, keyType);

        //...package up the result...
        CABean caBean = new CABean();
        caBean.setChain(signedChain);
        caBean.setCSRPrivateKey(clientPrivateKey);
        caBean.setSubjectDN(x509DN);

        // ...and send it back
        return caBean;
    } catch (Exception e) {
        logger.error(e);
        return null;
    }
}

From source file:net.link.util.common.KeyUtils.java

public static KeyPair generateKeyPair(String algorithm) throws NoSuchAlgorithmException {

    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
    SecureRandom random = new SecureRandom();
    if ("RSA".equals(keyPairGenerator.getAlgorithm()))
        try {//from   ww  w.  j a  va 2  s  .com
            keyPairGenerator.initialize(new RSAKeyGenParameterSpec(RSA_KEYSIZE, RSAKeyGenParameterSpec.F4),
                    random);
        } catch (InvalidAlgorithmParameterException e) {
            throw new InternalInconsistencyException("KeyGenParams incompatible with key generator.", e);
        }
    else if (keyPairGenerator instanceof DSAKeyPairGenerator) {
        DSAKeyPairGenerator dsaKeyPairGenerator = (DSAKeyPairGenerator) keyPairGenerator;
        dsaKeyPairGenerator.initialize(DSA_MODLEN, false, random);
    }

    return keyPairGenerator.generateKeyPair();
}

From source file:com.wandrell.util.ksgen.BouncyCastleKeyStoreFactory.java

/**
 * Creates a key pair.//from  w  ww  .  jav a  2 s .  c o  m
 *
 * @return the key pair
 * @throws NoSuchAlgorithmException
 *             if the required algorithm for the key pair does not exist
 */
private final KeyPair getKeyPair() throws NoSuchAlgorithmException {
    final KeyPairGenerator keyPairGenerator; // Key pair generator
    final KeyPair keypair; // Key pair

    keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024, new SecureRandom());

    keypair = keyPairGenerator.generateKeyPair();

    LOGGER.debug("Created key pair with private key {} {} and public key {} {}",
            keypair.getPrivate().getAlgorithm(), Arrays.asList(keypair.getPrivate().getEncoded()),
            keypair.getPublic().getAlgorithm(), Arrays.asList(keypair.getPublic().getEncoded()));

    return keypair;
}

From source file:com.streamsets.datacollector.publicrestapi.TestCredentialsDeploymentResource.java

private KeyPair generateKeys() throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    keyGen.initialize(512, random);/*  w  w  w  .ja  va  2 s .c o m*/
    return keyGen.generateKeyPair();
}

From source file:net.solarnetwork.node.setup.impl.DefaultKeystoreService.java

private X509Certificate createSelfSignedCertificate(KeyStore keyStore, String dn, String alias) {
    try {// w w  w . j a  v a 2  s .  com
        // create new key pair for the node
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(keySize, new SecureRandom());
        KeyPair keypair = keyGen.generateKeyPair();
        PublicKey publicKey = keypair.getPublic();
        PrivateKey privateKey = keypair.getPrivate();

        Certificate cert = certificateService.generateCertificate(dn, publicKey, privateKey);
        keyStore.setKeyEntry(alias, privateKey, getKeyStorePassword().toCharArray(),
                new Certificate[] { cert });
        saveKeyStore(keyStore);
        return (X509Certificate) cert;
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateException("Error setting up node key pair", e);
    } catch (KeyStoreException e) {
        throw new CertificateException("Error setting up node key pair", e);
    }
}

From source file:org.teknux.jettybootstrap.keystore.JettyKeystore.java

private static KeyPair generateKeyPair(String algorithm) throws JettyKeystoreException {
    try {/*from   w ww.j  a v  a  2 s . c om*/
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
        return keyPairGenerator.generateKeyPair();
    } catch (NoSuchAlgorithmException e) {
        throw new JettyKeystoreException(JettyKeystoreException.ERROR_CREATE_KEYS,
                "Can not generate private and public keys", e);
    }
}