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:my.adam.smo.common.AsymmetricEncryptionBox.java

@PostConstruct
public void init() throws NoSuchAlgorithmException {
    keyGen = KeyPairGenerator.getInstance("RSA");

    try {//from   w w  w  . java2 s .  c o  m
        PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(Base64.decode(this.privKeyS));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        prvKey = keyFactory.generatePrivate(privKeySpec);
    } catch (InvalidKeySpecException e) {
        logger.error("invalid private key", e);
    }

    try {
        X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(Base64.decode(this.pubKeyS));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        pubKey = keyFactory.generatePublic(pubKeySpec);
    } catch (InvalidKeySpecException e) {
        logger.error("invalid public key", e);
    }
}

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: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.");
    }//from   w w w  . jav a  2 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:org.aon.esolutions.appconfig.client.util.RSAEncryptUtil.java

public static KeyPair generateKey() throws GeneralSecurityException {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
    keyGen.initialize(1024);/*from  w  w  w  . ja v a  2  s. co  m*/
    KeyPair key = keyGen.generateKeyPair();
    return key;
}

From source file:com.xinferin.licensing.LicenceGenerator.java

/**
 * Creates a new private and public key and at the same time encodes the public key as XML to be used by the .NET client
 * @param size//from  w w w.  j ava2s.  co  m
 * @param productId
 *
 */
private void firstTimeInitialisation(int size) {
    try {

        // Get Key Pair Generator for RSA.
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(size);

        KeyPair keypair = keyGen.genKeyPair();
        privateKey = keypair.getPrivate();
        publicKey = keypair.getPublic();

        // Get the bytes of the public and private keys
        byte[] privateKeyBytes = privateKey.getEncoded();
        byte[] publicKeyBytes = publicKey.getEncoded();

        // store temporarily witht he public key for the lifetime of this class.
        encodedPrivateKey = new Base64().encode(privateKeyBytes);

        // Generate the Private Key, Public Key and Public Key in XML format.
        KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
        KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBytes));
        RSAPublicKey rsaPublicKey = (RSAPublicKey) KeyFactory.getInstance("RSA")
                .generatePublic(new X509EncodedKeySpec(publicKeyBytes));

        // Store the public key in XML string to make compatible .Net public key file
        encodedToXMLPublicKey = getRSAPublicKeyAsXMLString(rsaPublicKey);

    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
}

From source file:org.wisdom.framework.vertx.ssl.FakeKeyStore.java

private static void generateAndStoreKeyStore(KeyStore keyStore, File keyStoreFile) throws Exception {
    FileOutputStream out = null;//from   ww w . j  a  v a  2s .  c om
    try {
        LOGGER.info("Generating HTTPS key pair in " + keyStoreFile.getAbsolutePath() + " - this may take some"
                + " time. If nothing happens, try moving the mouse/typing on the keyboard to generate some entropy.");

        // Generate the key pair
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        // Generate a self signed certificate
        X509Certificate cert = createSelfSignedCertificate(keyPair);

        // Create the key store, first set the store pass
        keyStore.load(null, "".toCharArray());
        keyStore.setKeyEntry("wisdom-generated", keyPair.getPrivate(), "".toCharArray(),
                new X509Certificate[] { cert });

        keyStoreFile.getParentFile().mkdirs();
        out = new FileOutputStream(keyStoreFile);
        keyStore.store(out, "".toCharArray());

        LOGGER.info("Key Store generated in " + keyStoreFile.getAbsoluteFile());
    } finally {
        IOUtils.closeQuietly(out);
    }
}

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

/**
 * ?DSA??p,q,g,j,x,y/*from   ww  w  .  ja v  a 2s. co  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:org.computerist.ssltools.zap.ZapSslCertificateUtils.java

/**
 * Creates a new Root CA certificate and returns private and public key as
 * {@link KeyStore}. The {@link KeyStore#getDefaultType()} is used.
 *
 * @return//from   w  w w. j a v a2 s  .  co m
 * @throws NoSuchAlgorithmException If no providers are found
 * for 'RSA' key pair generator
 * or 'SHA1PRNG' Secure random number generator
 * @throws IllegalStateException in case of errors during assembling {@link KeyStore}
 */
public static final KeyStore createRootCA() throws NoSuchAlgorithmException {
    final Date startDate = Calendar.getInstance().getTime();
    final Date expireDate = new Date(startDate.getTime() + (DEFAULT_VALID_DAYS * 24L * 60L * 60L * 1000L));

    final KeyPairGenerator g = KeyPairGenerator.getInstance("RSA");
    g.initialize(2048, SecureRandom.getInstance("SHA1PRNG"));
    final KeyPair keypair = g.genKeyPair();
    final PrivateKey privKey = keypair.getPrivate();
    final PublicKey pubKey = keypair.getPublic();
    Random rnd = new Random();

    // using the hash code of the user's name and home path, keeps anonymity
    // but also gives user a chance to distinguish between each other
    X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE);
    namebld.addRDN(BCStyle.CN, "OWASP Zed Attack Proxy Root CA");
    namebld.addRDN(BCStyle.L, Integer.toHexString(System.getProperty("user.name").hashCode())
            + Integer.toHexString(System.getProperty("user.home").hashCode()));
    namebld.addRDN(BCStyle.O, "OWASP Root CA");
    namebld.addRDN(BCStyle.OU, "OWASP ZAP Root CA");
    namebld.addRDN(BCStyle.C, "xx");

    X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(namebld.build(),
            BigInteger.valueOf(rnd.nextInt()), startDate, expireDate, namebld.build(), pubKey);

    KeyStore ks = null;
    try {
        certGen.addExtension(X509Extension.subjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(pubKey));
        certGen.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(true));
        certGen.addExtension(X509Extension.keyUsage, false,
                new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment
                        | KeyUsage.dataEncipherment | KeyUsage.cRLSign));

        Vector<DERObject> eku = new Vector<>(3, 1);
        eku.add(KeyPurposeId.id_kp_serverAuth);
        eku.add(KeyPurposeId.id_kp_clientAuth);
        eku.add(KeyPurposeId.anyExtendedKeyUsage);
        certGen.addExtension(X509Extension.extendedKeyUsage, false, new ExtendedKeyUsage(eku));

        final ContentSigner sigGen = new JcaContentSignerBuilder("SHA1WithRSAEncryption").setProvider("BC")
                .build(privKey);
        final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC")
                .getCertificate(certGen.build(sigGen));

        ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null, null);
        ks.setKeyEntry(FixedSslCertificateService.ZAPROXY_JKS_ALIAS, privKey,
                FixedSslCertificateService.PASSPHRASE, new Certificate[] { cert });
    } catch (final Exception e) {
        throw new IllegalStateException("Errors during assembling root CA.", e);
    }
    return ks;
}

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

private String generatePublicKey() throws NoSuchAlgorithmException {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(1024, new SecureRandom());
    KeyPair kp = kpg.generateKeyPair();
    PublicKey pubKey = kp.getPublic();

    return Base64.encodeBase64String(pubKey.getEncoded());
}

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 ww  w  .  j a  v  a 2  s.c om*/

    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);
}