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.streamsets.pipeline.stage.processor.http.HttpProcessorIT.java

@Test
public void testOAuth2Jwt() throws Exception {
    tokenGetCount = 0;/* www. ja v a  2  s. c  o m*/
    keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
    try {
        HttpProcessorConfig conf = new HttpProcessorConfig();
        conf.httpMethod = HttpMethod.GET;
        conf.dataFormat = DataFormat.JSON;
        conf.resourceUrl = getBaseUri() + "test/get";
        conf.client.useOAuth2 = true;
        conf.client.oauth2.credentialsGrantType = OAuth2GrantTypes.JWT;
        conf.client.oauth2.algorithm = SigningAlgorithms.RS256;
        conf.client.oauth2.jwtClaims = JWT;
        conf.client.oauth2.key = () -> Base64.encodeBase64String(keyPair.getPrivate().getEncoded());
        conf.client.oauth2.tokenUrl = getBaseUri() + "jwtToken";

        List<Record> records = createRecords("test/get");
        ProcessorRunner runner = createProcessorRunner(conf);
        try {
            StageRunner.Output output = runner.runProcess(records);
            assertOutputMap(output, "hello", "world!");
        } finally {
            runner.runDestroy();
        }
        assertEquals(1, tokenGetCount);
    } finally {
        token = null;
        tokenGetCount = 0;
    }
}

From source file:it.scoppelletti.programmerpower.security.CryptoUtils.java

/**
 * Restituisce un generatore di coppie di chiavi (pubblica, privata).
 *      // w w  w  .  j  a  v  a  2 s . c om
 * <H4>1. Propriet&agrave;</H4>
 * 
 * <P><TABLE WIDTH="100%" BORDER="1" CELLPADDING="5">
 * <THEAD>
 * <TR>
 *     <TH>Propriet&agrave;</TH>
 *     <TH>Descrizione</TH>     
 * </TR>
 * </THEAD>
 * <TBODY>
 * <TR>
 *      <TD>{@code alg}</TD>
 *      <TD>Codice dell&rsquo;algoritmo di crittografia.</TD>            
 * </TR>
 * <TR>
 *      <TD>{@code param.factory}</TD>
 *      <TD>Nome della classe di factory dei parametri specifici
 *      dell&rsquo;algoritmo; la classe deve implementare
 *      l&rsquo;interfaccia {@code AlgorithmParameterSpecFactory} e
 *      pu&ograve; prevedere altre propriet&agrave;.</TD>          
 * </TR>
 * <TR>
 *      <TD>{@code param.factory.prefix}</TD>
 *      <TD>Eventuale prefisso da applicare al nome delle propriet&agrave;
 *      interrogate dal provider {@code param.factory}.</TD>          
 * </TR> 
 * <TR>
 *      <TD>{@code key.size}</TD>
 *      <TD>Dimensione della chiave (numero di bit).</TD>          
 * </TR> 
 * <TR>
 *     <TD COLSPAN="2">Le propriet&agrave; {@code param.factory} e
 *     {@code key.size} non possono essere entrambe impostate; se nessuna
 *     delle due propriet&agrave; &egrave; impostata, il generatore
 *     sar&agrave; inizializzato con i parametri di default definiti dallo
 *     specifico provider JCA.</TD>
 * </TR>
 * </TBODY>
 * </TABLE></P>       
 *  
 * @param  props  Propriet&agrave;.
 * @param  prefix Prefisso da applicare al nome delle propriet&agrave; da
 *                interrogare. Pu&ograve; essere {@code null}.
 * @return        Oggetto.
 * @see    it.scoppelletti.programmerpower.security.spi.AlgorithmParameterSpecFactory
 * @see    <A HREF="{@docRoot}/it/scoppelletti/programmerpower/security/CryptoUtils.html#idAlg">Algoritmi
 *         di crittografia</A>
 */
public static KeyPairGenerator getKeyPairGenerator(Properties props, String prefix) {
    int keySize;
    String alg, name;
    KeyPairGenerator gen;
    AlgorithmParameterSpec params;
    SecurityResources res = new SecurityResources();

    if (props == null) {
        throw new ArgumentNullException("props");
    }

    name = Strings.concat(prefix, CryptoUtils.PROP_KEYALGORITHM);
    alg = props.getProperty(name);
    if (Strings.isNullOrEmpty(alg)) {
        throw new ArgumentNullException(name);
    }

    params = CryptoUtils.getAlgorithmParameterSpec(props, prefix);
    keySize = CryptoUtils.getKeySize(props, prefix);
    if (params != null && keySize >= 0) {
        throw new IllegalArgumentException(
                res.getArgumentIncompatibilityException(Strings.concat(prefix, CryptoUtils.PROP_PARAMFACTORY),
                        Strings.concat(prefix, CryptoUtils.PROP_KEYSIZE)));
    }

    try {
        gen = KeyPairGenerator.getInstance(alg);
        if (params != null) {
            gen.initialize(params);
        }
        if (keySize >= 0) {
            gen.initialize(keySize);
        }
    } catch (GeneralSecurityException ex) {
        throw SecurityUtils.toSecurityException(ex);
    }

    return gen;
}

From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java

/**
 * Initialize the Diffie-Hellman keys. This method is not thread safe
 *//*from  w  ww.j av a2  s  .  c  om*/
public static void initDHKeys(DistributionConfig config) throws Exception {

    dhSKAlgo = config.getSecurityClientDHAlgo();
    dhPrivateKey = null;
    dhPublicKey = null;
    // Initialize the keys when either the host is a client that has
    // non-blank setting for DH symmetric algo, or this is a server
    // that has authenticator defined.
    if ((dhSKAlgo != null && dhSKAlgo.length() > 0) /* || securityService.isClientSecurityRequired() */) {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH");
        DHParameterSpec dhSpec = new DHParameterSpec(dhP, dhG, dhL);
        keyGen.initialize(dhSpec);
        KeyPair keypair = keyGen.generateKeyPair();

        // Get the generated public and private keys
        dhPrivateKey = keypair.getPrivate();
        dhPublicKey = keypair.getPublic();

        random = new SecureRandom();
        // Force the random generator to seed itself.
        byte[] someBytes = new byte[48];
        random.nextBytes(someBytes);
    }
}

From source file:duthientan.mmanm.com.Main.java

private void BntGenerationKeyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BntGenerationKeyActionPerformed
    // TODO add your handling code here:
    if (filePath.size() != 0) {

        progressBarCipher.setIndeterminate(true);
        new Thread(new Runnable() {
            @Override//from   w w w .j a  v a 2  s  .  c om
            public void run() {
                try {
                    Path path = Paths.get(filePath.get(0));
                    String srcParent = path.getParent().toString();
                    final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
                    keyGen.initialize(2048);
                    final KeyPair key = keyGen.generateKeyPair();
                    File privateKeyFile = new File(srcParent + "/private.key");
                    File publicKeyFile = new File(srcParent + "/public.key");
                    publicKeyFile.createNewFile();
                    publicKeyFile.createNewFile();
                    ObjectOutputStream publicKeyOS = new ObjectOutputStream(
                            new FileOutputStream(publicKeyFile));
                    publicKeyOS.writeObject(key.getPublic());
                    publicKeyOS.close();
                    ObjectOutputStream privateKeyOS = new ObjectOutputStream(
                            new FileOutputStream(privateKeyFile));
                    privateKeyOS.writeObject(key.getPrivate());
                    privateKeyOS.close();
                    progressBarCipher.setIndeterminate(false);
                    JFrame frame = new JFrame("COMPLETED");
                    JOptionPane.showMessageDialog(frame, "Greneration Key File Completed");
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                } catch (NoSuchAlgorithmException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }).start();

    } else {
        JFrame frame = new JFrame("ERROR");
        JOptionPane.showMessageDialog(frame, "Please Choice File To Cipher Before Greneration Key");
    }
}

From source file:com.streamsets.pipeline.stage.origin.http.HttpClientSourceIT.java

@Test
public void testOAuth2Jwt() throws Exception {
    tokenGetCount = 0;//from   www  .  j  a  va 2 s.  c  om
    keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
    try {
        DataFormat dataFormat = DataFormat.JSON;
        HttpClientConfigBean conf = new HttpClientConfigBean();
        conf.client.authType = AuthenticationType.NONE;
        conf.client.useOAuth2 = true;
        conf.client.oauth2.credentialsGrantType = OAuth2GrantTypes.JWT;
        conf.client.oauth2.algorithm = SigningAlgorithms.RS256;
        conf.client.oauth2.jwtClaims = JWT;
        conf.client.oauth2.key = () -> Base64.encodeBase64String(keyPair.getPrivate().getEncoded());
        conf.client.oauth2.tokenUrl = getBaseUri() + "jwtToken";
        conf.httpMode = HttpClientMode.STREAMING;
        conf.resourceUrl = getBaseUri() + "stream";
        conf.client.readTimeoutMillis = 1000;
        conf.basic.maxBatchSize = 100;
        conf.basic.maxWaitTime = 1000;
        conf.pollingInterval = 1000;
        conf.httpMethod = HttpMethod.GET;
        conf.dataFormat = dataFormat;
        conf.dataFormatConfig.jsonContent = JsonMode.MULTIPLE_OBJECTS;

        runBatchAndAssertNames(dataFormat, conf);
        assertEquals(1, tokenGetCount);
    } finally {
        token = null;
    }
}