Example usage for java.security KeyPairGenerator generateKeyPair

List of usage examples for java.security KeyPairGenerator generateKeyPair

Introduction

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

Prototype

public KeyPair generateKeyPair() 

Source Link

Document

Generates a key pair.

Usage

From source file:com.vmware.admiral.auth.lightwave.pc.X509CertificateHelper.java

public X509Certificate generateX509Certificate(String keyPairAlg, String sigAlg)
        throws NoSuchAlgorithmException, CertificateException, OperatorCreationException {

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(keyPairAlg);
    keyGen.initialize(1024, new SecureRandom());

    KeyPair clientKeyPair = keyGen.generateKeyPair();

    String solutionUser = "oidc.client" + UUID.randomUUID().toString();

    return generateCertificate(clientKeyPair, solutionUser, sigAlg);
}

From source file:cherry.goods.crypto.VersionedSignatureTest.java

private RSASignature createRSASignature() throws Exception {
    KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
    keygen.initialize(2048);//from  ww w .  j a v a 2  s  . co  m
    KeyPair key = keygen.generateKeyPair();
    RSASignature impl = new RSASignature();
    impl.setAlgorithm("SHA256withRSA");
    impl.setPublicKeyBytes(key.getPublic().getEncoded());
    impl.setPrivateKeyBytes(key.getPrivate().getEncoded());
    return impl;
}

From source file:org.candlepin.CRLWriteBenchmark.java

@Setup(Level.Trial)
public void createKey() throws Exception {
    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");

    generator.initialize(2048);/*  w  w  w .  ja v a  2s  . c  om*/
    keyPair = generator.generateKeyPair();
}

From source file:info.fcrp.keepitsafe.bean.CryptBeanTest.java

@Test
public void assymetric() throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(1024, new SecureRandom());
    KeyPair kp = kpg.generateKeyPair();
    PrivateKey priKey = kp.getPrivate();
    PublicKey pubKey = kp.getPublic();

    Cipher c = Cipher.getInstance("RSA");
    String plain = "plain";
    byte[] plainBytes = plain.getBytes();

    c.init(Cipher.ENCRYPT_MODE, pubKey);
    c.update(plainBytes);/*from w w  w.  j  a  v  a 2 s .  co  m*/

    byte[] encBytes = c.doFinal();
    String enc = Base64.encodeBase64String(encBytes);
    assertNotSame(plain, enc);

    c.init(Cipher.DECRYPT_MODE, priKey);
    c.update(encBytes);
    byte[] decBytes = c.doFinal();
    String dec = new String(decBytes);

    assertEquals(plain, dec);
}

From source file:org.wso2.carbon.certificate.mgt.core.util.CSRGenerator.java

/**
 * Generate the desired keypair/* w  w  w . j  a v a2s. c  o  m*/
 *
 * @param alg
 * @param keySize
 * @return
 */
public KeyPair generateKeyPair(String alg, int keySize) {
    try {
        KeyPairGenerator keyPairGenerator = null;
        keyPairGenerator = KeyPairGenerator.getInstance(alg);
        keyPairGenerator.initialize(keySize);
        return keyPairGenerator.generateKeyPair();
    } catch (NoSuchAlgorithmException e) {
        log.error("The provided algorithm is not found ", e);
    }
    return null;
}

From source file:net.solarnetwork.pki.bc.test.BCCertificateServiceTest.java

@Test
public void signCertificate() throws Exception {
    X509Certificate cert = service.generateCertificate(TEST_DN, publicKey, privateKey);
    String csr = service.generatePKCS10CertificateRequestString(cert, privateKey);

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(2048, new SecureRandom());
    KeyPair caKeypair = keyGen.generateKeyPair();
    X509Certificate caCert = service.generateCertificationAuthorityCertificate(TEST_CA_DN,
            caKeypair.getPublic(), caKeypair.getPrivate());

    X509Certificate signed = service.signCertificate(csr, caCert, caKeypair.getPrivate());
    assertEquals("Issuer", caCert.getSubjectX500Principal(), signed.getIssuerX500Principal());
    assertEquals("Subject", cert.getSubjectX500Principal(), signed.getSubjectX500Principal());
}

From source file:edu.vt.middleware.crypt.signature.SignatureAlgorithmTest.java

/**
 * @return  Test data.//from  w  w w  .  jav  a2s. c  o  m
 *
 * @throws  Exception  On test data generation failure.
 */
@DataProvider(name = "testdata")
public Object[][] createTestData() throws Exception {
    final KeyPairGenerator rsaKeyGen = KeyPairGenerator.getInstance("RSA");
    final KeyPair rsaKeys = rsaKeyGen.generateKeyPair();

    final KeyPairGenerator dsaKeyGen = KeyPairGenerator.getInstance("DSA");
    final KeyPair dsaKeys = dsaKeyGen.generateKeyPair();

    return new Object[][] { { new DSASignature(), dsaKeys, null, },
            { new DSASignature(), dsaKeys, new Base64Converter(), },
            { new DSASignature(new SHA512()), dsaKeys, new HexConverter(), },
            { new DSASignature(new Tiger()), dsaKeys, new HexConverter(), },
            { new RSASignature(), rsaKeys, null, }, { new RSASignature(), rsaKeys, new Base64Converter(), },
            { new RSASignature(new MD5()), rsaKeys, new HexConverter(), },
            { new RSASignature(new Whirlpool()), rsaKeys, new HexConverter(), }, };
}

From source file:com.bluepixel.security.manager.Server.java

private void generateKey() {
    try {/*from   w w  w.  j  a v  a2  s  . c  o  m*/
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance(DEFAULT_ALGORITHM);
        keyGen.initialize(DEFAULT_KEY_LENGTH);
        KeyPair keypair = keyGen.generateKeyPair();
        PublicKey pbKey = keypair.getPublic();
        PrivateKey piKey = keypair.getPrivate();

        publicKey = Base64.encodeWebSafe(pbKey.getEncoded(), false);
        privateKey = Base64.encodeWebSafe(piKey.getEncoded(), false);

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

        cipher.init(Cipher.ENCRYPT_MODE, piKey);

        secretKeys = new ConcurrentHashMap<String, String>();
        String[] randomKeys = generateRandomWords(10);
        for (String key : randomKeys) {
            String cipherText = Base64.encodeWebSafe(cipher.doFinal(key.getBytes()), false);
            secretKeys.put(key, cipherText);
        }
    } catch (NoSuchAlgorithmException e) {
    } catch (InvalidKeyException e) {
    } catch (NoSuchPaddingException e) {
    } catch (IllegalBlockSizeException e) {
    } catch (BadPaddingException e) {
    }
}

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 {/*  w ww  . j a v  a2 s  .  c  o  m*/
            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:org.candlepin.CRLBenchmark.java

@Setup(Level.Trial)
public void buildMassiveCRL() throws Exception {
    X500Name issuer = new X500Name("CN=Test Issuer");

    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");

    generator.initialize(2048);// www  . j a v  a2s. c om
    KeyPair keyPair = generator.generateKeyPair();

    Provider bc = new BouncyCastleProvider();
    ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(bc)
            .build(keyPair.getPrivate());

    X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuer, new Date());

    crlBuilder.addExtension(X509Extension.authorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(keyPair.getPublic()));
    /* With a CRL number of 127, incrementing it should cause the number of bytes in the length
     * portion of the TLV to increase by one.*/
    crlBuilder.addExtension(X509Extension.cRLNumber, false, new CRLNumber(new BigInteger("127")));

    for (int i = 0; i < 2000000; i++) {
        crlBuilder.addCRLEntry(new BigInteger(String.valueOf(i)), new Date(), CRLReason.unspecified);
    }

    X509CRLHolder holder = crlBuilder.build(signer);
    X509CRL crl = new JcaX509CRLConverter().setProvider(bc).getCRL(holder);

    crlFile = File.createTempFile("crl", ".der");
    System.out.println("\nWrote test crl to " + crlFile.getAbsolutePath());
    FileUtils.writeByteArrayToFile(crlFile, crl.getEncoded());
}