某次專案需要把 Android 客戶端的一些 SQL 敘述加密後再傳輸,我選了 DES。結果一測就遇到經典錯誤:
javax.crypto.BadPaddingException: Given final block not properly padded
偶爾還會直接跑出亂碼。查了資料,方向通常是兩個:金鑰不對,或編碼方式不同。檢查之後發現金鑰邏輯沒錯,問題出在建立 Key 時必須先把使用者給的字串規則轉成固定 8 位元組的陣列——DES 的金鑰長度是固定的 8 bytes,不足要補 0,超出要截斷。少了這步,Android 與桌面 Java 的行為就會不一致。
package com.spring.sky.util;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.spec.SecretKeySpec;
/**
* DES 檔案加密 & 解密
* 可實現 Android 與 Windows 之間的檔案互通
*/
public class FileDES {
/** 加解密的 key */
private Key mKey;
/** 解密的 Cipher */
private Cipher mDecryptCipher;
/** 加密的 Cipher */
private Cipher mEncryptCipher;
public FileDES(String key) throws Exception
{
initKey(key);
initCipher();
}
/**
* 建立一個加解密的 key
*/
public void initKey(String keyRule) {
byte[] keyByte = keyRule.getBytes();
// 建立一個空的八位陣列,預設為 0
byte[] byteTemp = new byte[8];
// 將使用者指定的規則轉成八位陣列
for (int i = 0; i < byteTemp.length && i < keyByte.length; i++) {
byteTemp[i] = keyByte[i];
}
mKey = new SecretKeySpec(byteTemp, "DES");
}
/**
* 初始化加解密 Cipher
*/
private void initCipher() throws Exception
{
mEncryptCipher = Cipher.getInstance("DES");
mEncryptCipher.init(Cipher.ENCRYPT_MODE, mKey);
mDecryptCipher = Cipher.getInstance("DES");
mDecryptCipher.init(Cipher.DECRYPT_MODE, mKey);
}
/**
* 加密檔案(以串流輸入)
* @param in 原始資料
* @param savePath 加密後的存放位置
*/
public void doEncryptFile(InputStream in, String savePath)
{
if (in == null)
{
System.out.println("inputstream is null");
return;
}
try {
CipherInputStream cin = new CipherInputStream(in, mEncryptCipher);
OutputStream os = new FileOutputStream(savePath);
byte[] bytes = new byte[1024];
int len = -1;
while ((len = cin.read(bytes)) > 0)
{
os.write(bytes, 0, len);
os.flush();
}
os.close();
cin.close();
in.close();
System.out.println("加密成功");
} catch (Exception e) {
System.out.println("加密失敗");
e.printStackTrace();
}
}
/**
* 加密檔案(以路徑輸入)
*/
public void doEncryptFile(String filePath, String savePath)
throws FileNotFoundException
{
doEncryptFile(new FileInputStream(filePath), savePath);
}
/**
* 解密檔案(以串流輸入)
*/
public void doDecryptFile(InputStream in)
{
if (in == null)
{
System.out.println("inputstream is null");
return;
}
try {
CipherInputStream cin = new CipherInputStream(in, mDecryptCipher);
BufferedReader reader =
new BufferedReader(new InputStreamReader(cin));
String line = null;
while ((line = reader.readLine()) != null)
{
System.out.println(line);
}
reader.close();
cin.close();
in.close();
System.out.println("解密成功");
} catch (Exception e) {
System.out.println("解密失敗");
e.printStackTrace();
}
}
/**
* 解密檔案(以路徑輸入)
*/
public void doDecryptFile(String filePath) throws Exception
{
doDecryptFile(new FileInputStream(filePath));
}
public static void main(String[] args) throws Exception {
FileDES fileDES = new FileDES("spring.sky");
fileDES.doEncryptFile("d:/a.txt", "d:/b"); // 加密
fileDES.doDecryptFile("d:/b"); // 解密
}
}
這份程式我分別在 Android 1.6 與桌面 Java 上實測通過,雙向都能正確還原,只要依需求再包一層即可。
AES/CBC/PKCS5Padding 或 GCM),並把金鑰交給 Keystore 管理。keyRule.getBytes("UTF-8"),否則跨平台可能產生不同結果,這正是「同一份金鑰在兩邊對不上」的常見原因。