import com.gs.utility.io.Transfer;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
/**
* AES算法
*
* @author Guozheng
* @version 0.0.1, 13-10-9, 下午7:59
*/
public final class AES implements Cryptographic {
private Key key;
private static final String KEY_ALGORITHM = "AES";
private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
private int keyLength = 128;
@Override
public byte[] encrypt(byte[] plainText) throws Exception {
return decode(plainText, Cipher.ENCRYPT_MODE);
}
@Override
public byte[] decrypt(byte[] cipherText) throws Exception {
return decode(cipherText, Cipher.DECRYPT_MODE);
}
private byte[] decode(byte[] bytes, int mode) throws Exception {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(mode, this.key);
return cipher.doFinal(bytes);
}
private void createKey(byte[] bytes) throws NoSuchAlgorithmException {
KeyGenerator generator = KeyGenerator.getInstance(KEY_ALGORITHM);
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(bytes);
generator.init(this.keyLength, secureRandom);
this.key = new SecretKeySpec(generator.generateKey().getEncoded(), KEY_ALGORITHM);
}
public void setKeyFile(String path) throws IOException, NoSuchAlgorithmException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Transfer.copy(new File(path), bos);
bos.flush();
bos.close();
createKey(bos.toByteArray());
}
public void setKeyText(String text) throws NoSuchAlgorithmException {
createKey(text.getBytes());
}
public void setKeyBytes(byte[] bytes) throws NoSuchAlgorithmException {
createKey(bytes);
}
public void setKeyLength(int keyLength) {
this.keyLength = keyLength;
}
}
public final class Base64 implements Cryptographic {
/**
* 内部加解密对象
*/
private Cryptographic cryptography;
public byte[] encrypt(byte[] plainText) throws Exception {
if (this.cryptography != null) plainText = this.cryptography.encrypt(plainText);
return org.apache.commons.codec.binary.Base64.encodeBase64(plainText);
}
public byte[] decrypt(byte[] cipherText) throws Exception {
cipherText = org.apache.commons.codec.binary.Base64.decodeBase64(cipherText);
if (this.cryptography != null) cipherText = this.cryptography.decrypt(cipherText);
return cipherText;
}
public void setCryptography(Cryptographic cryptography) {
this.cryptography = cryptography;
}
}
public interface Cryptographic {
/**
* 加密
*
* @param plainText 明文消息
* @return 密文消息
* @throws Exception 加密中出现的异常
*/
public abstract byte[] encrypt(byte[] plainText) throws Exception;
/**
* 解码
*
* @param cipherText 密文消息
* @return 明文消息
* @throws Exception 解码中出现的异常
*/
public abstract byte[] decrypt(byte[] cipherText) throws Exception;
}