List of usage examples for javax.crypto KeyGenerator generateKey
public final SecretKey generateKey()
From source file:MainClass.java
public static void main(String[] args) throws Exception { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); byte[] input = "www.java2s.com".getBytes(); byte[] ivBytes = new byte[] { 0x00, 0x00, 0x00, 0x01, 0x04, 0x05, 0x06, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 };// ww w . jav a2 s. c om Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC"); KeyGenerator generator = KeyGenerator.getInstance("AES", "BC"); generator.init(192); Key encryptionKey = generator.generateKey(); System.out.println("key : " + Utils.toHex(encryptionKey.getEncoded())); System.out.println("input : " + new String(input)); // encryption pass cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, new IvParameterSpec(ivBytes)); byte[] cipherText = new byte[cipher.getOutputSize(input.length)]; int ctLength = cipher.update(input, 0, input.length, cipherText, 0); ctLength += cipher.doFinal(cipherText, ctLength); // decryption pass Key decryptionKey = new SecretKeySpec(encryptionKey.getEncoded(), encryptionKey.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, decryptionKey, new IvParameterSpec(ivBytes)); byte[] plainText = new byte[cipher.getOutputSize(ctLength)]; int ptLength = cipher.update(cipherText, 0, ctLength, plainText, 0); ptLength += cipher.doFinal(plainText, ptLength); System.out.println("plain : " + new String(plainText) + " bytes: " + ptLength); }
From source file:MainClass.java
public static void main(String args[]) throws Exception { KeyGenerator keyGen = KeyGenerator.getInstance("DES"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN"); random.setSeed(101L);//from www . j av a 2 s.c o m keyGen.init(56, random); SecretKey sKey = keyGen.generateKey(); SecretKeyFactory kfactory = SecretKeyFactory.getInstance("DES"); DESKeySpec kspec = (DESKeySpec) kfactory.getKeySpec(sKey, DESKeySpec.class); System.out.println(sKey); FileOutputStream fos = new FileOutputStream("secretKeys"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(kspec.getKey()); FileInputStream fin = new FileInputStream("secretKeys"); ObjectInputStream ois = new ObjectInputStream(fin); byte[] kMaterial = (byte[]) ois.readObject(); DESKeySpec keyspec = new DESKeySpec(kMaterial); SecretKey newKey = kfactory.generateSecret(keyspec); System.out.println(newKey); System.out.println("Do the keys equal :" + newKey.equals(sKey)); }
From source file:org.apache.juddi.samples.DES.java
public static void main(String[] args) throws Exception { DES des = new DES(); KeyGenerator kgen; try {//w w w . j av a 2s .c om kgen = KeyGenerator.getInstance(DESEDE_ENCRYPTION_SCHEME); kgen.init(168); SecretKey skey = kgen.generateKey(); byte[] raw = skey.getEncoded(); myEncryptionKey = new String(Base64.encodeBase64(raw)); myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME; arrayBytes = myEncryptionKey.getBytes(UNICODE_FORMAT); ks = new DESedeKeySpec(arrayBytes); skf = SecretKeyFactory.getInstance(myEncryptionScheme); cipher = Cipher.getInstance(myEncryptionScheme); key = skf.generateSecret(ks); System.out.println(new String(Base64.encodeBase64(raw))); System.out.println(des.encrypt("password")); System.out.println(des.decrypt(des.encrypt("password"))); } catch (Exception ex) { ex.printStackTrace(); ; } }
From source file:org.apache.metron.dataservices.auth.AuthToken.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("keystoreFile", true, "Keystore File"); options.addOption("keystorePassword", true, "Keystore Password"); options.addOption("authTokenAlias", true, ""); CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(options, args); try {//from w w w. j a v a2 s . com KeyStore ks = KeyStore.getInstance("JCEKS"); String keystorePassword = cmd.getOptionValue("keystorePassword"); String keystoreFile = cmd.getOptionValue("keystoreFile"); String authTokenAlias = cmd.getOptionValue("authTokenAlias"); ks.load(null, keystorePassword.toCharArray()); // generate a key and store it in the keystore... KeyGenerator keyGen = KeyGenerator.getInstance("AES"); SecretKey key = keyGen.generateKey(); KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection( keystorePassword.toCharArray()); KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(key); ks.setEntry(authTokenAlias, skEntry, protParam); java.io.FileOutputStream fos = null; try { fos = new java.io.FileOutputStream(keystoreFile); ks.store(fos, keystorePassword.toCharArray()); } finally { if (fos != null) { fos.close(); } } System.out.println("done"); } catch (Exception e) { e.printStackTrace(); } }
From source file:AESTest.java
public static void main(String[] args) { try {//from ww w . j av a 2 s . c o m if (args[0].equals("-genkey")) { KeyGenerator keygen = KeyGenerator.getInstance("AES"); SecureRandom random = new SecureRandom(); keygen.init(random); SecretKey key = keygen.generateKey(); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(args[1])); out.writeObject(key); out.close(); } else { int mode; if (args[0].equals("-encrypt")) mode = Cipher.ENCRYPT_MODE; else mode = Cipher.DECRYPT_MODE; ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3])); Key key = (Key) keyIn.readObject(); keyIn.close(); InputStream in = new FileInputStream(args[1]); OutputStream out = new FileOutputStream(args[2]); Cipher cipher = Cipher.getInstance("AES"); cipher.init(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:RSATest.java
public static void main(String[] args) { try {/*from w w w.jav a 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(); } }
From source file:com.tremolosecurity.openunison.util.OpenUnisonUtils.java
public static void main(String[] args) throws Exception { logger = org.apache.logging.log4j.LogManager.getLogger(OpenUnisonUtils.class.getName()); Options options = new Options(); options.addOption("unisonXMLFile", true, "The full path to the Unison xml file"); options.addOption("keystorePath", true, "The full path to the Unison keystore"); options.addOption("chainName", true, "The name of the authentication chain"); options.addOption("mechanismName", true, "The name of the authentication mechanism for SAML2"); options.addOption("idpName", true, "The name of the identity provider application"); options.addOption("pathToMetaData", true, "The full path to the saml2 metadata file"); options.addOption("createDefault", false, "If set, add default parameters"); options.addOption("action", true, "export-sp-metadata, import-sp-metadata, export-secretkey, print-secretkey, import-idp-metadata, export-idp-metadata, clear-dlq, import-secretkey, create-secretkey"); options.addOption("urlBase", true, "Base URL, no URI; https://host:port"); options.addOption("alias", true, "Key alias"); options.addOption("newKeystorePath", true, "Path to the new keystore"); options.addOption("newKeystorePassword", true, "Password for the new keystore"); options.addOption("help", false, "Prints this message"); options.addOption("signMetadataWithKey", true, "Signs the metadata with the specified key"); options.addOption("dlqName", true, "The name of the dead letter queue"); options.addOption("upgradeFrom106", false, "Updates workflows from 1.0.6"); options.addOption("secretkey", true, "base64 encoded secret key"); options.addOption("envFile", true, "Environment variables for parmaterized configs"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args, true); if (args.length == 0 || cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("OpenUnisonUtils", options); }/*from ww w . jav a 2s. c om*/ logger.info("Loading Unison Configuration"); String unisonXMLFile = loadOption(cmd, "unisonXMLFile", options); TremoloType ttRead = loadTremoloType(unisonXMLFile, cmd, options); String action = loadOption(cmd, "action", options); TremoloType ttWrite = null; if (action.equalsIgnoreCase("import-sp-metadata") || action.equalsIgnoreCase("import-idp-metadata")) { ttWrite = loadTremoloType(unisonXMLFile); } logger.info("Configuration loaded"); logger.info("Loading the keystore..."); String ksPath = loadOption(cmd, "keystorePath", options); KeyStore ks = loadKeyStore(ksPath, ttRead); logger.info("...loaded"); if (action.equalsIgnoreCase("import-sp-metadata")) { importMetaData(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks); } else if (action.equalsIgnoreCase("export-sp-metadata")) { exportSPMetaData(options, cmd, ttRead, ks); } else if (action.equalsIgnoreCase("print-secretkey")) { printSecreyKey(options, cmd, ttRead, ks); } else if (action.equalsIgnoreCase("import-secretkey")) { importSecreyKey(options, cmd, ttRead, ks, ksPath); } else if (action.equalsIgnoreCase("create-secretkey")) { Security.addProvider(new BouncyCastleProvider()); logger.info("Creating AES-256 secret key"); String alias = loadOption(cmd, "alias", options); logger.info("Alias : '" + alias + "'"); KeyGenerator kg = KeyGenerator.getInstance("AES", "BC"); kg.init(256, new SecureRandom()); SecretKey sk = kg.generateKey(); ks.setKeyEntry(alias, sk, ttRead.getKeyStorePassword().toCharArray(), null); logger.info("Saving key"); ks.store(new FileOutputStream(ksPath), ttRead.getKeyStorePassword().toCharArray()); logger.info("Finished"); } else if (action.equalsIgnoreCase("export-secretkey")) { logger.info("Export Secret Key"); logger.info("Loading key"); String alias = loadOption(cmd, "alias", options); SecretKey key = (SecretKey) ks.getKey(alias, ttRead.getKeyStorePassword().toCharArray()); logger.info("Loading new keystore path"); String pathToNewKeystore = loadOption(cmd, "newKeystorePath", options); logger.info("Loading new keystore password"); String ksPassword = loadOption(cmd, "newKeystorePassword", options); KeyStore newKS = KeyStore.getInstance("PKCS12"); newKS.load(null, ttRead.getKeyStorePassword().toCharArray()); newKS.setKeyEntry(alias, key, ksPassword.toCharArray(), null); newKS.store(new FileOutputStream(pathToNewKeystore), ksPassword.toCharArray()); logger.info("Exported"); } else if (action.equalsIgnoreCase("import-idp-metadata")) { importIdpMetadata(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks); } else if (action.equalsIgnoreCase("export-idp-metadata")) { exportIdPMetadata(options, cmd, ttRead, ks); } else if (action.equalsIgnoreCase("clear-dlq")) { logger.info("Getting the DLQ Name..."); String dlqName = loadOption(cmd, "dlqName", options); QueUtils.emptyDLQ(ttRead, dlqName); } else if (action.equalsIgnoreCase("upgradeFrom106")) { logger.info("Upgrading OpenUnison's configuration from 1.0.6"); String backupFileName = unisonXMLFile + ".bak"; logger.info("Backing up to '" + backupFileName + "'"); BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(unisonXMLFile))); PrintWriter out = new PrintWriter(new FileOutputStream(backupFileName)); String line = null; while ((line = in.readLine()) != null) { out.println(line); } out.flush(); out.close(); in.close(); ByteArrayOutputStream bout = new ByteArrayOutputStream(); AddChoiceToTasks.convert(new FileInputStream(unisonXMLFile), bout); FileOutputStream fsout = new FileOutputStream(unisonXMLFile); fsout.write(bout.toByteArray()); fsout.flush(); fsout.close(); } }
From source file:MainClass.java
public static void desEncrypt(String f1, String f2) throws Exception { SecretKey key = null;/*from ww w. ja v a 2s .c om*/ ObjectInputStream keyFile = new ObjectInputStream(new FileInputStream("DESKey.ser")); key = (SecretKey) keyFile.readObject(); keyFile.close(); KeyGenerator keygen = KeyGenerator.getInstance("DES"); key = keygen.generateKey(); ObjectOutputStream keyFileout = new ObjectOutputStream(new FileOutputStream("DESKey.ser")); keyFileout.writeObject(key); keyFileout.close(); Cipher cipher = null; cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); BufferedInputStream in = new BufferedInputStream(new FileInputStream(f1)); CipherOutputStream out = new CipherOutputStream(new BufferedOutputStream(new FileOutputStream(f2)), cipher); int i; do { i = in.read(); if (i != -1) out.write(i); } while (i != -1); in.close(); out.close(); }
From source file:MainClass.java
public static SecretKey createKeyForAES(int bitLength, SecureRandom random) throws NoSuchAlgorithmException, NoSuchProviderException { KeyGenerator generator = KeyGenerator.getInstance("AES", "BC"); generator.init(128, random);/*ww w.ja v a2s . c o m*/ return generator.generateKey(); }
From source file:Main.java
private static byte[] generateMacSecret() { try {/*from ww w. j a v a 2 s.c om*/ KeyGenerator generator = KeyGenerator.getInstance("HmacSHA1"); return generator.generateKey().getEncoded(); } catch (NoSuchAlgorithmException e) { Log.w("keyutil", e); return null; } }