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:MainClass.java

public static void main(String[] args) throws Exception {
    String s = "F488FD584E49DBCD20B49DE49107366B336C380D451D0F7C88"
            + "11111111111111111111111111111111111111111111111111"
            + "11111111111111111111111111111111111111111111111111"
            + "11111111111111111111111111111111111111111111111111"
            + "11111111111111111111111111111111111111111111111111" + "2F78C7";
    BigInteger base = BigInteger.valueOf(2);
    BigInteger modulous = new BigInteger(s, 16);
    DHParameterSpec skipParameterSpec = new DHParameterSpec(modulous, base);

    KeyPairGenerator kpg1 = KeyPairGenerator.getInstance("DH");
    kpg1.initialize(skipParameterSpec);/*from w  w  w. j  a va  2  s  . c  o  m*/
    KeyPair kp1 = kpg1.generateKeyPair();

    KeyAgreement ka1 = KeyAgreement.getInstance("DH");
    DHPrivateKey privateKey1 = (DHPrivateKey) kp1.getPrivate();
    DHPublicKey publicKey1 = (DHPublicKey) kp1.getPublic();
    ka1.init(privateKey1);
    System.out.println("1 is using " + publicKey1.getY() + " for its public key");

    KeyPairGenerator kpg2 = KeyPairGenerator.getInstance("DH");
    kpg2.initialize(skipParameterSpec);
    KeyPair kp2 = kpg2.generateKeyPair();

    KeyAgreement ka2 = KeyAgreement.getInstance("DH");
    DHPrivateKey privateKey2 = (DHPrivateKey) kp2.getPrivate();
    DHPublicKey publicKey2 = (DHPublicKey) kp2.getPublic();
    ka2.init(privateKey2);
    System.out.println("2 is using " + publicKey2.getY() + "for its public key");
    // Use the KeyAgreement object of 1 to generate its shared key
    ka1.doPhase(publicKey2, true);
    SecretKey sharedKey1 = ka1.generateSecret("DES");
    System.out.println("1 is using " + new String(sharedKey1.getEncoded()) + " as its DES session key");
    // Use the KeyAgreement object of 2 to generate its shared key
    ka2.doPhase(publicKey1, true);
    SecretKey sharedKey2 = ka2.generateSecret("DES");
    System.out.println("2 is using " + new String(sharedKey2.getEncoded()) + "as its DES session key");
}

From source file:com.cliqset.magicsig.util.KeyGen.java

public static void main(String[] args) {
    try {//from   ww w  .j  av  a  2  s .  c  om
        FileOutputStream fos = new FileOutputStream(fileName);
        for (int x = 0; x < numKeys; x++) {
            fos.write((x + " RSA.").getBytes("ASCII"));
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(keySize);
            KeyPair keyPair = keyPairGenerator.genKeyPair();

            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPublicKeySpec publicSpec = keyFactory.getKeySpec(keyPair.getPublic(), RSAPublicKeySpec.class);
            RSAPrivateKeySpec privateSpec = keyFactory.getKeySpec(keyPair.getPrivate(),
                    RSAPrivateKeySpec.class);

            fos.write(Base64.encodeBase64URLSafe(getBytes(publicSpec.getModulus())));

            fos.write(".".getBytes("ASCII"));

            fos.write(Base64.encodeBase64URLSafe(getBytes(publicSpec.getPublicExponent())));

            fos.write(".".getBytes("ASCII"));

            fos.write(Base64.encodeBase64URLSafe(getBytes(privateSpec.getPrivateExponent())));

            fos.write("\n".getBytes("ASCII"));

            System.out.println(x);
        }
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:SignatureTest.java

public static void main(String[] args) {
    try {/*  w  w  w .jav  a 2  s.c  o m*/
        if (args[0].equals("-genkeypair")) {
            KeyPairGenerator pairgen = KeyPairGenerator.getInstance("DSA");
            SecureRandom random = new SecureRandom();
            pairgen.initialize(KEYSIZE, random);
            KeyPair keyPair = pairgen.generateKeyPair();
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(args[1]));
            out.writeObject(keyPair.getPublic());
            out.close();
            out = new ObjectOutputStream(new FileOutputStream(args[2]));
            out.writeObject(keyPair.getPrivate());
            out.close();
        } else if (args[0].equals("-sign")) {
            ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3]));
            PrivateKey privkey = (PrivateKey) keyIn.readObject();
            keyIn.close();

            Signature signalg = Signature.getInstance("DSA");
            signalg.initSign(privkey);

            File infile = new File(args[1]);
            InputStream in = new FileInputStream(infile);
            int length = (int) infile.length();
            byte[] message = new byte[length];
            in.read(message, 0, length);
            in.close();

            signalg.update(message);
            byte[] signature = signalg.sign();

            DataOutputStream out = new DataOutputStream(new FileOutputStream(args[2]));
            int signlength = signature.length;
            out.writeInt(signlength);
            out.write(signature, 0, signlength);
            out.write(message, 0, length);
            out.close();
        } else if (args[0].equals("-verify")) {
            ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[2]));
            PublicKey pubkey = (PublicKey) keyIn.readObject();
            keyIn.close();

            Signature verifyalg = Signature.getInstance("DSA");
            verifyalg.initVerify(pubkey);

            File infile = new File(args[1]);
            DataInputStream in = new DataInputStream(new FileInputStream(infile));
            int signlength = in.readInt();
            byte[] signature = new byte[signlength];
            in.read(signature, 0, signlength);

            int length = (int) infile.length() - signlength - 4;
            byte[] message = new byte[length];
            in.read(message, 0, length);
            in.close();

            verifyalg.update(message);
            if (!verifyalg.verify(signature))
                System.out.print("not ");
            System.out.println("verified");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:RSATest.java

public static void main(String[] args) {
    try {//from   ww w  .j a v a  2 s .  com
        if (args[0].equals("-genkey")) {
            KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA");
            SecureRandom random = new SecureRandom();
            pairgen.initialize(KEYSIZE, random);
            KeyPair keyPair = pairgen.generateKeyPair();
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(args[1]));
            out.writeObject(keyPair.getPublic());
            out.close();
            out = new ObjectOutputStream(new FileOutputStream(args[2]));
            out.writeObject(keyPair.getPrivate());
            out.close();
        } else if (args[0].equals("-encrypt")) {
            KeyGenerator keygen = KeyGenerator.getInstance("AES");
            SecureRandom random = new SecureRandom();
            keygen.init(random);
            SecretKey key = keygen.generateKey();

            // wrap with RSA public key
            ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3]));
            Key publicKey = (Key) keyIn.readObject();
            keyIn.close();

            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.WRAP_MODE, publicKey);
            byte[] wrappedKey = cipher.wrap(key);
            DataOutputStream out = new DataOutputStream(new FileOutputStream(args[2]));
            out.writeInt(wrappedKey.length);
            out.write(wrappedKey);

            InputStream in = new FileInputStream(args[1]);
            cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            crypt(in, out, cipher);
            in.close();
            out.close();
        } else {
            DataInputStream in = new DataInputStream(new FileInputStream(args[1]));
            int length = in.readInt();
            byte[] wrappedKey = new byte[length];
            in.read(wrappedKey, 0, length);

            // unwrap with RSA private key
            ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3]));
            Key privateKey = (Key) keyIn.readObject();
            keyIn.close();

            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.UNWRAP_MODE, privateKey);
            Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);

            OutputStream out = new FileOutputStream(args[2]);
            cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, key);

            crypt(in, out, cipher);
            in.close();
            out.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:testSig.java

public static void main(String[] args) {

    /* Test generating and verifying a DSA signature */

    try {//from w w  w .  j av a  2s  .c o  m

        /* generate a key pair */

        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
        keyGen.initialize(1024, new SecureRandom());
        KeyPair pair = keyGen.generateKeyPair();

        /*
         * create a Signature object to use for signing and verifying
         */

        Signature dsa = Signature.getInstance("SHA/DSA");

        /* initialize the Signature object for signing */

        PrivateKey priv = pair.getPrivate();

        dsa.initSign(priv);

        /* Update and sign the data */

        FileInputStream fis = new FileInputStream(args[0]);
        byte b;
        while (fis.available() != 0) {
            b = (byte) fis.read();
            dsa.update(b);
        }
        ;

        fis.close();

        /*
         * Now that all the data to be signed has been read in, sign it
         */
        byte[] sig = dsa.sign();

        /* Verify the signature */

        /* Initialize the Signature object for verification */
        PublicKey pub = pair.getPublic();
        dsa.initVerify(pub);

        /* Update and verify the data */

        fis = new FileInputStream(args[0]);
        while (fis.available() != 0) {
            b = (byte) fis.read();
            dsa.update(b);
        }
        ;

        fis.close();

        boolean verifies = dsa.verify(sig);

        System.out.println("signature verifies: " + verifies);

    } catch (Exception e) {
        System.err.println("Caught exception " + e.toString());
    }

}

From source file:com.emc.ecs.s3.sample.ECSS3Factory.java

public static void main(String[] args) {
    try {//from  ww  w . j a va 2  s.  c  om
        KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA");
        keyGenerator.initialize(1024, new SecureRandom());
        KeyPair myKeyPair = keyGenerator.generateKeyPair();

        // Serialize.
        byte[] pubKeyBytes = myKeyPair.getPublic().getEncoded();
        byte[] privKeyBytes = myKeyPair.getPrivate().getEncoded();

        String pubKeyStr = new String(Base64.encodeBase64(pubKeyBytes, false), "US-ASCII");
        String privKeyStr = new String(Base64.encodeBase64(privKeyBytes, false), "US-ASCII");

        System.out.println("Public Key: " + pubKeyStr);
        System.out.println("Private Key: " + privKeyStr);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.clustercontrol.util.KeyCheck.java

/**
 * ????????//from w w  w. ja v  a  2s  .  com
 * 
 * @param args
 */
public static void main(String[] args) {
    PrivateKey privateKey = null;
    PublicKey publicKey = null;

    /// ??????? true
    /// ???????? false (?)
    boolean flag = false;
    if (flag) {
        try {
            // ?
            privateKey = getPrivateKey(
                    "???????privateKey.txt??");

            // ?
            publicKey = getPublicKey("???????");
            // publicKey = getPublicKey(publicKeyStr);
        } catch (Exception e) {
            System.out.println("hoge" + e.getMessage());
        }
    } else {
        KeyPairGenerator generator;
        try {
            generator = KeyPairGenerator.getInstance(ALGORITHM);
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            // ?? 1024
            generator.initialize(1024, random);
            KeyPair keyPair = generator.generateKeyPair();
            privateKey = keyPair.getPrivate();
            publicKey = keyPair.getPublic();
        } catch (NoSuchAlgorithmException ex) {
            System.out.println(ex.getMessage());
        }
    }

    //
    // ?
    System.out.println("?");
    System.out.println(byte2String(privateKey.getEncoded()));
    System.out.println("?");
    System.out.println(byte2String(publicKey.getEncoded()));

    // ???????
    String string = "20140701_nttdata";
    byte[] src = string.getBytes();
    System.out.println("??String");
    System.out.println(string);
    System.out.println("??byte");
    System.out.println(byte2String(src));

    // ?
    try {
        String encStr = encrypt(string, privateKey);
        System.out.println("?");
        System.out.println(encStr);

        // ?
        String decStr = decrypt(encStr, publicKey);
        System.out.println("?");
        System.out.println(decStr);
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

}

From source file:Signing.java

public static void main(String[] args) throws Exception {
        SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();
        SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

        SOAPHeader soapHeader = soapEnvelope.getHeader();
        SOAPHeaderElement headerElement = soapHeader.addHeaderElement(soapEnvelope.createName("Signature",
                "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"));

        SOAPBody soapBody = soapEnvelope.getBody();
        soapBody.addAttribute(//from w  ww.j  a  v  a 2 s . c  o m
                soapEnvelope.createName("id", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"),
                "Body");
        Name bodyName = soapEnvelope.createName("FooBar", "z", "http://example.com");
        SOAPBodyElement gltp = soapBody.addBodyElement(bodyName);

        Source source = soapPart.getContent();
        Node root = null;
        if (source instanceof DOMSource) {
            root = ((DOMSource) source).getNode();
        } else if (source instanceof SAXSource) {
            InputSource inSource = ((SAXSource) source).getInputSource();
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            DocumentBuilder db = null;

            db = dbf.newDocumentBuilder();

            Document doc = db.parse(inSource);
            root = (Node) doc.getDocumentElement();
        }

        dumpDocument(root);

        KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
        kpg.initialize(1024, new SecureRandom());
        KeyPair keypair = kpg.generateKeyPair();

        XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance();
        Reference ref = sigFactory.newReference("#Body", sigFactory.newDigestMethod(DigestMethod.SHA1, null));
        SignedInfo signedInfo = sigFactory.newSignedInfo(
                sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                        (C14NMethodParameterSpec) null),
                sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref));
        KeyInfoFactory kif = sigFactory.getKeyInfoFactory();
        KeyValue kv = kif.newKeyValue(keypair.getPublic());
        KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(kv));

        XMLSignature sig = sigFactory.newXMLSignature(signedInfo, keyInfo);

        System.out.println("Signing the message...");
        PrivateKey privateKey = keypair.getPrivate();
        Element envelope = getFirstChildElement(root);
        Element header = getFirstChildElement(envelope);
        DOMSignContext sigContext = new DOMSignContext(privateKey, header);
        sigContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");
        sigContext.setIdAttributeNS(getNextSiblingElement(header),
                "http://schemas.xmlsoap.org/soap/security/2000-12", "id");
        sig.sign(sigContext);

        dumpDocument(root);

        System.out.println("Validate the signature...");
        Element sigElement = getFirstChildElement(header);
        DOMValidateContext valContext = new DOMValidateContext(keypair.getPublic(), sigElement);
        valContext.setIdAttributeNS(getNextSiblingElement(header),
                "http://schemas.xmlsoap.org/soap/security/2000-12", "id");
        boolean valid = sig.validate(valContext);

        System.out.println("Signature valid? " + valid);
    }

From source file:ai.susi.tools.JsonSignature.java

public static void main(String[] args) throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(2048);//w  ww . ja  v  a  2s  .  c o  m
    KeyPair keyPair = keyGen.genKeyPair();

    String jsonString = "{\n" + "        \"_id\": \"57b44e738d9af9fa2df13b27\",\n" + "        \"index\": 0,\n"
            + "        \"guid\": \"13af6838-08c8-4709-8dff-5ecb20bbaaa7\",\n" + "        \"isActive\": false,\n"
            + "        \"balance\": \"$2,092.08\",\n" + "        \"picture\": \"http://placehold.it/32x32\",\n"
            + "        \"age\": 22,\n" + "        \"eyeColor\": \"blue\",\n"
            + "        \"name\": \"Wyatt Jefferson\",\n" + "        \"gender\": \"male\",\n"
            + "        \"company\": \"GEEKFARM\",\n" + "        \"email\": \"wyattjefferson@geekfarm.com\",\n"
            + "        \"phone\": \"+1 (855) 405-2375\",\n"
            + "        \"address\": \"506 Court Street, Gambrills, Minnesota, 8953\",\n"
            + "        \"about\": \"Ea sunt quis non occaecat aliquip sint eiusmod. Aliquip id non ut sunt est laboris proident reprehenderit incididunt velit. Quis deserunt dolore aliqua voluptate magna laborum minim. Pariatur voluptate ad consequat culpa sit veniam eiusmod et ex ipsum.\\r\\n\",\n"
            + "        \"registered\": \"2015-08-08T03:21:53 -02:00\",\n"
            + "        \"latitude\": -39.880621,\n" + "        \"longitude\": 44.053688,\n"
            + "        \"tags\": [\n" + "            \"non\",\n" + "            \"cupidatat\",\n"
            + "            \"in\",\n" + "            \"Lorem\",\n" + "            \"tempor\",\n"
            + "            \"fugiat\",\n" + "            \"aliqua\"\n" + "        ],\n"
            + "        \"friends\": [\n" + "            {\n" + "                \"id\": 0,\n"
            + "                \"name\": \"Gail Blevins\"\n" + "            },\n" + "            {\n"
            + "                \"id\": 1,\n" + "                \"name\": \"Tricia Francis\"\n"
            + "            },\n" + "            {\n" + "                \"id\": 2,\n"
            + "                \"name\": \"Letitia Winters\"\n" + "            }\n" + "        ],\n"
            + "        \"greeting\": \"Hello, Wyatt Jefferson! You have 1 unread messages.\",\n"
            + "        \"favoriteFruit\": \"strawberry\"\n" + "    }";

    String jsonStringSimple = "{\n" + "        \"_id\": \"57b44e738d9af9fa2df13b27\",\n"
            + "        \"index\": 0,\n" + "        \"guid\": \"13af6838-08c8-4709-8dff-5ecb20bbaaa7\",\n"
            + "        \"isActive\": false,\n" + "        \"balance\": \"$2,092.08\",\n"
            + "        \"picture\": \"http://placehold.it/32x32\",\n" + "        \"age\": 22,\n"
            + "        \"eyeColor\": \"blue\",\n" + "        \"name\": \"Wyatt Jefferson\",\n"
            + "        \"gender\": \"male\",\n" + "        \"company\": \"GEEKFARM\",\n"
            + "        \"email\": \"wyattjefferson@geekfarm.com\",\n"
            + "        \"phone\": \"+1 (855) 405-2375\",\n"
            + "        \"address\": \"506 Court Street, Gambrills, Minnesota, 8953\",\n"
            + "        \"about\": \"Ea sunt quis non occaecat aliquip sint eiusmod. Aliquip id non ut sunt est laboris proident reprehenderit incididunt velit. Quis deserunt dolore aliqua voluptate magna laborum minim. Pariatur voluptate ad consequat culpa sit veniam eiusmod et ex ipsum.\\r\\n\",\n"
            + "        \"registered\": \"2015-08-08T03:21:53 -02:00\",\n"
            + "        \"latitude\": -39.880621,\n" + "        \"longitude\": 44.053688,\n" + "    }";

    JSONObject randomObj = new JSONObject(jsonString);
    JSONObject tmp = new JSONObject(jsonStringSimple);
    Map<String, byte[]> randomObj2 = new HashMap<String, byte[]>();
    for (String key : tmp.keySet()) {
        Object value = tmp.get(key);
        randomObj2.put(key, value.toString().getBytes());
    }

    addSignature(randomObj, keyPair.getPrivate());
    addSignature(randomObj2, keyPair.getPrivate());
    if (hasSignature(randomObj))
        System.out.println("Verify 1: " + verify(randomObj, keyPair.getPublic()));
    if (hasSignature(randomObj2))
        System.out.println("Verify 2: " + verify(randomObj, keyPair.getPublic()));
    removeSignature(randomObj);
    removeSignature(randomObj2);
}

From source file:Main.java

public static KeyPair generateRSAKeyPair(int keyLength) {
    try {//w ww . jav  a2 s  .c  om
        KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
        kpg.initialize(keyLength);
        return kpg.genKeyPair();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }
}