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.github.aynu.mosir.core.standard.util.SecurityHelper.java

/**
 * RSA???/*  w  w  w.ja v a 2  s  .c o  m*/
 * <dl>
 * <dt>?
 * <dd>RSA??????2048??????
 * </dl>
 * @return RSA?
 */
public static KeyPair createKeyPair() {
    try {
        final KeyPairGenerator generator = KeyPairGenerator.getInstance(ALGO_KEY);
        generator.initialize(2048);
        final KeyPair pair = generator.generateKeyPair();
        if (LOG.isDebugEnabled()) {
            final RSAPublicKey publicKey = (RSAPublicKey) pair.getPublic();
            final RSAPrivateKey privateKey = (RSAPrivateKey) pair.getPrivate();
            LOG.debug("public-modulus={}", Base64.encodeBase64String(publicKey.getModulus().toByteArray()));
            LOG.debug("public-exponent={}",
                    Base64.encodeBase64String(publicKey.getPublicExponent().toByteArray()));
            LOG.debug("private-modulus={}", Base64.encodeBase64String(privateKey.getModulus().toByteArray()));
            LOG.debug("private-exponent={}",
                    Base64.encodeBase64String(privateKey.getPrivateExponent().toByteArray()));
        }
        return pair;
    } catch (final NoSuchAlgorithmException e) {
        throw new StandardRuntimeException(e);
    }
}

From source file:com.kixeye.chassis.transport.shared.JettyConnectorRegistry.java

/**
 * Register to listen to HTTPS.//from   w w  w  .java2s .c o  m
 * 
 * @param server
 * @param address
 * @throws Exception 
 */
public static void registerHttpsConnector(Server server, InetSocketAddress address, boolean selfSigned,
        boolean mutualSsl, String keyStorePath, String keyStoreData, String keyStorePassword,
        String keyManagerPassword, String trustStorePath, String trustStoreData, String trustStorePassword,
        String[] excludedCipherSuites) throws Exception {
    // SSL Context Factory
    SslContextFactory sslContextFactory = new SslContextFactory();

    if (selfSigned) {
        char[] passwordChars = UUID.randomUUID().toString().toCharArray();

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

        keyStore.load(null, passwordChars);

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

        v3CertGen.setSerialNumber(BigInteger.valueOf(new SecureRandom().nextInt()).abs());
        v3CertGen.setIssuerDN(new X509Principal("CN=" + "kixeye.com" + ", OU=None, O=None L=None, C=None"));
        v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
        v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)));
        v3CertGen.setSubjectDN(new X509Principal("CN=" + "kixeye.com" + ", OU=None, O=None L=None, C=None"));

        v3CertGen.setPublicKey(keyPair.getPublic());
        v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption");

        X509Certificate privateKeyCertificate = v3CertGen.generateX509Certificate(keyPair.getPrivate());

        keyStore.setKeyEntry("selfSigned", keyPair.getPrivate(), passwordChars,
                new java.security.cert.Certificate[] { privateKeyCertificate });

        ByteArrayOutputStream keyStoreBaos = new ByteArrayOutputStream();
        keyStore.store(keyStoreBaos, passwordChars);

        keyStoreData = new String(Hex.encode(keyStoreBaos.toByteArray()), Charsets.UTF_8);
        keyStorePassword = new String(passwordChars);
        keyManagerPassword = keyStorePassword;

        sslContextFactory.setTrustAll(true);
    }

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

    if (StringUtils.isNotBlank(keyStoreData)) {
        keyStore.load(new ByteArrayInputStream(Hex.decode(keyStoreData)), keyStorePassword.toCharArray());
    } else if (StringUtils.isNotBlank(keyStorePath)) {
        try (InputStream inputStream = new DefaultResourceLoader().getResource(keyStorePath).getInputStream()) {
            keyStore.load(inputStream, keyStorePassword.toCharArray());
        }
    }

    sslContextFactory.setKeyStore(keyStore);
    sslContextFactory.setKeyStorePassword(keyStorePassword);
    if (StringUtils.isBlank(keyManagerPassword)) {
        keyManagerPassword = keyStorePassword;
    }
    sslContextFactory.setKeyManagerPassword(keyManagerPassword);
    KeyStore trustStore = null;
    if (StringUtils.isNotBlank(trustStoreData)) {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(new ByteArrayInputStream(Hex.decode(trustStoreData)), trustStorePassword.toCharArray());
    } else if (StringUtils.isNotBlank(trustStorePath)) {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        try (InputStream inputStream = new DefaultResourceLoader().getResource(trustStorePath)
                .getInputStream()) {
            trustStore.load(inputStream, trustStorePassword.toCharArray());
        }
    }
    if (trustStore != null) {
        sslContextFactory.setTrustStore(trustStore);
        sslContextFactory.setTrustStorePassword(trustStorePassword);
    }
    sslContextFactory.setNeedClientAuth(mutualSsl);
    sslContextFactory.setExcludeCipherSuites(excludedCipherSuites);

    // SSL Connector
    ServerConnector connector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.toString()),
            new HttpConnectionFactory());
    connector.setHost(address.getHostName());
    connector.setPort(address.getPort());

    server.addConnector(connector);
}

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

@Before
public void setup() {
    service = new BCCertificateService();
    KeyPairGenerator keyGen;/*from w  w  w . j a  v a  2  s . c  o m*/
    try {
        keyGen = KeyPairGenerator.getInstance("RSA");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    keyGen.initialize(2048, new SecureRandom());
    KeyPair keypair = keyGen.generateKeyPair();
    publicKey = keypair.getPublic();
    privateKey = keypair.getPrivate();
}

From source file:co.cask.cdap.security.tools.KeyStores.java

/**
 * Create a Java key store with a stored self-signed certificate.
 * @return Java keystore which has a self signed X.509 certificate
 *///  w  w  w.  j  av a2 s. c o m
public static KeyStore generatedCertKeyStore(SConfiguration sConf, String password) {
    try {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance(KEY_PAIR_ALGORITHM);
        SecureRandom random = SecureRandom.getInstance(SECURE_RANDOM_ALGORITHM, SECURE_RANDOM_PROVIDER);
        keyGen.initialize(KEY_SIZE, random);
        // generate a key pair
        KeyPair pair = keyGen.generateKeyPair();
        int validity = sConf.getInt(Constants.Security.SSL.CERT_VALIDITY, VALIDITY);

        X509Certificate cert = getCertificate(DISTINGUISHED_NAME, pair, validity, SIGNATURE_ALGORITHM);

        KeyStore keyStore = KeyStore.getInstance(SSL_KEYSTORE_TYPE);
        keyStore.load(null, password.toCharArray());
        keyStore.setKeyEntry(CERT_ALIAS, pair.getPrivate(), password.toCharArray(),
                new java.security.cert.Certificate[] { cert });
        return keyStore;
    } catch (Exception e) {
        throw new RuntimeException(
                "SSL is enabled but a key store file could not be created. A keystore is required "
                        + "for SSL to be used.",
                e);
    }
}

From source file:edu.vt.middleware.crypt.util.CryptReaderWriterTest.java

/**
 * @return  Private key test data.//from w w w.java2 s  .  c om
 *
 * @throws  Exception  On test data generation failure.
 */
@DataProvider(name = "privkeydata")
public Object[][] createPrivKeyTestData() 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[][] { { rsaKeys.getPrivate(), "S33Kr1t!" }, { dsaKeys.getPrivate(), "S33Kr1t!" },
            { rsaKeys.getPrivate(), null }, { dsaKeys.getPrivate(), null }, };
}

From source file:org.wisdom.engine.ssl.FakeKeyStore.java

private static void generateAndStoreKeyStore(KeyStore keyStore, File keyStoreFile) throws Exception {
    FileOutputStream out = null;//from   w w w. java 2  s  .  c  o  m
    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 });

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

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

From source file:com.ligadata.EncryptUtils.EncryptionUtil.java

/**
 * Generate key which contains a pair of private and public key using 1024
 * bytes. Store the set of keys in given files publicKeyFile,privateKeyFile
 * @param algorithm//w  w w . java  2  s.c om
 *          : algorithm used
 * @param publicKeyFile
 *          :The file containing public key
 * @param privateKeyFile
 *          :The file containing private key
 */
public static void generateSampleKeys(String algorithm, String publicKeyFile, String privateKeyFile) {
    try {
        if (areKeysPresent(publicKeyFile, privateKeyFile)) {
            return;
        }
        final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm);
        keyGen.initialize(1024);
        final KeyPair key = keyGen.generateKeyPair();

        File privateKeyFD = new File(privateKeyFile);
        File publicKeyFD = new File(publicKeyFile);

        // Create files to store public and private key
        if (privateKeyFD.getParentFile() != null) {
            privateKeyFD.getParentFile().mkdirs();
        }
        privateKeyFD.createNewFile();

        if (publicKeyFD.getParentFile() != null) {
            publicKeyFD.getParentFile().mkdirs();
        }
        publicKeyFD.createNewFile();

        // Saving the Public key in a file
        ObjectOutputStream publicKeyOS = new ObjectOutputStream(new FileOutputStream(publicKeyFD));
        publicKeyOS.writeObject(key.getPublic());
        publicKeyOS.close();

        // Saving the Private key in a file
        ObjectOutputStream privateKeyOS = new ObjectOutputStream(new FileOutputStream(privateKeyFD));
        privateKeyOS.writeObject(key.getPrivate());
        privateKeyOS.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

private RSASignature create2(char[] password) throws Exception {

    KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
    keygen.initialize(2048);// w  w w  .j a  v a 2  s . c  o m
    KeyPair key = keygen.generateKeyPair();

    String pbeAlgName = "PBEWithMD5AndDES";
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    PBEParameterSpec pbeParamSpec = new PBEParameterSpec(RandomUtils.nextBytes(8), 20);
    SecretKey pbeKey = SecretKeyFactory.getInstance(pbeAlgName).generateSecret(pbeKeySpec);
    AlgorithmParameters pbeParam = AlgorithmParameters.getInstance(pbeAlgName);
    pbeParam.init(pbeParamSpec);
    Cipher cipher = Cipher.getInstance(pbeAlgName);
    cipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParam);
    EncryptedPrivateKeyInfo encryptedKeyInfo = new EncryptedPrivateKeyInfo(pbeParam,
            cipher.doFinal(key.getPrivate().getEncoded()));

    RSASignature impl = new RSASignature();
    impl.setAlgorithm("SHA256withRSA");
    impl.setPublicKeyBytes(key.getPublic().getEncoded());
    impl.setPrivateKeyBytes(encryptedKeyInfo.getEncoded(), password);
    return impl;
}

From source file:org.globus.gsi.gssapi.test.GlobusGSSCredentialTest.java

@Override
protected void setUp() throws Exception {
    manager = new GlobusGSSManagerImpl();
    kpg = KeyPairGenerator.getInstance("RSA");
    certificateGenerator = new X509V3CertificateGenerator();
    certificateGenerator.setIssuerDN(SELF_SIGNED_DN);
    certificateGenerator.setSubjectDN(SELF_SIGNED_DN);
    certificateGenerator.setNotBefore(new Date());
    certificateGenerator.setNotAfter(new Date(System.currentTimeMillis() + 1000 * 60));
    certificateGenerator.setSerialNumber(BigInteger.ONE);
    certificateGenerator.setSignatureAlgorithm("SHA1WithRSA");
}

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

private RSACrypto create2(char[] password) throws Exception {

    KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
    keygen.initialize(2048);/*from ww  w  .  jav  a2  s. c o m*/
    KeyPair key = keygen.generateKeyPair();

    String pbeAlgName = "PBEWithMD5AndDES";
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    PBEParameterSpec pbeParamSpec = new PBEParameterSpec(RandomUtils.nextBytes(8), 20);
    SecretKey pbeKey = SecretKeyFactory.getInstance(pbeAlgName).generateSecret(pbeKeySpec);
    AlgorithmParameters pbeParam = AlgorithmParameters.getInstance(pbeAlgName);
    pbeParam.init(pbeParamSpec);
    Cipher cipher = Cipher.getInstance(pbeAlgName);
    cipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParam);
    EncryptedPrivateKeyInfo encryptedKeyInfo = new EncryptedPrivateKeyInfo(pbeParam,
            cipher.doFinal(key.getPrivate().getEncoded()));

    RSACrypto impl = new RSACrypto();
    impl.setAlgorithm("RSA/ECB/PKCS1Padding");
    impl.setPublicKeyBytes(key.getPublic().getEncoded());
    impl.setPrivateKeyBytes(encryptedKeyInfo.getEncoded(), password);
    return impl;
}