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:com.ibm.mobilefirstplatform.clientsdk.android.security.mca.internal.security.DefaultJSONSignerTests.java

public KeyPair generateRandomKeyPair() {
    KeyPair keyPair = null;// ww w.  j  a v a  2s .co m

    try {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(512);
        keyPair = kpg.genKeyPair();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    return keyPair;
}

From source file:org.lightjason.agentspeak.action.buildin.crypto.EAlgorithm.java

/**
 * generates a key/*from  www.  j  av  a  2s  .  co  m*/
 *
 * @return key pair object (public key / private key or null)
 *
 * @throws NoSuchAlgorithmException on algorithm error
 */
public final Pair<Key, Key> generateKey() throws NoSuchAlgorithmException {
    switch (this) {
    case AES:
    case DES:
        return new ImmutablePair<>(KeyGenerator.getInstance(m_key).generateKey(), null);

    case RSA:
        final KeyPair l_key = KeyPairGenerator.getInstance(m_key).generateKeyPair();
        return new ImmutablePair<>(l_key.getPublic(), l_key.getPrivate());

    default:
        throw new CIllegalStateException(CCommon.languagestring(this, "unknown", this));
    }
}

From source file:org.kde.kdeconnect.NetworkPackageTest.java

public void testEncryption() throws JSONException {
    NetworkPackage original = new NetworkPackage("com.test");
    original.set("hello", "hola");

    NetworkPackage copy = NetworkPackage.unserialize(original.serialize());

    NetworkPackage decrypted = new NetworkPackage("");

    KeyPair keyPair;//from   w  ww.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;
    }

    PrivateKey privateKey = keyPair.getPrivate();
    assertNotNull(privateKey);

    PublicKey publicKey = keyPair.getPublic();
    assertNotNull(publicKey);

    // Encrypt and decrypt np
    assertEquals(original.getType(), "com.test");
    try {
        NetworkPackage encrypted = RsaHelper.encrypt(original, publicKey);
        assertEquals(encrypted.getType(), NetworkPackage.PACKAGE_TYPE_ENCRYPTED);

        decrypted = RsaHelper.decrypt(encrypted, privateKey);
        assertEquals(decrypted.getType(), "com.test");

    } catch (Exception e) {
        e.printStackTrace();
    }

    // np should be equal to np2
    assertEquals(decrypted.getLong("id"), copy.getLong("id"));
    assertEquals(decrypted.getType(), copy.getType());
    assertEquals(decrypted.getJSONArray("body"), copy.getJSONArray("body"));

    String json = "{\"body\":{\"nowPlaying\":\"A really long song name - A really long artist name\",\"player\":\"A really long player name\",\"the_meaning_of_life_the_universe_and_everything\":\"42\"},\"id\":945945945,\"type\":\"kdeconnect.a_really_really_long_package_type\"}\n";
    NetworkPackage longJsonNp = NetworkPackage.unserialize(json);
    try {
        NetworkPackage encrypted = RsaHelper.encrypt(longJsonNp, publicKey);
        decrypted = RsaHelper.decrypt(encrypted, privateKey);
        String decryptedJson = decrypted.serialize();
        JSONAssert.assertEquals(json, decryptedJson, true);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.lightjason.agentspeak.action.builtin.crypto.EAlgorithm.java

/**
 * generates a key//from   w  w w . j  a v a2  s .c  o  m
 *
 * @return key pair object (public key / private key or null)
 *
 * @throws NoSuchAlgorithmException on algorithm error
 */
@Nonnull
public final Pair<Key, Key> generateKey() throws NoSuchAlgorithmException {
    switch (this) {
    case AES:
    case DES:
        return new ImmutablePair<>(KeyGenerator.getInstance(m_key).generateKey(), null);

    case RSA:
        final KeyPair l_key = KeyPairGenerator.getInstance(m_key).generateKeyPair();
        return new ImmutablePair<>(l_key.getPublic(), l_key.getPrivate());

    default:
        throw new CIllegalStateException(CCommon.languagestring(this, "unknown", this));
    }
}

From source file:de.dennishoersch.web.chat.Encryption.java

public KeyPair generateRSAKeyPair() {
    try {// w  w w  .  jav a  2s .c o m
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(1024);
        return keyGen.genKeyPair();

    } catch (NoSuchAlgorithmException e) {
        throw Throwables.throwUnchecked(e);
    }
}

From source file:be.e_contract.mycarenet.common.SessionKey.java

/**
 * Generator constructor. Creates a new MyCareNet session key.
 * //w w w.  j a  v a  2  s . c  o m
 * @param keySize
 *            the RSA key size.
 */
public SessionKey(int keySize) {
    KeyPairGenerator keyPairGenerator;
    try {
        keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("RSA algo not available", e);
    }
    SecureRandom random = new SecureRandom();
    try {
        keyPairGenerator.initialize(new RSAKeyGenParameterSpec(keySize, RSAKeyGenParameterSpec.F4), random);
    } catch (InvalidAlgorithmParameterException e) {
        throw new RuntimeException("unsupported key size: " + keySize);
    }
    this.keyPair = keyPairGenerator.generateKeyPair();
}

From source file:wsattacker.library.signatureFaking.helper.CertificateHandler.java

public void createFakedCertificate() throws CertificateHandlerException {
    try {/*from w w  w  .j  a v  a2  s  . co m*/
        log.debug("Faking the found certificate");
        // TODO: implement this with bouncy castle
        KeyPairGenerator kpg = KeyPairGenerator.getInstance(originalPublicKey.getAlgorithm());
        kpg.initialize(((RSAPublicKey) certificate.getPublicKey()).getModulus().bitLength());
        fakedKeyPair = kpg.generateKeyPair();

        X509CertInfo info = new X509CertInfo();
        CertificateValidity interval = new CertificateValidity(certificate.getNotBefore(),
                certificate.getNotAfter());
        // TODO: new SecureRandom().generateSeed(64) is very slow! Replace
        // it?
        // BigInteger sn = new BigInteger(new
        // SecureRandom().generateSeed(64));
        BigInteger sn = new BigInteger(64, new Random());
        X500Name owner = new X500Name(certificate.getSubjectDN().getName());
        X500Name issuer = new X500Name(certificate.getIssuerDN().getName());

        info.set(X509CertInfo.VALIDITY, interval);
        info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
        info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));
        info.set(X509CertInfo.ISSUER, new CertificateIssuerName(issuer));
        info.set(X509CertInfo.KEY, new CertificateX509Key(fakedKeyPair.getPublic()));

        info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));

        AlgorithmId algo = new AlgorithmId(new ObjectIdentifier(certificate.getSigAlgOID()));
        info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo));

        // Sign the cert to identify the algorithm that's used.
        fakedCertificate = new X509CertImpl(info);
        fakedCertificate.sign(fakedKeyPair.getPrivate(), certificate.getSigAlgName());
    } catch (CertificateException e) {
        throw new CertificateHandlerException(e);
    } catch (IOException e) {
        throw new CertificateHandlerException(e);
    } catch (InvalidKeyException e) {
        throw new CertificateHandlerException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateHandlerException(e);
    } catch (NoSuchProviderException e) {
        throw new CertificateHandlerException(e);
    } catch (SignatureException e) {
        throw new CertificateHandlerException(e);
    }
}

From source file:org.mitre.jwt.signer.service.impl.KeyStoreTest.java

/**
 * Create an RSA KeyPair and insert into specified KeyStore
 * //from   w w w .  j a  v  a 2  s. com
 * @param location
 * @param domainName
 * @param alias
 * @param keystorePassword
 * @param aliasPassword
 * @param daysNotValidBefore
 * @param daysNotValidAfter
 * @return
 * @throws GeneralSecurityException
 * @throws IOException
 */
public static java.security.KeyStore generateKeyPair(KeyStore keystore, String keyPairAlgorithm, int keySize,
        String signatureAlgorithm, String domainName, String alias, String aliasPassword,
        int daysNotValidBefore, int daysNotValidAfter) throws GeneralSecurityException, IOException {

    java.security.KeyStore ks;

    if (keystore != null) {
        ks = keystore.getKeystore();
    } else {
        ks = java.security.KeyStore.getInstance(java.security.KeyStore.getDefaultType());
        ks.load(null, null);
    }

    KeyPairGenerator rsaKeyPairGenerator = null;

    rsaKeyPairGenerator = KeyPairGenerator.getInstance(keyPairAlgorithm);

    rsaKeyPairGenerator.initialize(keySize);
    KeyPair rsaKeyPair = rsaKeyPairGenerator.generateKeyPair();

    // BC sez X509V3CertificateGenerator is deprecated and the docs say to
    // use another, but it seemingly isn't included jar...
    X509V3CertificateGenerator v3CertGen = createCertificate(domainName, daysNotValidBefore, daysNotValidAfter);

    PrivateKey privateKey = rsaKeyPair.getPrivate();

    v3CertGen.setPublicKey(rsaKeyPair.getPublic());
    v3CertGen.setSignatureAlgorithm(signatureAlgorithm);

    // BC docs say to use another, but it seemingly isn't included...
    X509Certificate certificate = v3CertGen.generateX509Certificate(privateKey);

    // if exist, overwrite
    ks.setKeyEntry(alias, privateKey, aliasPassword.toCharArray(),
            new java.security.cert.Certificate[] { certificate });

    if (keystore != null) {
        keystore.setKeystore(ks);
    }

    return ks;
}

From source file:net.solarnetwork.node.setup.test.DefaultSetupServiceTest.java

@BeforeClass
public static void setupClass() throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(2048, new SecureRandom());
    CA_KEY_PAIR = keyGen.generateKeyPair();
    CA_CERT = PKITestUtils.generateNewCACert(CA_KEY_PAIR.getPublic(), TEST_CA_DN, null,
            CA_KEY_PAIR.getPrivate(), TEST_CA_DN);
}

From source file:org.dasein.cloud.test.identity.IdentityResources.java

/**
 * @link http://stackoverflow.com/a/14582408/211197
 * @return Encoded generated public key//from   w  w  w . j a  va  2s . c  o  m
 */
private @Nullable String generateKey() {
    KeyPairGenerator generator;
    try {
        generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(2048);
        KeyPair keyPair = generator.genKeyPair();
        RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
        ByteArrayOutputStream byteOs = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(byteOs);
        dos.writeInt("ssh-rsa".getBytes().length);
        dos.write("ssh-rsa".getBytes());
        dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length);
        dos.write(rsaPublicKey.getPublicExponent().toByteArray());
        dos.writeInt(rsaPublicKey.getModulus().toByteArray().length);
        dos.write(rsaPublicKey.getModulus().toByteArray());
        String publicKeyEncoded = new String(Base64.encodeBase64(byteOs.toByteArray()));
        return "ssh-rsa " + publicKeyEncoded + " dasein";
    } catch (Throwable e) {
        return null;
    }
}