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.opendaylight.aaa.cert.impl.ODLMdsalKeyTool.java

public KeyStore createKeyStoreWithSelfSignCert(final String keyStoreName, final String keyStorePwd,
        final String dName, final String keyAlias, final int validity, final String keyAlg, final int keySize,
        final String signAlg) {
    try {/*w ww  .  j  a  v  a 2  s. c om*/
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(keyAlg);
        keyPairGenerator.initialize(keySize);
        final KeyPair keyPair = keyPairGenerator.generateKeyPair();
        final X509V3CertificateGenerator x509V3CertGen = new X509V3CertificateGenerator();
        x509V3CertGen.setSerialNumber(getSecureRandomeInt());
        x509V3CertGen.setIssuerDN(new X509Principal(dName));
        x509V3CertGen.setNotBefore(new Date(System.currentTimeMillis()));
        x509V3CertGen
                .setNotAfter(new Date(System.currentTimeMillis() + (KeyStoreConstant.DAY_TIME * validity)));
        x509V3CertGen.setSubjectDN(new X509Principal(dName));
        x509V3CertGen.setPublicKey(keyPair.getPublic());
        x509V3CertGen.setSignatureAlgorithm(signAlg);
        final X509Certificate x509Cert = x509V3CertGen.generateX509Certificate(keyPair.getPrivate());
        final KeyStore ctlKeyStore = KeyStore.getInstance("JKS");
        ctlKeyStore.load(null, keyStorePwd.toCharArray());
        ctlKeyStore.setKeyEntry(keyAlias, keyPair.getPrivate(), keyStorePwd.toCharArray(),
                new java.security.cert.Certificate[] { x509Cert });
        LOG.info("{} is created", keyStoreName);
        return ctlKeyStore;
    } catch (final NoSuchAlgorithmException | InvalidKeyException | SecurityException | SignatureException
            | KeyStoreException | CertificateException | IOException e) {
        LOG.error("Fatal error creating keystore", e);
        return null;
    }
}

From source file:org.apache.sshd.common.util.SecurityUtils.java

public static synchronized KeyPairGenerator getKeyPairGenerator(String algorithm)
        throws NoSuchAlgorithmException, NoSuchProviderException {
    register();//from   w w  w.  j ava 2  s  .  co m
    if (getSecurityProvider() == null) {
        return KeyPairGenerator.getInstance(algorithm);
    } else {
        return KeyPairGenerator.getInstance(algorithm, getSecurityProvider());
    }
}

From source file:test.integ.be.fedict.trust.util.TestUtils.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(1024, RSAKeyGenParameterSpec.F4), random);
    } else if (keyPairGenerator instanceof DSAKeyPairGenerator) {
        DSAKeyPairGenerator dsaKeyPairGenerator = (DSAKeyPairGenerator) keyPairGenerator;
        dsaKeyPairGenerator.initialize(512, false, random);
    }/*from   w  ww. j a va2 s.c  om*/
    return keyPairGenerator.generateKeyPair();
}

From source file:org.opendaylight.aaa.cert.impl.ODLKeyTool.java

public boolean createKeyStoreWithSelfSignCert(final String keyStoreName, final String keyStorePwd,
        final String dName, final String keyAlias, final int validity) {
    try {/* www .  j  a  v a 2 s  . com*/
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator
                .getInstance(KeyStoreConstant.DEFAULT_KEY_ALG);
        keyPairGenerator.initialize(KeyStoreConstant.DEFAULT_KEY_SIZE);
        final KeyPair keyPair = keyPairGenerator.generateKeyPair();
        final X509V3CertificateGenerator x509V3CertGen = new X509V3CertificateGenerator();
        x509V3CertGen.setSerialNumber(getSecureRandomeInt());
        x509V3CertGen.setIssuerDN(new X509Principal(dName));
        x509V3CertGen.setNotBefore(new Date(System.currentTimeMillis()));
        x509V3CertGen
                .setNotAfter(new Date(System.currentTimeMillis() + (KeyStoreConstant.DAY_TIME * validity)));
        x509V3CertGen.setSubjectDN(new X509Principal(dName));
        x509V3CertGen.setPublicKey(keyPair.getPublic());
        x509V3CertGen.setSignatureAlgorithm(KeyStoreConstant.DEFAULT_SIGN_ALG);
        final X509Certificate x509Cert = x509V3CertGen.generateX509Certificate(keyPair.getPrivate());
        final KeyStore ctlKeyStore = KeyStore.getInstance("JKS");
        ctlKeyStore.load(null, keyStorePwd.toCharArray());
        ctlKeyStore.setKeyEntry(keyAlias, keyPair.getPrivate(), keyStorePwd.toCharArray(),
                new java.security.cert.Certificate[] { x509Cert });
        final FileOutputStream fOutputStream = new FileOutputStream(workingDir + keyStoreName);
        ctlKeyStore.store(fOutputStream, keyStorePwd.toCharArray());
        LOG.info("{} is created", keyStoreName);
        return true;
    } catch (NoSuchAlgorithmException | InvalidKeyException | SecurityException | SignatureException
            | KeyStoreException | CertificateException | IOException e) {
        LOG.error("Fatal error creating key", e);
        return false;
    }
}

From source file:org.apache.openaz.xacml.pdp.test.custom.TestCustom.java

/**
 * This function generates the public/private key pair. Should never have to call this again, this was
 * called once to generate the keys. They were saved into the testsets/custom/datatype-function
 * sub-directory.//w w w .  j  a  va  2 s .  com
 */
public void generateKeyPair() {
    //
    // Generate a RSA private/public key pair
    //
    KeyPairGenerator keyGen;
    try {
        keyGen = KeyPairGenerator.getInstance(ALGORITHM);
    } catch (NoSuchAlgorithmException e) {
        logger.error("failed to generate keypair: " + e);
        return;
    }
    keyGen.initialize(1024);
    final KeyPair key = keyGen.generateKeyPair();
    //
    // Save the keys to disk
    //
    Path file = Paths.get(this.directory, PRIVATEKEY_FILE);
    try (ObjectOutputStream os = new ObjectOutputStream(Files.newOutputStream(file))) {
        os.writeObject(key.getPrivate());
    } catch (IOException e) {
        e.printStackTrace();
    }
    file = Paths.get(this.directory, PUBLICKEY_FILE);
    try (ObjectOutputStream os = new ObjectOutputStream(Files.newOutputStream(file))) {
        os.writeObject(key.getPublic());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.sshtools.j2ssh.transport.kex.DhGroup1Sha1.java

/**
 *
 *
 * @throws IOException/*  w  ww.j ava 2 s.com*/
 * @throws AlgorithmNotSupportedException
 */
protected void onInit() throws IOException {

    try {
        dhKeyPairGen = KeyPairGenerator.getInstance("DH");
        dhKeyAgreement = KeyAgreement.getInstance("DH");
    } catch (NoSuchAlgorithmException ex) {
        throw new AlgorithmNotSupportedException(ex.getMessage());
    }
}

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

@Test
public void testPrivateKeyEncryption03() throws Throwable {
    PrivateKey privateKey = KeyPairGenerator.getInstance(KeyFileUtilities.keyAlgorithm).generateKeyPair()
            .getPrivate();/*www. jav  a  2s . c  o m*/

    byte[] privateKeyData = KeyFileUtilities.writeEncryptedPrivateKey(privateKey,
            "myTestPassword01".toCharArray());

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

    PrivateKey privateKey2 = KeyFileUtilities.readEncryptedPrivateKey(privateKeyData,
            "myTestPassword01".toCharArray());

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

From source file:org.cogroo.addon.util.SecurityUtil.java

public KeyPair genKeyPair() {
    KeyPair kpr = null;// w  w w  . j  a  v a  2s  .c  om
    try {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(new RSAKeyGenParameterSpec(RSAKEYSIZE, RSAKeyGenParameterSpec.F4));
        kpr = kpg.generateKeyPair();
    } catch (NoSuchAlgorithmException e) {
        LOG.log(Level.SEVERE, "Error generating key pair", e);
    } catch (InvalidAlgorithmParameterException e) {
        LOG.log(Level.SEVERE, "Error generating key pair", e);
    }
    return kpr;
}

From source file:org.apache.xml.security.test.signature.CreateSignatureTest.java

protected void setUp() throws Exception {
    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);/* www.  ja  v a  2 s  .  c o m*/
    db = dbf.newDocumentBuilder();
    org.apache.xml.security.Init.init();
    kp = KeyPairGenerator.getInstance("RSA").genKeyPair();
}

From source file:com.l2jfree.loginserver.manager.LoginManager.java

/**
 * Private constructor to avoid direct instantiation.
 * Initialize a key generator./*www . j  av a  2s  . c o  m*/
 */
private LoginManager() {
    try {
        _log.info("LoginManager: initializing.");

        _hackProtection = new FastMap<InetAddress, FailedLoginAttempt>();

        _keyPairs = new ScrambledKeyPair[10];

        _service = (AccountsServices) L2Registry.getBean("AccountsServices");

        _connections = new FastList<L2Client>();

        KeyPairGenerator keygen = null;

        try {
            keygen = KeyPairGenerator.getInstance("RSA");
            RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4);
            keygen.initialize(spec);
        } catch (GeneralSecurityException e) {
            _log.fatal("Error in RSA setup:", e);
            _log.info("Server shutting down now");
            System.exit(1);
            return;
        }

        //generate the initial set of keys
        for (int i = 0; i < 10; i++) {
            _keyPairs[i] = new ScrambledKeyPair(keygen.generateKeyPair());
        }
        _log.info("LoginManager: Cached 10 KeyPairs for RSA communication");

        testCipher((RSAPrivateKey) _keyPairs[0].getPair().getPrivate());

        // Store keys for blowfish communication
        generateBlowFishKeys();
    } catch (GeneralSecurityException e) {
        _log.fatal("FATAL: Failed initializing LoginManager. Reason: " + e.getMessage(), e);
        System.exit(1);
    }

}