Example usage for java.security KeyPairGenerator initialize

List of usage examples for java.security KeyPairGenerator initialize

Introduction

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

Prototype

public void initialize(AlgorithmParameterSpec params) throws InvalidAlgorithmParameterException 

Source Link

Document

Initializes the key pair generator using the specified parameter set and the SecureRandom implementation of the highest-priority installed provider as the source of randomness.

Usage

From source file:org.apache.sshd.server.keyprovider.AbstractGeneratorHostKeyProvider.java

private KeyPair generateKeyPair(String algorithm) {
    try {//from   ww w . j  av  a  2  s.c o  m
        KeyPairGenerator generator = SecurityUtils.getKeyPairGenerator(algorithm);
        if (keySize != 0) {
            generator.initialize(keySize);
        }
        LOG.info("Generating host key...");
        KeyPair kp = generator.generateKeyPair();
        return kp;
    } catch (Exception e) {
        LOG.error("Unable to generate keypair", e);
        return null;
    }
}

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

public void createFakedCertificate() throws CertificateHandlerException {
    try {/*from www. j a  v  a2 s.  c  o 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.owasp.benchmark.testcode.BenchmarkTest02152.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");

    String param = request.getParameter("vector");
    if (param == null)
        param = "";

    String bar = doSomething(param);

    // Code based on example from:
    // http://examples.javacodegeeks.com/core-java/crypto/encrypt-decrypt-file-stream-with-des/

    try {// ww w. ja va2  s.  c o  m
        javax.crypto.Cipher c = javax.crypto.Cipher.getInstance("RSA/ECB/PKCS1Padding", "SunJCE");
        // Prepare the cipher to encrypt
        java.security.KeyPairGenerator keyGen = java.security.KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(1024);
        java.security.PublicKey publicKey = keyGen.genKeyPair().getPublic();
        c.init(javax.crypto.Cipher.ENCRYPT_MODE, publicKey);

        // encrypt and store the results
        byte[] input = { (byte) '?' };
        Object inputParam = bar;
        if (inputParam instanceof String)
            input = ((String) inputParam).getBytes();
        if (inputParam instanceof java.io.InputStream) {
            byte[] strInput = new byte[1000];
            int i = ((java.io.InputStream) inputParam).read(strInput);
            if (i == -1) {
                response.getWriter().println(
                        "This input source requires a POST, not a GET. Incompatible UI for the InputStream source.");
                return;
            }
            input = java.util.Arrays.copyOf(strInput, i);
        }
        byte[] result = c.doFinal(input);

        java.io.File fileTarget = new java.io.File(
                new java.io.File(org.owasp.benchmark.helpers.Utils.testfileDir), "passwordFile.txt");
        java.io.FileWriter fw = new java.io.FileWriter(fileTarget, true); //the true will append the new data
        fw.write("secret_value=" + org.owasp.esapi.ESAPI.encoder().encodeForBase64(result, true) + "\n");
        fw.close();
        response.getWriter()
                .println("Sensitive value: '" + org.owasp.esapi.ESAPI.encoder().encodeForHTML(new String(input))
                        + "' encrypted and stored<br/>");

    } catch (java.security.NoSuchAlgorithmException e) {
        response.getWriter().println(
                "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
        e.printStackTrace(response.getWriter());
        throw new ServletException(e);
    } catch (java.security.NoSuchProviderException e) {
        response.getWriter().println(
                "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
        e.printStackTrace(response.getWriter());
        throw new ServletException(e);
    } catch (javax.crypto.NoSuchPaddingException e) {
        response.getWriter().println(
                "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
        e.printStackTrace(response.getWriter());
        throw new ServletException(e);
    } catch (javax.crypto.IllegalBlockSizeException e) {
        response.getWriter().println(
                "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
        e.printStackTrace(response.getWriter());
        throw new ServletException(e);
    } catch (javax.crypto.BadPaddingException e) {
        response.getWriter().println(
                "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
        e.printStackTrace(response.getWriter());
        throw new ServletException(e);
    } catch (java.security.InvalidKeyException e) {
        response.getWriter().println(
                "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
        e.printStackTrace(response.getWriter());
        throw new ServletException(e);
    }
    response.getWriter()
            .println("Crypto Test javax.crypto.Cipher.getInstance(java.lang.String,java.lang.String) executed");
}

From source file:org.candlepin.util.X509CRLEntryStreamTest.java

@Before
public void setUp() throws Exception {
    URL url = X509CRLEntryStreamTest.class.getClassLoader().getResource("crl.der");
    derFile = new File(url.getFile());

    url = X509CRLEntryStreamTest.class.getClassLoader().getResource("crl.pem");
    pemFile = new File(url.getFile());

    issuer = new X500Name("CN=Test Issuer");

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

    generator.initialize(2048);
    keyPair = generator.generateKeyPair();

    signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(BC).build(keyPair.getPrivate());
}

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   ww w.  ja va2 s. c o  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:edu.vt.alerts.android.library.tasks.RegistrationTask.java

private KeyPair generateKeyPair() throws Exception {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance(KEYPAIR_ALGORITHM);
    kpg.initialize(KEYPAIR_KEYSIZE);
    return kpg.generateKeyPair();
}

From source file:org.owasp.benchmark.testcode.BenchmarkTest01139.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");

    String param = "";
    boolean flag = true;
    java.util.Enumeration<String> names = request.getHeaderNames();
    while (names.hasMoreElements() && flag) {
        String name = (String) names.nextElement();
        java.util.Enumeration<String> values = request.getHeaders(name);
        if (values != null) {
            while (values.hasMoreElements() && flag) {
                String value = (String) values.nextElement();
                if (value.equals("vector")) {
                    param = name;//www  . java 2 s  . c om
                    flag = false;
                }
            }
        }
    }

    String bar = new Test().doSomething(param);

    // Code based on example from:
    // http://examples.javacodegeeks.com/core-java/crypto/encrypt-decrypt-file-stream-with-des/

    try {
        javax.crypto.Cipher c = javax.crypto.Cipher.getInstance("RSA/ECB/PKCS1Padding", "SunJCE");
        // Prepare the cipher to encrypt
        java.security.KeyPairGenerator keyGen = java.security.KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(1024);
        java.security.PublicKey publicKey = keyGen.genKeyPair().getPublic();
        c.init(javax.crypto.Cipher.ENCRYPT_MODE, publicKey);

        // encrypt and store the results
        byte[] input = { (byte) '?' };
        Object inputParam = bar;
        if (inputParam instanceof String)
            input = ((String) inputParam).getBytes();
        if (inputParam instanceof java.io.InputStream) {
            byte[] strInput = new byte[1000];
            int i = ((java.io.InputStream) inputParam).read(strInput);
            if (i == -1) {
                response.getWriter().println(
                        "This input source requires a POST, not a GET. Incompatible UI for the InputStream source.");
                return;
            }
            input = java.util.Arrays.copyOf(strInput, i);
        }
        byte[] result = c.doFinal(input);

        java.io.File fileTarget = new java.io.File(
                new java.io.File(org.owasp.benchmark.helpers.Utils.testfileDir), "passwordFile.txt");
        java.io.FileWriter fw = new java.io.FileWriter(fileTarget, true); //the true will append the new data
        fw.write("secret_value=" + org.owasp.esapi.ESAPI.encoder().encodeForBase64(result, true) + "\n");
        fw.close();
        response.getWriter()
                .println("Sensitive value: '" + org.owasp.esapi.ESAPI.encoder().encodeForHTML(new String(input))
                        + "' encrypted and stored<br/>");

    } catch (java.security.NoSuchAlgorithmException e) {
        response.getWriter().println(
                "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
        e.printStackTrace(response.getWriter());
        throw new ServletException(e);
    } catch (java.security.NoSuchProviderException e) {
        response.getWriter().println(
                "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
        e.printStackTrace(response.getWriter());
        throw new ServletException(e);
    } catch (javax.crypto.NoSuchPaddingException e) {
        response.getWriter().println(
                "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
        e.printStackTrace(response.getWriter());
        throw new ServletException(e);
    } catch (javax.crypto.IllegalBlockSizeException e) {
        response.getWriter().println(
                "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
        e.printStackTrace(response.getWriter());
        throw new ServletException(e);
    } catch (javax.crypto.BadPaddingException e) {
        response.getWriter().println(
                "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
        e.printStackTrace(response.getWriter());
        throw new ServletException(e);
    } catch (java.security.InvalidKeyException e) {
        response.getWriter().println(
                "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case");
        e.printStackTrace(response.getWriter());
        throw new ServletException(e);
    }
    response.getWriter()
            .println("Crypto Test javax.crypto.Cipher.getInstance(java.lang.String,java.lang.String) executed");
}

From source file:cloud.google.com.windows.example.ExampleCode.java

private KeyPair generateKeys() throws NoSuchAlgorithmException {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");

    // Key moduli for encryption/decryption are 2048 bits long.
    keyGen.initialize(2048);

    return keyGen.genKeyPair();
}

From source file:hudson.cli.Connection.java

public KeyAgreement diffieHellman(boolean side, int keySize) throws IOException, GeneralSecurityException {
    KeyPair keyPair;/*  w ww . ja  va 2 s .  c  o m*/
    PublicKey otherHalf;

    if (side) {
        AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance("DH");
        paramGen.init(keySize);

        KeyPairGenerator dh = KeyPairGenerator.getInstance("DH");
        dh.initialize(paramGen.generateParameters().getParameterSpec(DHParameterSpec.class));
        keyPair = dh.generateKeyPair();

        // send a half and get a half
        writeKey(keyPair.getPublic());
        otherHalf = KeyFactory.getInstance("DH").generatePublic(readKey());
    } else {
        otherHalf = KeyFactory.getInstance("DH").generatePublic(readKey());

        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DH");
        keyPairGen.initialize(((DHPublicKey) otherHalf).getParams());
        keyPair = keyPairGen.generateKeyPair();

        // send a half and get a half
        writeKey(keyPair.getPublic());
    }

    KeyAgreement ka = KeyAgreement.getInstance("DH");
    ka.init(keyPair.getPrivate());
    ka.doPhase(otherHalf, true);

    return ka;
}

From source file:com.subgraph.vega.internal.http.proxy.ssl.CertificateCreator.java

private KeyPairGenerator createKeyGenerator() throws CertificateException {
    try {//from   w  ww  .  j a  v a 2 s.  c  o  m
        final KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(1024);
        return kpg;
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateException("Failed to create RSA key pair generator." + e.getMessage());
    }
}