Example usage for java.security KeyPair getPublic

List of usage examples for java.security KeyPair getPublic

Introduction

In this page you can find the example usage for java.security KeyPair getPublic.

Prototype

public PublicKey getPublic() 

Source Link

Document

Returns a reference to the public key component of this key pair.

Usage

From source file:models.logic.CipherDecipher.java

public static void main(String[] args) {
    try {/*from   ww w  . ja v  a  2s . co  m*/

        System.out.println("Hash original: " + utils.HashGenerator.generateSHA512("originalFiles/original"));

        //Gerando o par
        KeyPair kp = publicPrivateKeyGenerator();
        User user = new User("Nome", "a@a.com", kp.getPublic(), kp.getPrivate());

        //Gerando a chave randomica
        SecretKey key = generateKey();

        //Encriptando o arquivo
        FileInputStream fis = new FileInputStream("originalFiles/original");
        FileOutputStream fos = new FileOutputStream("encrypted.txt");
        encrypt(key, fis, fos);
        System.out.println("Hash encriptado: " + utils.HashGenerator.generateSHA512("encrypted.txt"));

        //Salvando a chave em disco
        keyToFile(key, "key");
        //Encriptando a chave com a chave privada
        FileInputStream fisKey = new FileInputStream("key");
        FileOutputStream fosKey = new FileOutputStream("encryptedKey");
        encrypt((SecretKey) user.getPrivateKey(), fis, fos);

        //Decriptando a chave em disco
        FileInputStream fisKey2 = new FileInputStream("encryptedKey");
        FileOutputStream fosKey2 = new FileOutputStream("decryptedKey");
        decrypt((SecretKey) user.getPublicKey(), fisKey2, fosKey2);

        //Zerando a chave e abrindo do arquivo
        key = null;
        key = fileToKey("decryptedKey");

        //String keyString = keyToString(key);
        //System.out.println(keyString);
        //key = null;
        //key = stringToKey(keyString);

        FileInputStream fis2 = new FileInputStream("encrypted.txt");
        FileOutputStream fos2 = new FileOutputStream("decrypted.txt");
        decrypt(key, fis2, fos2);
        System.out.println("Hash Final: " + utils.HashGenerator.generateSHA512("decrypted.txt"));

    } catch (Throwable e) {
        e.printStackTrace();
    }
}

From source file:net.padlocksoftware.padlock.keymaker.Main.java

/**
 * @param args the command line arguments
 *///from  www.  j  a v  a2s .  co m
public static void main(String[] args) {

    int keySize = 1024;
    File file = null;

    if (args.length < 1 || args.length > 3) {
        showUsageAndExit();
    }

    for (int x = 0; x < args.length; x++) {
        String arg = args[x];

        if (arg.equals("-s")) {
            try {
                x++;
            } catch (Exception e) {
                showUsageAndExit();
            }
        } else {
            file = new File(arg);
        }
    }

    KeyPair pair = KeyManager.createKeyPair();
    try {
        KeyManager.exportKeyPair(pair, file);
        String[] lines = formatOutput(new String(Hex.encodeHex(pair.getPublic().getEncoded())));
        System.out.println("Your public key code: \n");
        for (int x = 0; x < lines.length; x++) {
            String line = lines[x];
            if (x == 0) {
                // First line
                System.out.println("\t private static final String publicKey = \n\t\t\"" + line + "\" + ");
            } else if (x == lines.length - 1) {
                // Last line
                System.out.println("\t\t\"" + line + "\";\n");
            } else {
                System.out.println("\t\t\"" + line + "\" + ");
            }
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }

}

From source file:SignatureTest.java

public static void main(String[] args) {
    try {//  w w w.java 2  s .  com
        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:com.cliqset.magicsig.util.KeyGen.java

public static void main(String[] args) {
    try {//from  w  ww.  j av a 2 s  . com
        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:org.apache.xml.security.samples.signature.CreateDonaldsAdditionalURISignature.java

/**
 * Method main/*from ww w.  j  a  v a  2  s .c om*/
 *
 * @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:MainClass.java

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

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", "BC");

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

    KeyPair keyPair = keyGen.generateKeyPair();
    Signature signature = Signature.getInstance("DSA", "BC");

    signature.initSign(keyPair.getPrivate(), new SecureRandom());
    byte[] message = "abc".getBytes();
    signature.update(message);/*from   w  w  w. j ava  2s  .co m*/

    byte[] sigBytes = signature.sign();
    signature.initVerify(keyPair.getPublic());
    signature.update(message);
    System.out.println(signature.verify(sigBytes));
}

From source file:MainClass.java

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

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC");

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

    KeyPair keyPair = keyGen.generateKeyPair();
    Signature signature = Signature.getInstance("SHA1withRSA", "BC");

    signature.initSign(keyPair.getPrivate(), new SecureRandom());

    byte[] message = "abc".getBytes();
    signature.update(message);//  w  w w.  j a  va2  s.com

    byte[] sigBytes = signature.sign();
    signature.initVerify(keyPair.getPublic());
    signature.update(message);
    System.out.println(signature.verify(sigBytes));
}

From source file:RSATest.java

public static void main(String[] args) {
    try {/*  w  w  w  . j a  va2s . co  m*/
        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:Main.java

public static void main(String[] args) throws Exception {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(1024);//from w  w w .  j a va2s. c om
    KeyPair keyPair = kpg.genKeyPair();

    byte[] data = "test".getBytes("UTF8");

    Signature sig = Signature.getInstance("MD5WithRSA");
    sig.initSign(keyPair.getPrivate());
    sig.update(data);
    byte[] signatureBytes = sig.sign();
    System.out.println("Singature:" + new BASE64Encoder().encode(signatureBytes));

    sig.initVerify(keyPair.getPublic());
    sig.update(data);

    System.out.println(sig.verify(signatureBytes));
}

From source file:MainClass.java

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

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC");
    keyGen.initialize(512, new SecureRandom());
    KeyPair keyPair = keyGen.generateKeyPair();

    Signature signature = Signature.getInstance("SHA256withRSA", "BC");
    signature.initSign(keyPair.getPrivate());

    byte[] message = "abc".getBytes();
    signature.update(message);/*from w  w  w.java 2 s  . co  m*/

    byte[] sigBytes = signature.sign();
    Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
    cipher.init(Cipher.DECRYPT_MODE, keyPair.getPublic());

    byte[] decSig = cipher.doFinal(sigBytes);
    ASN1InputStream aIn = new ASN1InputStream(decSig);
    ASN1Sequence seq = (ASN1Sequence) aIn.readObject();

    System.out.println(ASN1Dump.dumpAsString(seq));

    MessageDigest hash = MessageDigest.getInstance("SHA-256", "BC");
    hash.update(message);

    ASN1OctetString sigHash = (ASN1OctetString) seq.getObjectAt(1);
    System.out.println(MessageDigest.isEqual(hash.digest(), sigHash.getOctets()));
}