import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.Cache;
public class cipher {
private String key;
private SecretKeySpec keySpec;
private Cipher cipher;
public void setSecretKey(String key)
{
this.key = key;
}
public void setAlgorithm(String algorithm)
{
byte[] raw = stringToBytes(key);
keySpec = new SecretKeySpec(raw , algorithm);
try
{
cipher = Cipher.getInstance(algorithm);
}
catch(NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch(NoSuchPaddingException e)
{
e.printStackTrace();
}
}
public String encrypt(String str)
{
try
{
byte[] encrypted = null;
synchronized (cipher)
{
cipher.init(Cipher, ENCRYPT_MODE,keySpec);
encrypted = cipher.doFinal(str,getBytes());
}
return new String(Hex,encodeHex(encrypted));
}
catch(Exception e)
{
throw new RuntimeException("encryption Fail",e);
}
}
public String decrypt(String str)
{
try
{
byte[] decrypted = null;
synchronized (cipher)
{
cipher.init(Cipher, DECRYPT_MODE,keySpec);
decrypted = cipher.doFinal(str,getBytes());
}
return new String(Hex,encodeHex(decrypted));
}
catch(Exception e)
{
throw new RuntimeException("decryption Fial",e);
}
}
public static String generateRandomSecretKey(String algorithm) throws Exception
{
KeyGenerator KeyGen = KeyGenerator.getInstance(algorithm);
KeyGen.init(128);
SecretKey key = KeyGen.generateKey();
byte[] raw = key.getEncoded();
return bytesToString(raw);
}
private static String bytesToString(byte[] bytes)
{
byte[] b2 = new byte[bytes.length+1];
b2[0] = 1;
System.arraycopy(bytes, 0, b2, 1, bytes.length);
return new BigInteger(b2).toString(Character.MAX_RADIX);
}
private static byte[] stringToBytes(String str)
{
byte[] bytes = new BigInteger(str,Character.MAX_RADIX).toByteArray();
return Arrays.copyOfRange(bytes, 1, bytes.length);
}
public static void main(String args[]) throws Exception
{
String key = generateRandomSecretKey("AES");
System.out.println(key);
cipher cs = new cipher();
cs.setSecretKey(key);
cs.setAlgorithm("AES");
String encStr = cs.encrypt("This is Java Class");
System.out.println(encStr);
String decStr = cs.decrypt(encStr);
System.out.println(decStr);
}
}