import java.io.*;
import javax.crypto.*;
import java.security.*;
public class AESHelper
{
private BufferedReader in=null;
private PrintStream out=null;
private Cipher encryptCipher=null;
private Cipher decryptCipher=null;
private SecretKey secretKey=null;
public AESHelper(BufferedReader in, PrintStream out, SecretKey secretKey) { this.in=in; this.out=out; this.secretKey=secretKey; }
public void initCipher() throws Exception
{
(encryptCipher=Cipher.getInstance("AES")).init(Cipher.ENCRYPT_MODE, secretKey);
(decryptCipher=Cipher.getInstance("AES")).init(Cipher.DECRYPT_MODE, secretKey);
}
public static SecretKey generateKey() throws Exception
{
KeyGenerator keyGenerator=KeyGenerator.getInstance("AES");
keyGenerator.init(new SecureRandom());
return keyGenerator.generateKey();
}
public void sendMessage(String msg) throws Exception
{
out.println(ToolKit.byteArrayToHexString(crypt(msg.getBytes(), encryptCipher)));
}
public String receiveMessage() throws Exception
{
String line="";
while((line=in.readLine())!=null)
{
if(!line.equals(""))
break;
}
return new String(crypt(ToolKit.hexStringToByteArray(line), decryptCipher));
}
private byte[] crypt(byte[] dataInput, Cipher cipher) throws Exception
{
ByteArrayInputStream bais=new ByteArrayInputStream(dataInput);
ByteArrayOutputStream baos=new ByteArrayOutputStream();
int blockSize=cipher.getBlockSize();
int outputSize=cipher.getOutputSize(blockSize);
byte[] input=new byte[blockSize];
byte[] output=new byte[outputSize];
int readBytes=0;
boolean finish=false;
while(!finish)
{
readBytes=bais.read(input);
if(readBytes==blockSize)
{
int outputLength=cipher.update(input, 0, blockSize, output);
baos.write(output, 0, outputLength);
}
else
finish=true;
}
if(readBytes>0)
output=cipher.doFinal(input, 0, readBytes);
else
output=cipher.doFinal();
baos.write(output);
return (baos.toByteArray());
}
}
class ToolKit
{
public static String byteArrayToHexString(byte[] input)
{
StringBuffer sb=new StringBuffer(input.length*2);
for(int i=0; i<input.length; i++)
{
int v=input[i]&0xFF;
if(v<16)
sb.append("0");
sb.append(Integer.toHexString(v));
}
return sb.toString();
}
public static byte[] hexStringToByteArray(String input)
{
byte[] ret=new byte[input.length()/2];
for(int i=0; i<ret.length; i++)
{
int index=i*2;
int v=Integer.parseInt(input.substring(index, index+2), 16);
ret[i]=(byte)v;
}
return ret;
}
}