AES 設計時,應該確定好雙方的 IV 和 Key 值及值用的 Mode 、Key Size 、 Output Base64 或者 HEX … 等問題。
雙方在做的時候,也能給個正確的範例。比方說,到此網頁試試
https://www.devglan.com/online-tools/aes-encryption-decryption
//欲進行加密的文字字串
//Iv、Key 需看您的 Key Size 去設定長度,此範例是 128
//Key 最好的寫法是用「動態」,此方式為靜態,比較危險
private final static String IvAES = "kuochinghsiaokuo" ;//16字長度
private final static String KeyAES = "kuochinghsiaokuo";//16字長度
/**
* AES加密 , 使用方式 AES.EncryptAES("pp@gmail.com")
* @param text
* @return 回傳 AES/CBC/HEX 字串
*/
public static String EncryptAES(String text)
{
try
{
//轉成 Byte
byte[] bb = text.getBytes();
byte[] iv = IvAES.getBytes("UTF-8");
byte[] key = KeyAES.getBytes("UTF-8");
AlgorithmParameterSpec mAlgorithmParameterSpec = new IvParameterSpec(iv);
SecretKeySpec mSecretKeySpec = new SecretKeySpec(key, "AES");
Cipher mCipher = null;
mCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
mCipher.init(Cipher.ENCRYPT_MODE,
mSecretKeySpec,
mAlgorithmParameterSpec);
// byte 轉成 Hex
String byte2HexStr = AES.parseByte2HexStr(mCipher.doFinal(bb));
return byte2HexStr;
}
catch(Exception ex)
{
return "";
}
}
// byte 轉成 Hex
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**
* AES解密 , 使用方式 AES.DecryptAES("BB667399AD93E6771D4DB1852DC65953")
* @param text
* @return 回傳 加密前字串
*/
public static String DecryptAES(String text)
{
try
{
// Hex 轉成 byte
byte[] tobyte = AES.parseHexStr2Byte(text);
byte[] iv = IvAES.getBytes("UTF-8");
byte[] key = KeyAES.getBytes("UTF-8");
AlgorithmParameterSpec mAlgorithmParameterSpec = new IvParameterSpec(iv);
SecretKeySpec mSecretKeySpec = new SecretKeySpec(key, "AES");
Cipher mCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
mCipher.init(Cipher.DECRYPT_MODE,
mSecretKeySpec,
mAlgorithmParameterSpec);
//轉成正常的字
String byte2string = new String(mCipher.doFinal(tobyte), StandardCharsets.UTF_8);
return byte2string;
}
catch(Exception ex)
{
return "";
}
}
// Hex 轉成 byte
public static byte[] parseHexStr2Byte(String hexString) {
char[] hex = hexString.toCharArray();
int length = hex.length / 2;
byte[] rawData = new byte[length];
for (int i = 0; i < length; i++) {
int high = Character.digit(hex[i * 2], 16);
int low = Character.digit(hex[i * 2 + 1], 16);
int value = (high << 4) | low;
if (value > 127)
value -= 256;
rawData [i] = (byte) value;
}
return rawData ;
}
Learn More →
待補
Android
Java
AES
CBC
Hex
Base64
Encrypt
Decrypt
:::info 官網預設 minifyEnabled = false、shrinkResources = false 所以,寫程式的時候,也請把 debug 打開吧!把 minifyEnabled 改成 true 、 shrinkResources 改成 true ::: buildTypes { debug{ // Enables code shrinking, obfuscation, and optimization for only // your project's release build type.
Jan 20, 2021Android 6 ~ 9 :::danger 第一次訊問會出現 :::  :::danger 第二之後訊問會出現,多了「不要再詢問」的選項 此時有兩種狀況:
Jan 20, 2021or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up