AES介紹
AES: 高級加密標準(Advanced Encryption Standard)
作爲新一代的數據集加密標準,匯聚了強安全性、高性能、高效率、易用和靈活等優點,設計有三個密鑰長度(128bit,192bit,256bit),與DES相比,加密強度更高,更安全。
特點
密鑰爲128位時,也就是16byte,加密後的byte數組長度爲:(原文byte數組長度 / 16) +16
解密密鑰不匹配時,java方法會拋出異常。
Android實現
import android.util.Base64;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AESUtil {
// Const string for AES encrypt
private static final String ALGORITHM = "AES";
private static final String ALGORITHM_PADDING = "AES/CBC/PKCS5Padding";
private static final String RAN_TIME_STR = "1234567890123456";
// Use CBC mode, need a iv to enhance the strength of encryption
private static final IvParameterSpec IV_PARAMETER_SPEC = new IvParameterSpec(RAN_TIME_STR.getBytes());
/**
* Do AES encryption
*
* @param key The key for encryption
* @param data Source to be encrypted.
* @return Encrypted bytes
*/
public static byte[] encrypt(String key, byte[] data) throws Exception {
Key k = toKey(key.getBytes());
byte[] raw = k.getEncoded();
SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM_PADDING);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, IV_PARAMETER_SPEC);
return cipher.doFinal(data);
}
/**
* Do AES decryption
*
* @param key The key for decryption
* @param data Source to be decrypted
* @return Decrypted bytes
*/
public static byte[] decrypt(String key, byte[] data) throws Exception {
Key k = toKey(key.getBytes());
byte[] raw = k.getEncoded();
SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM_PADDING);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, IV_PARAMETER_SPEC);
return cipher.doFinal(data);
}
/**
* Constructs a secret key from the given byte array.
*
* @param key The key material of the secret key.
* @return Secret key
*/
private static Key toKey(byte[] key) {
return new SecretKeySpec(key, ALGORITHM);
}
/**
* Change bytes to Hex string
*
* @param bytesData Source bytes
* @return Hex string
*/
public static String bytes2Hex(byte[] bytesData) {
String tmp;
StringBuilder des = new StringBuilder();
for (byte byteData : bytesData) {
tmp = (Integer.toHexString(byteData & 0xFF));
if (tmp.length() == 1) {
des.append("0");
}
des.append(tmp);
}
return des.toString();
}
/**
* Encode a common string to base64 string
*
* @param strSrc Common string to be encoded
* @return Base64 string
*/
public static String base64Encode(String strSrc) {
return Base64.encodeToString(strSrc.getBytes(), Base64.DEFAULT);
}
/**
* Decode a base64 string to common string
*
* @param strSrc Base64 string to be decoded
* @return Common string
*/
public static String base64Decode(String strSrc) {
return new String(Base64.decode(strSrc.getBytes(), Base64.DEFAULT));
}
}