Sunday, December 30, 2012

Encryption.java

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

//use apache common-codec instead of sun.misc.BASE64...
import org.apache.commons.codec.binary.Base64;

public class Encryption {

public static final String ALGORITHM = "AES";

public static void main(String[] args) {
long start = System.currentTimeMillis();
String cipherText = encrypt("934617", "xxmh");
System.out.println(cipherText);
String plainText = decrypt(cipherText, "xxmh");
System.out.println(plainText);
long end = System.currentTimeMillis();
System.out.println( (end-start) );
}

public static String encrypt(String content, String password) {
try {
SecretKeySpec key = getKey(password);
Cipher cipher = Cipher.getInstance(ALGORITHM);
byte[] byteContent = content.getBytes("UTF-8");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] result = cipher.doFinal(byteContent);
return Base64.encodeBase64String(result);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

public static String decrypt(String content, String password) {
try {
SecretKeySpec key = getKey(password);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] result = cipher.doFinal(Base64.decodeBase64(content));
return new String(result, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

private static SecretKeySpec getKey(String password)
throws NoSuchAlgorithmException {
KeyGenerator kgen = KeyGenerator.getInstance(ALGORITHM);
kgen.init(256, new SecureRandom(password.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, ALGORITHM);
return key;
}

}

No comments:

Post a Comment