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, Provider provider)
        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 {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");
    SecureRandom random = new SecureRandom();

    KeyPairGenerator fact = KeyPairGenerator.getInstance("RSA", "BC");
    fact.initialize(1024, random);//from   w w  w. j  ava  2  s.co  m

    KeyPair keyPair = fact.generateKeyPair();
    Key wrapKey = createKeyForAES(256, random);
    cipher.init(Cipher.WRAP_MODE, wrapKey);

    byte[] wrappedKey = cipher.wrap(keyPair.getPrivate());
    cipher.init(Cipher.UNWRAP_MODE, wrapKey);
    Key key = cipher.unwrap(wrappedKey, "RSA", Cipher.PRIVATE_KEY);
    System.out.println(keyPair.getPrivate().equals(key));

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    //Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    DHParameterSpec dhParams = new DHParameterSpec(p512, g512);
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH", "BC");

    keyGen.initialize(dhParams, new SecureRandom());

    KeyAgreement aKeyAgree = KeyAgreement.getInstance("DH", "BC");
    KeyPair aPair = keyGen.generateKeyPair();
    KeyAgreement bKeyAgree = KeyAgreement.getInstance("DH", "BC");
    KeyPair bPair = keyGen.generateKeyPair();

    aKeyAgree.init(aPair.getPrivate());// w  w  w.  ja v a2  s.  c  o m
    bKeyAgree.init(bPair.getPrivate());

    aKeyAgree.doPhase(bPair.getPublic(), true);
    bKeyAgree.doPhase(aPair.getPublic(), true);

    MessageDigest hash = MessageDigest.getInstance("SHA1", "BC");
    System.out.println(new String(hash.digest(aKeyAgree.generateSecret())));
    System.out.println(new String(hash.digest(bKeyAgree.generateSecret())));
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    DHParameterSpec dhParams = new DHParameterSpec(p512, g512);
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH", "BC");

    keyGen.initialize(dhParams, new SecureRandom());

    KeyAgreement aKeyAgree = KeyAgreement.getInstance("DH", "BC");
    KeyPair aPair = keyGen.generateKeyPair();
    KeyAgreement bKeyAgree = KeyAgreement.getInstance("DH", "BC");
    KeyPair bPair = keyGen.generateKeyPair();

    aKeyAgree.init(aPair.getPrivate());//from  w  ww .  j  av  a2 s  . co m
    bKeyAgree.init(bPair.getPrivate());

    aKeyAgree.doPhase(bPair.getPublic(), true);
    bKeyAgree.doPhase(aPair.getPublic(), true);

    MessageDigest hash = MessageDigest.getInstance("SHA1", "BC");
    System.out.println(new String(hash.digest(aKeyAgree.generateSecret())));
    System.out.println(new String(hash.digest(bKeyAgree.generateSecret())));
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC");

    kpGen.initialize(1024, new SecureRandom());
    KeyPair pair = kpGen.generateKeyPair();
    PKCS10CertificationRequest request = generateRequest(pair);
    PEMWriter pemWrt = new PEMWriter(new OutputStreamWriter(System.out));
    pemWrt.writeObject(request);// w ww . j  a  v  a2  s .co m
    pemWrt.close();
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC");
    kpGen.initialize(1024, new SecureRandom());

    KeyPair pair = kpGen.generateKeyPair();

    PKCS10CertificationRequest request = generateRequest(pair);

    PEMWriter pemWrt = new PEMWriter(new OutputStreamWriter(System.out));
    pemWrt.writeObject(request);/*  w w w  .  ja  v  a2 s. c  o m*/
    pemWrt.close();
}

From source file:GenSig.java

public static void main(String[] args) {

    /* Generate a DSA signature */

    if (args.length != 1) {
        System.out.println("Usage: GenSig nameOfFileToSign");
    } else/*from   w w  w  . j  a  v a 2  s.  c o  m*/
        try {

            /* Generate a key pair */

            KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", "SUN");
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");

            keyGen.initialize(1024, random);

            KeyPair pair = keyGen.generateKeyPair();
            PrivateKey priv = pair.getPrivate();
            PublicKey pub = pair.getPublic();

            /*
             * Create a Signature object and initialize it with the private
             * key
             */

            Signature dsa = Signature.getInstance("SHA1withDSA", "SUN");

            dsa.initSign(priv);

            /* Update and sign the data */

            FileInputStream fis = new FileInputStream(args[0]);
            BufferedInputStream bufin = new BufferedInputStream(fis);
            byte[] buffer = new byte[1024];
            int len;
            while (bufin.available() != 0) {
                len = bufin.read(buffer);
                dsa.update(buffer, 0, len);
            }
            ;

            bufin.close();

            /*
             * Now that all the data to be signed has been read in, generate
             * a signature for it
             */

            byte[] realSig = dsa.sign();

            /* Save the signature in a file */
            FileOutputStream sigfos = new FileOutputStream("sig");
            sigfos.write(realSig);

            sigfos.close();

            /* Save the public key in a file */
            byte[] key = pub.getEncoded();
            FileOutputStream keyfos = new FileOutputStream("suepk");
            keyfos.write(key);

            keyfos.close();

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

}

From source file:org.apache.xml.security.samples.signature.CreateDonaldsAdditionalURISignature.java

/**
 * Method main// w  w  w.j a  v  a 2  s  . co m
 *
 * @param unused
 * @throws Exception
 */
public static void main(String unused[]) throws Exception {

    org.apache.xml.security.Init.init();

    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();

    dbf.setNamespaceAware(true);

    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();

    // test digests in references
    macAndWrite(db, "secret".getBytes("UTF-8"), XMLSignature.ALGO_ID_MAC_HMAC_SHA1,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1, "MacSha1_DigestSha1.xml");
    macAndWrite(db, "secret".getBytes("UTF-8"), XMLSignature.ALGO_ID_MAC_HMAC_SHA1,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA256, "MacSha1_DigestSha256.xml");
    macAndWrite(db, "secret".getBytes("UTF-8"), XMLSignature.ALGO_ID_MAC_HMAC_SHA1,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA384, "MacSha1_DigestSha384.xml");
    macAndWrite(db, "secret".getBytes("UTF-8"), XMLSignature.ALGO_ID_MAC_HMAC_SHA1,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA512, "MacSha1_DigestSha512.xml");
    macAndWrite(db, "secret".getBytes("UTF-8"), XMLSignature.ALGO_ID_MAC_HMAC_SHA1,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_RIPEMD160, "MacSha1_DigestRipemd160.xml");
    macAndWrite(db, "secret".getBytes("UTF-8"), XMLSignature.ALGO_ID_MAC_HMAC_SHA1,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5, "MacSha1_DigestMd5.xml");

    // test digests in hmacs
    macAndWrite(db, "secret".getBytes("UTF-8"), XMLSignature.ALGO_ID_MAC_HMAC_SHA1,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1, "MacSha1_DigestSha1.xml");
    macAndWrite(db, "secret".getBytes("UTF-8"), XMLSignature.ALGO_ID_MAC_HMAC_SHA256,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1, "MacSha256_DigestSha1.xml");
    macAndWrite(db, "secret".getBytes("UTF-8"), XMLSignature.ALGO_ID_MAC_HMAC_SHA384,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1, "MacSha384_DigestSha1.xml");
    macAndWrite(db, "secret".getBytes("UTF-8"), XMLSignature.ALGO_ID_MAC_HMAC_SHA512,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1, "MacSha512_DigestSha1.xml");
    macAndWrite(db, "secret".getBytes("UTF-8"), XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1, "MacRipemd160_DigestSha1.xml");
    macAndWrite(db, "secret".getBytes("UTF-8"), XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1, "MacMd5_DigestSha1.xml");

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC");
    KeyPair keyPair = kpg.generateKeyPair();
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey pubkey = keyPair.getPublic();

    // test digests in RSA
    signAndWrite(db, privateKey, pubkey, XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1, "SignatureRsaSha1_DigestSha1.xml");
    signAndWrite(db, privateKey, pubkey, XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1, "SignatureRsaSha256_DigestSha1.xml");
    signAndWrite(db, privateKey, pubkey, XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1, "SignatureRsaSha384_DigestSha1.xml");
    signAndWrite(db, privateKey, pubkey, XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1, "SignatureRsaSha512_DigestSha1.xml");
    signAndWrite(db, privateKey, pubkey, XMLSignature.ALGO_ID_SIGNATURE_RSA_RIPEMD160,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1, "SignatureRsaRipemd160_DigestSha1.xml");
    signAndWrite(db, privateKey, pubkey, XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1, "SignatureRsaMd5_DigestSha1.xml");
}

From source file:com.lingxiang2014.util.RSAUtils.java

public static KeyPair generateKeyPair() {
    try {/*from ww  w.j  av a  2s .c  om*/
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", PROVIDER);
        keyPairGenerator.initialize(KEY_SIZE, new SecureRandom());
        return keyPairGenerator.generateKeyPair();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:Main.java

@SuppressLint("NewApi")
public static KeyPair generateRsaPairWithGenerator(Context ctx, String alais)
        throws InvalidAlgorithmParameterException, NoSuchProviderException, NoSuchAlgorithmException {
    Calendar notBefore = Calendar.getInstance();
    Calendar notAfter = Calendar.getInstance();
    notAfter.add(1, Calendar.YEAR);
    KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(ctx).setAlias(alais)
            .setSubject(new X500Principal(String.format("CN=%s, OU=%s", alais, ctx.getPackageName())))
            .setSerialNumber(BigInteger.ONE).setStartDate(notBefore.getTime()).setEndDate(notAfter.getTime())
            .build();// w w  w.j  a v a2  s.  co m

    KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
    kpGenerator.initialize(spec);
    KeyPair kp = kpGenerator.generateKeyPair();

    return kp;
}

From source file:Main.java

static KeyPair generateRsaKeyPair(int keySizeInBits) {
    if (keySizeInBits == 0 || keySizeInBits % 8 != 0)
        return null;
    try {//  w  ww  .j  a  v  a  2  s .  c om
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "SC");
        generator.initialize(keySizeInBits, new SecureRandom());

        KeyPair pair = generator.generateKeyPair();

        // Log.d("","public : "+keyToBase64(pair.getPublic()));
        // Log.d("","private: "+keyToBase64(pair.getPrivate()));

        return pair;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}