1 3 package org.jgroups.demos; 4 5 import java.io.FileOutputStream ; 6 import java.io.OutputStream ; 7 import java.security.KeyStore ; 8 9 import javax.crypto.KeyGenerator; 10 import javax.crypto.SecretKey; 11 12 31 public class KeyStoreGenerator { 32 33 static String symAlg = "Blowfish"; 34 static int keySize =56; 35 static String keyStoreName = "defaultStore.keystore"; 36 static String storePass = "changeit"; 37 static String alias = "myKey"; 38 39 public static void main(String [] args) 40 { 41 42 int i = 0, j; 43 String arg =null;; 44 boolean specified =false; 45 46 while (i < args.length && args[i].startsWith("-")) { 47 arg = args[i++]; 48 System.out.println("Found arg of " + arg); 49 if (arg.equalsIgnoreCase("--alg")){ 50 if (i<args.length){ 51 symAlg = args[i++]; 52 }else{ 53 System.out.println("No Algorithm supplied using default of "+ symAlg); 54 } 55 } 56 else if (arg.equalsIgnoreCase("--size")){ 57 if (i<args.length){ 58 keySize = Integer.parseInt(args[i++]); 59 }else{ 60 System.out.println("No Size supplied using default of "+keySize); 61 } 62 }else if (arg.equalsIgnoreCase("--storeName")){ 63 64 if (i<args.length){ 65 String temp = args[i++]; 66 keyStoreName = temp; 67 }else{ 68 System.out.println("No keystore supplied using default of "+keyStoreName); 69 } 70 } 71 else if (arg.equalsIgnoreCase("--storePass")){ 72 if (i<args.length){ 73 storePass = args[i++]; 74 }else{ 75 System.out.println("No password supplied using default of "+storePass); 76 } 77 } 78 else if (arg.equalsIgnoreCase("--alias")){ 79 if (i<args.length){ 80 alias = args[i++]; 81 }else{ 82 System.out.println("No alias supplied using default of "+alias); 83 } 84 } 85 } 86 System.out.println("Creating file '" + keyStoreName +"' using Algorithm '"+ 87 symAlg +"' size '"+keySize + "'"); 88 89 OutputStream stream =null; 90 try { 91 stream= new FileOutputStream (keyStoreName); 92 SecretKey key = initSymKey(); 93 KeyStore store = KeyStore.getInstance("JCEKS"); 94 store.load(null,null); 95 store.setKeyEntry(alias,key,storePass.toCharArray(),null); 96 store.store(stream,storePass.toCharArray()); 97 98 } catch (Exception e){ 99 e.printStackTrace(); 100 } 101 finally{ 102 try { 103 stream.close(); 104 } catch (Exception e){ 105 106 } 107 } 108 System.out.println("Finished keystore creation"); 109 } 110 111 public static SecretKey initSymKey() throws Exception 112 { 113 KeyGenerator keyGen = null; 114 116 keyGen = KeyGenerator.getInstance(getAlgorithm(symAlg)); 117 118 keyGen.init(keySize); 119 SecretKey secretKey = keyGen.generateKey(); 120 121 return secretKey; 122 123 } 124 125 private static String getAlgorithm(String s) 126 { 127 int index = s.indexOf("/"); 128 if (index == -1) 129 return s; 130 131 return s.substring(0, index); 132 } 133 } 134 | Popular Tags |