/* * Copyright (C) Sergey P. Derevyago, 2005. * * Permission to copy, use, modify, sell and distribute this software is granted * provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied warranty, and * with no claim as to its suitability for any purpose. * */ import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.Random; public class KeyGen { public static void main(String[] args) throws Exception { if (args.length!=1) { System.out.println("Invalid args. key_file is missing"); return; } if ((new File(args[0])).exists()) { System.out.println(args[0]+" file already exists"); return; } FileOutputStream fout=new FileOutputStream(args[0]); BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); int bitKeyLen=readInt(in, "Enter key length in bits", 128, 512); int byteKeyLen=(bitKeyLen+7)/8; int maxVal=readInt(in, "Enter maximum value", 2, 65536); BigInteger biMaxVal=BigInteger.valueOf(maxVal); int n=1; for (BigInteger a=biMaxVal, end=BigInteger.ONE.shiftLeft(bitKeyLen-1); a.compareTo(end)<0; a=a.multiply(biMaxVal)) n++; System.out.println(); BigInteger keyVal=BigInteger.ZERO; for (int i=1; i<=n; i++) { int val=readInt(in, "["+i+" of "+n+"] enter value", 1, maxVal); keyVal=keyVal.multiply(biMaxVal).add(BigInteger.valueOf(val-1)); } keyVal=keyVal.multiply(BigInteger.valueOf(2)).add(BigInteger.ONE); System.out.println(); byte[] bytes=keyVal.toByteArray(), key=new byte[byteKeyLen]; if (bytes.length>(8-bitKeyLen%8) : 0xff; key[0]&=msbMask; if (key[0]==0) { for (Random rnd=new Random(); key[0]==0; ) key[0]=(byte)(rnd.nextInt(256)&msbMask); System.out.println("The most significant byte was changed from 0 to "+ Integer.toHexString(key[0]&0xff)); } fout.write(key); fout.close(); System.out.println(args[0]+" file created!"); } public static int readInt(BufferedReader in, String msg, int minVal, int maxVal) throws Exception { for (;;) { System.out.print(msg+" ("+minVal+"-"+maxVal+"): "); try { int val=Integer.parseInt(in.readLine()); if (val>=minVal && val<=maxVal) return val; } catch (NumberFormatException ignore) {} System.out.println(" Error! Reenter value from "+minVal+" to "+maxVal); } } }