List of usage examples for java.security KeyPair getPrivate
public PrivateKey getPrivate()
From source file:org.apache.xml.security.samples.signature.CreateDonaldsAdditionalURISignature.java
/** * Method main// w w w. j a v a2 s . com * * @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:models.logic.CipherDecipher.java
public static void main(String[] args) { try {//from www . j a v a2 s . c o 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:MainClass.java
public static void main(String[] args) throws Exception { String password = "password"; KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024);//from ww w .j a va 2s. c o m KeyPair keyPair = keyPairGenerator.genKeyPair(); String publicKeyFilename = "public"; byte[] publicKeyBytes = keyPair.getPublic().getEncoded(); FileOutputStream fos = new FileOutputStream(publicKeyFilename); fos.write(publicKeyBytes); fos.close(); String privateKeyFilename = "privateKeyFilename"; byte[] privateKeyBytes = keyPair.getPrivate().getEncoded(); byte[] encryptedPrivateKeyBytes = passwordEncrypt(password.toCharArray(), privateKeyBytes); fos = new FileOutputStream(privateKeyFilename); fos.write(encryptedPrivateKeyBytes); fos.close(); }
From source file:com.cliqset.magicsig.util.KeyGen.java
public static void main(String[] args) { try {/*from ww w . j a va 2 s . c o m*/ 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:testSig.java
public static void main(String[] args) { /* Test generating and verifying a DSA signature */ try {/*from w w w . ja v a 2 s . 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.clustercontrol.util.KeyCheck.java
/** * ????????/*from www .j a v a 2 s .c o m*/ * * @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:SignatureTest.java
public static void main(String[] args) { try {/* w ww. j a v a 2s . co 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:MainClass.java
public static void main(String[] args) throws Exception { KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish"); keyGenerator.init(128);/* w w w .j av a2s .co m*/ Key blowfishKey = keyGenerator.generateKey(); KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024); KeyPair keyPair = keyPairGenerator.genKeyPair(); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic()); byte[] blowfishKeyBytes = blowfishKey.getEncoded(); System.out.println(new String(blowfishKeyBytes)); byte[] cipherText = cipher.doFinal(blowfishKeyBytes); System.out.println(new String(cipherText)); cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate()); byte[] decryptedKeyBytes = cipher.doFinal(cipherText); System.out.println(new String(decryptedKeyBytes)); SecretKey newBlowfishKey = new SecretKeySpec(decryptedKeyBytes, "Blowfish"); }
From source file:cloudeventbus.cli.Certs.java
public static void main(String[] args) throws Exception { final JCommander commander = new JCommander(); final DefaultOptions options = new DefaultOptions(); final CreateAuthorityCommand createAuthorityCommand = new CreateAuthorityCommand(); final CreateClientCommand createClientCommand = new CreateClientCommand(); final CreateServerCommand createServerCommand = new CreateServerCommand(); final ChainCertificateCommand chainCertificateCommand = new ChainCertificateCommand(); final ShowCertificateCommand showCertificateCommand = new ShowCertificateCommand(); final ImportCertificatesCommand importCertificatesCommand = new ImportCertificatesCommand(); final RemoveAuthorityCommand removeAuthorityCommand = new RemoveAuthorityCommand(); final ValidateCommand validateCommand = new ValidateCommand(); commander.addObject(options);//from w ww .jav a 2s .c o m commander.addCommand(createAuthorityCommand); commander.addCommand(createClientCommand); commander.addCommand(createServerCommand); commander.addCommand(chainCertificateCommand); commander.addCommand(new ListAuthorities()); commander.addCommand(showCertificateCommand); commander.addCommand(importCertificatesCommand); commander.addCommand(removeAuthorityCommand); commander.addCommand(validateCommand); commander.setProgramName("eventbus-certs"); try { commander.parse(args); final String command = commander.getParsedCommand(); if (command == null) { commander.usage(); } else { final TrustStore trustStore = CertificateUtils.loadTrustStore(options.trustStore); switch (command) { case CREATE_AUTHORITY: { final KeyPair keyPair = CertificateUtils.generateKeyPair(); CertificateUtils.savePrivateKey(keyPair.getPrivate(), createAuthorityCommand.privateKey); final Certificate certificate = CertificateUtils.generateSelfSignedCertificate(keyPair, getExpirationDate(createAuthorityCommand.expirationDate), Subject.list(createAuthorityCommand.subscribePermissions), Subject.list(createAuthorityCommand.publishPermissions), createAuthorityCommand.comment); trustStore.add(certificate); CertificateUtils.saveCertificates(options.trustStore, trustStore); System.out.println("Created authority certificate."); break; } case LIST_AUTHORITIES: { displayCertificates(trustStore); break; } case CREATE_CLIENT: createCertificate(trustStore, Certificate.Type.CLIENT, createClientCommand); break; case CREATE_SERVER: createCertificate(trustStore, Certificate.Type.SERVER, createServerCommand); break; case SHOW_CERTIFICATE: { final CertificateChain certificates = CertificateUtils .loadCertificateChain(showCertificateCommand.certificate); displayCertificates(certificates); break; } case CHAIN_CERTIFICATE: chainCertificate(chainCertificateCommand); break; case VALIDATE_CERTIFICATE: { final CertificateChain certificates = CertificateUtils .loadCertificateChain(validateCommand.certificate); trustStore.validateCertificateChain(certificates); System.out.println(validateCommand.certificate + " is valid."); break; } case IMPORT_CERTIFICATES: { final Path path = Paths.get(importCertificatesCommand.certificate); try (final InputStream fileIn = Files.newInputStream(path); final InputStream in = new Base64InputStream(fileIn)) { final Collection<Certificate> certificates = new ArrayList<>(); CertificateStoreLoader.load(in, certificates); for (Certificate certificate : certificates) { trustStore.add(certificate); } CertificateUtils.saveCertificates(options.trustStore, trustStore); } break; } case REMOVE_AUTHORITY: if (trustStore.remove(removeAuthorityCommand.serialNumber)) { System.err.println("Removed certificate from trust store."); CertificateUtils.saveCertificates(options.trustStore, trustStore); } else { System.err.println("Certificate with serial number " + removeAuthorityCommand.serialNumber + " not found."); } } } } catch (ParameterException e) { System.err.println(e.getMessage()); commander.usage(commander.getParsedCommand()); System.exit(1); } }
From source file:RSATest.java
public static void main(String[] args) { try {//from w ww . j a va 2 s . c om 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(); } }