編輯:關於 Android 程式設計
前言
資料加密是一門歷史悠久的技術:以加密算法與金鑰把明文轉為密文,收端再以解密算法與金鑰還原。它的核心是密碼學,至今仍是保護資訊最可靠的手段之一。
專案裡要用 Socket 傳檔案,且傳輸前必須加密。實現過程踩了不少坑,這篇把走過的路與結論一次整理出來。
// 秘鑰算法
private static final String KEY_ALGORITHM = "DES";
// 加密算法:algorithm/mode/padding
private static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5Padding";
// 秘鑰(DES 長度必須是 8 位)
private static final String KEY = "12345678";
public static void main(String args[]) {
String data = "加密解密";
KLog.d("加密數據:" + data);
byte[] encryptData = encrypt(data.getBytes());
KLog.d("加密後的數據:" + new String(encryptData));
byte[] decryptData = decrypt(encryptData);
KLog.d("解密後的數據:" + new String(decryptData));
}
public static byte[] encrypt(byte[] data) {
SecretKey secretKey = new SecretKeySpec(KEY.getBytes(), KEY_ALGORITHM);
try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] result = cipher.doFinal(data);
return Base64.getEncoder().encode(result);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static byte[] decrypt(byte[] data) {
byte[] resultBase64 = Base64.getDecoder().decode(data);
SecretKey secretKey = new SecretKeySpec(KEY.getBytes(), KEY_ALGORITHM);
try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return cipher.doFinal(resultBase64);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
輸出:
加密數據:加密解密
加密後的數據:rt6XE06pElmLZMaVxrbfCQ==
解密後的數據:加密解密
用戶端:
Socket socket = new Socket(ApiConstants.HOST, ApiConstants.PORT);
OutputStream outStream = socket.getOutputStream();
InputStream inStream = socket.getInputStream();
RandomAccessFile fileOutStream = new RandomAccessFile(file, "r");
fileOutStream.seek(0);
byte[] buffer = new byte[1024];
int len = -1;
while (((len = fileOutStream.read(buffer)) != -1)) {
outStream.write(buffer, 0, len);
}
fileOutStream.close();
outStream.close();
inStream.close();
socket.close();
伺服器端:
Socket socket = server.accept();
InputStream inStream = socket.getInputStream();
OutputStream outStream = socket.getOutputStream();
outStream.write(response.getBytes("UTF-8"));
RandomAccessFile fileOutStream = new RandomAccessFile(file, "rwd");
fileOutStream.seek(0);
byte[] buffer = new byte[1024];
int len;
while ((len = inStream.read(buffer)) != -1) {
// 從位元組輸入流讀資料寫入檔案
fileOutStream.write(buffer, 0, len);
}
fileOutStream.close();
inStream.close();
outStream.close();
socket.close();
用戶端:
while (((len = fileOutStream.read(buffer)) != -1)) {
outStream.write(DesUtil.encrypt(buffer), 0, len); // 對位元組陣列加密
}
伺服器端:
while ((len = inStream.read(buffer)) != -1) {
fileOutStream.write(DesUtil.decrypt(buffer), 0, len); // 對位元組陣列解密
}
結果伺服器解密時拋出:
javax.crypto.BadPaddingException: pad block corrupted
推測原因是加密過程會對資料做填充處理,而 IO 流傳輸中一旦分塊邊界對不上,解密自然失敗。更根本的問題在於:加密後的位元組在 UTF-8 等碼表上往往找不到對應字元,隨便轉成字串再轉回位元組,長度就會改變,資料已經不安全了。
接著嘗試改用 NoPadding 填充模式,雖然能解開,但實測 .txt 這類檔案可以正常顯示,.apk 卻會出現解析失敗——顯然行不通。
用 Base64 對位元組編碼,任何位元組都能映射成對應字元且可完整還原,因此轉換是安全的(轉 16 進位字串同理)。但用戶端讀的是位元組流,得先轉字符流;伺服器收到後又要轉回位元組再寫檔。實測字符流本身能成功解密,然而「檔案 ↔ 字符流」的轉換過程繁瑣,寫作與讀取一來一回很容易出錯。
實測發現只有當 CipherOutputStream 被 close 之後,CipherInputStream 才會收到資料。對串流式傳輸而言這顯然不可接受,只能放棄。
在 Android 上用 SSLSocket 稍嫌繁瑣:用戶端與伺服器都要準備金鑰與憑證,且 Android 端憑證必須是 bks 格式(Java 端用 jks)。JDK 的 keytool 只能產生 jks,要 bks 就得下載 BouncyCastle 庫。
一切就緒後,在 Android 6.0 以上還會遇到:
javax.net.ssl.SSLHandshakeException: Handshake failed
原因是 SSLSocket 的簽名演算法預設為 DSA,而 Android 6.0(API 23)之後 KeyStore 有變動,不再支援 DSA,但仍支援 ECDSA。也就是說得把 DSA 改成 ECDSA……坑越挖越深,於是決定換個思路。
既然「邊傳邊加解密」不好使,那就把順序拆開:傳之前先把檔案加密成一個新檔案,傳完之後伺服器再解密。實作如下:
public class FileDesUtil {
// 秘鑰算法
private static final String KEY_ALGORITHM = "DES";
// 加密算法:algorithm/mode/padding
private static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5Padding";
// DES 秘鑰長度必須是 8 位或以上
private static final byte[] KEY = {56, 57, 58, 59, 60, 61, 62, 63};
/**
* 加密檔案並保存到指定目錄
*
* @param fromFilePath 待加密檔案,如 c:/test/待加密文件.txt
* @param toFilePath 加密後存放路徑,如 c:/加密後文件.txt
*/
public static void encrypt(String fromFilePath, String toFilePath) {
KLog.i("encrypting...");
File fromFile = new File(fromFilePath);
if (!fromFile.exists()) {
KLog.e("to be encrypt file no exist!");
return;
}
File toFile = getFile(toFilePath);
SecretKey secretKey = new SecretKeySpec(KEY, KEY_ALGORITHM);
InputStream is = null;
OutputStream out = null;
CipherInputStream cis = null;
try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
is = new FileInputStream(fromFile);
out = new FileOutputStream(toFile);
cis = new CipherInputStream(is, cipher);
byte[] buffer = new byte[1024];
int r;
while ((r = cis.read(buffer)) > 0) {
out.write(buffer, 0, r);
}
} catch (Exception e) {
KLog.e(e.toString());
} finally {
closeQuietly(cis);
closeQuietly(is);
closeQuietly(out);
}
KLog.i("encrypt completed");
}
@NonNull
private static File getFile(String filePath) {
File fromFile = new File(filePath);
if (!fromFile.getParentFile().exists()) {
fromFile.getParentFile().mkdirs();
}
return fromFile;
}
/**
* 解密檔案並保存到指定目錄
*
* @param fromFilePath 已加密檔案,如 c:/加密後文件.txt
* @param toFilePath 解密後存放路徑,如 c:/test/解密後文件.txt
*/
public static void decrypt(String fromFilePath, String toFilePath) {
KLog.i("decrypting...");
File fromFile = new File(fromFilePath);
if (!fromFile.exists()) {
KLog.e("to be decrypt file no exist!");
return;
}
File toFile = getFile(toFilePath);
SecretKey secretKey = new SecretKeySpec(KEY, KEY_ALGORITHM);
InputStream is = null;
OutputStream out = null;
CipherOutputStream cos = null;
try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
is = new FileInputStream(fromFile);
out = new FileOutputStream(toFile);
cos = new CipherOutputStream(out, cipher);
byte[] buffer = new byte[1024];
int r;
while ((r = is.read(buffer)) >= 0) {
cos.write(buffer, 0, r);
}
} catch (Exception e) {
KLog.e(e.toString());
} finally {
closeQuietly(cos);
closeQuietly(out);
closeQuietly(is);
}
KLog.i("decrypt completed");
}
}
這個方案繞開了前面所有問題,成功實現了以 Socket 加密傳輸檔案。
對任何技術而言,理解底層原理都是必要的,否則遇到問題時很容易一頭霧水、不知從何查起。回頭看這五個方案,真正卡住的四個方案其實都敗在同一件事上:DES/ECB/PKCS5Padding 是「區塊加密 + 填充」的設計,它天生不適合被任意切塊串流處理。
最後還是要提醒一句安全面的取捨:DES 的 56 位金鑰在今日已不敷使用,且 ECB 模式會讓相同明文產生相同密文,容易洩漏結構。若這個元件要在新專案中沿用,建議至少升級為 AES-GCM(帶認證的串流友善模式),並把金鑰管理交給 Keystore,而不是硬編在程式碼裡。
Android 兩數相乘範例:Intent 傳值、跨頁跳轉與 Options Menu 一次學會
開發環境:Android 4.1 這個看起來很單純的計算機,其實包辦了 Android 入門階段最該練會的三件事:Intent 帶值跳頁、跨 Activity 取回資料
一分鐘上手:用 Logcat 除錯 Android 程式的完整步驟
Logcat 是 Android 開發中最實用的除錯工具之一,看似簡單,但每隔一段時間沒用,總會手忙腳亂地忘記怎麼設定。這裡就把 Logcat 的使用步驟完整記錄下來,以
動手寫一個 Android Studio 插件:從零開始的完整教學
一、前言 在日常使用 Android Studio 的過程中,我們或多或少都會借助一些外掛來提升開發效率,讓寫程式這件事變得更輕鬆。舉幾個常見的例子: https://g
Android Permission權限與安全機制解析(下)
Android 6.0權限全面詳細分析和解決方案 Marshmallow版本的權限變更 Android的權限系統一直是最重要的安全概念之一,但這些權限過去只在安裝時被詢問