Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android RSA 加解密實踐:填充方式、分段加密與效率對比

編輯:關於 Android 程式設計

前陣子和同事聊到數據安全傳輸,順手把之前用過的 RSA 非對稱加密方案整理成文。

RSA 是什麼

RSA 是最流行的公鑰密碼算法,密鑰長度可變,也是第一個同時支持數據加密與數字簽名的算法。原理步驟:

  1. 隨機選兩個大質數 p、q(p ≠ q),計算 N = pq;
  2. 取一個大於 1 小於 N 的自然數 e,且 e 與 (p-1)(q-1) 互素;
  3. 解方程 d × e ≡ 1 (mod (p-1)(q-1)),求出 d;
  4. 銷毀 p 和 q。

最終 (N, e) 是公鑰,d 是私鑰。發送方用 N 加密,接收方只能用 d 解密。

安全性依賴於大數分解難題,1024 位以下的 N 已被證明不安全。由於全程是大數運算,RSA 即使最快也比 DES 慢一個量級,這也是它最大的短板,因此實務中通常只用它加密少量數據或加密對稱密鑰。

第一步:生成密鑰對

/**
 * 隨機生成 RSA 密鑰對
 *
 * @param keyLength 密鑰長度,範圍 512~2048,一般取 1024
 */
public static KeyPair generateRSAKeyPair(int keyLength) {
    try {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
        kpg.initialize(keyLength);
        return kpg.genKeyPair();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }
}

基礎加解密

公鑰加密:

public static byte[] encryptByPublicKey(byte[] data, byte[] publicKey) throws Exception {
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
    KeyFactory kf = KeyFactory.getInstance(RSA);
    PublicKey keyPublic = kf.generatePublic(keySpec);
    Cipher cp = Cipher.getInstance(ECB_PKCS1_PADDING);
    cp.init(Cipher.ENCRYPT_MODE, keyPublic);
    return cp.doFinal(data);
}

私鑰加密:

public static byte[] encryptByPrivateKey(byte[] data, byte[] privateKey) throws Exception {
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);
    KeyFactory kf = KeyFactory.getInstance(RSA);
    PrivateKey keyPrivate = kf.generatePrivate(keySpec);
    Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
    cipher.init(Cipher.ENCRYPT_MODE, keyPrivate);
    return cipher.doFinal(data);
}

公鑰解密:

public static byte[] decryptByPublicKey(byte[] data, byte[] publicKey) throws Exception {
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
    KeyFactory kf = KeyFactory.getInstance(RSA);
    PublicKey keyPublic = kf.generatePublic(keySpec);
    Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
    cipher.init(Cipher.DECRYPT_MODE, keyPublic);
    return cipher.doFinal(data);
}

私鑰解密:

public static byte[] decryptByPrivateKey(byte[] encrypted, byte[] privateKey) throws Exception {
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);
    KeyFactory kf = KeyFactory.getInstance(RSA);
    PrivateKey keyPrivate = kf.generatePrivate(keySpec);
    Cipher cp = Cipher.getInstance(ECB_PKCS1_PADDING);
    cp.init(Cipher.DECRYPT_MODE, keyPrivate);
    return cp.doFinal(encrypted);
}

相關常量:

public static final String RSA = "RSA";                              // 非對稱加密算法
public static final String ECB_PKCS1_PADDING = "RSA/ECB/PKCS1Padding"; // 加密填充方式
public static final int DEFAULT_KEY_SIZE = 2048;                     // 默認密鑰長度
public static final byte[] DEFAULT_SPLIT = "#PART#".getBytes();      // 分塊分隔標記
// 當前密鑰支持加密的最大字節數
public static final int DEFAULT_BUFFERSIZE = (DEFAULT_KEY_SIZE / 8) - 11;

坑一:填充方式不一致

我以為寫完上面那些就萬事大吉了,結果 Android 端加密的數據服務器死活解不開。原因是 Android 系統的 RSA 默認實現是 RSA/None/NoPadding,而標準 JDK 是 RSA/None/PKCS1Padding。跨端通信時必須顯式指定一致的填充方式,否則必然失敗。

坑二:加密長度限制

接著又撞上 javax.crypto.IllegalBlockSizeException: Data must not be longer than ... bytes。RSA 規定:待加密字節數不能超過 KeySize / 8 - 11,加密後的密文字節數則正好是 KeySize / 8。的解決辦法是分塊加密,塊間用分隔標記拼接,解密時按標記切分。

公鑰分段加密:

public static byte[] encryptByPublicKeyForSpilt(byte[] data, byte[] publicKey) throws Exception {
    int dataLen = data.length;
    if (dataLen <= DEFAULT_BUFFERSIZE) {
        return encryptByPublicKey(data, publicKey);
    }
    List<Byte> allBytes = new ArrayList<Byte>(2048);
    int bufIndex = 0;
    int subDataLoop = 0;
    byte[] buf = new byte[DEFAULT_BUFFERSIZE];
    for (int i = 0; i < dataLen; i++) {
        buf[bufIndex] = data[i];
        if (++bufIndex == DEFAULT_BUFFERSIZE || i == dataLen - 1) {
            subDataLoop++;
            if (subDataLoop != 1) {
                for (byte b : DEFAULT_SPLIT) allBytes.add(b);
            }
            byte[] encryptBytes = encryptByPublicKey(buf, publicKey);
            for (byte b : encryptBytes) allBytes.add(b);
            bufIndex = 0;
            if (i == dataLen - 1) {
                buf = null;
            } else {
                buf = new byte[Math.min(DEFAULT_BUFFERSIZE, dataLen - i - 1)];
            }
        }
    }
    byte[] bytes = new byte[allBytes.size()];
    int i = 0;
    for (Byte b : allBytes) bytes[i++] = b.byteValue();
    return bytes;
}

私鑰分段加密:

public static byte[] encryptByPrivateKeyForSpilt(byte[] data, byte[] privateKey) throws Exception {
    int dataLen = data.length;
    if (dataLen <= DEFAULT_BUFFERSIZE) {
        return encryptByPrivateKey(data, privateKey);
    }
    List<Byte> allBytes = new ArrayList<Byte>(2048);
    int bufIndex = 0;
    int subDataLoop = 0;
    byte[] buf = new byte[DEFAULT_BUFFERSIZE];
    for (int i = 0; i < dataLen; i++) {
        buf[bufIndex] = data[i];
        if (++bufIndex == DEFAULT_BUFFERSIZE || i == dataLen - 1) {
            subDataLoop++;
            if (subDataLoop != 1) {
                for (byte b : DEFAULT_SPLIT) allBytes.add(b);
            }
            byte[] encryptBytes = encryptByPrivateKey(buf, privateKey);
            for (byte b : encryptBytes) allBytes.add(b);
            bufIndex = 0;
            if (i == dataLen - 1) {
                buf = null;
            } else {
                buf = new byte[Math.min(DEFAULT_BUFFERSIZE, dataLen - i - 1)];
            }
        }
    }
    byte[] bytes = new byte[allBytes.size()];
    int i = 0;
    for (Byte b : allBytes) bytes[i++] = b.byteValue();
    return bytes;
}

公鑰分段解密:

public static byte[] decryptByPublicKeyForSpilt(byte[] encrypted, byte[] publicKey) throws Exception {
    int splitLen = DEFAULT_SPLIT.length;
    if (splitLen <= 0) {
        return decryptByPublicKey(encrypted, publicKey);
    }
    int dataLen = encrypted.length;
    List<Byte> allBytes = new ArrayList<Byte>(1024);
    int latestStartIndex = 0;
    for (int i = 0; i < dataLen; i++) {
        byte bt = encrypted[i];
        boolean isMatchSplit = false;
        if (i == dataLen - 1) {
            // 已到末尾,把最後一段單獨解密
            byte[] part = new byte[dataLen - latestStartIndex];
            System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);
            byte[] decryptPart = decryptByPublicKey(part, publicKey);
            for (byte b : decryptPart) allBytes.add(b);
            latestStartIndex = i + splitLen;
            i = latestStartIndex - 1;
        } else if (bt == DEFAULT_SPLIT[0]) {
            if (splitLen > 1) {
                if (i + splitLen < dataLen) {
                    for (int j = 1; j < splitLen; j++) {
                        if (DEFAULT_SPLIT[j] != encrypted[i + j]) break;
                        if (j == splitLen - 1) isMatchSplit = true;
                    }
                }
            } else {
                isMatchSplit = true;
            }
            if (isMatchSplit) {
                byte[] part = new byte[i - latestStartIndex];
                System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);
                byte[] decryptPart = decryptByPublicKey(part, publicKey);
                for (byte b : decryptPart) allBytes.add(b);
                latestStartIndex = i + splitLen;
                i = latestStartIndex - 1;
            }
        }
    }
    byte[] bytes = new byte[allBytes.size()];
    int i = 0;
    for (Byte b : allBytes) bytes[i++] = b.byteValue();
    return bytes;
}

私鑰分段解密:

public static byte[] decryptByPrivateKeyForSpilt(byte[] encrypted, byte[] privateKey) throws Exception {
    int splitLen = DEFAULT_SPLIT.length;
    if (splitLen <= 0) {
        return decryptByPrivateKey(encrypted, privateKey);
    }
    int dataLen = encrypted.length;
    List<Byte> allBytes = new ArrayList<Byte>(1024);
    int latestStartIndex = 0;
    for (int i = 0; i < dataLen; i++) {
        byte bt = encrypted[i];
        boolean isMatchSplit = false;
        if (i == dataLen - 1) {
            byte[] part = new byte[dataLen - latestStartIndex];
            System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);
            byte[] decryptPart = decryptByPrivateKey(part, privateKey);
            for (byte b : decryptPart) allBytes.add(b);
            latestStartIndex = i + splitLen;
            i = latestStartIndex - 1;
        } else if (bt == DEFAULT_SPLIT[0]) {
            if (splitLen > 1) {
                if (i + splitLen < dataLen) {
                    for (int j = 1; j < splitLen; j++) {
                        if (DEFAULT_SPLIT[j] != encrypted[i + j]) break;
                        if (j == splitLen - 1) isMatchSplit = true;
                    }
                }
            } else {
                isMatchSplit = true;
            }
            if (isMatchSplit) {
                byte[] part = new byte[i - latestStartIndex];
                System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);
                byte[] decryptPart = decryptByPrivateKey(part, privateKey);
                for (byte b : decryptPart) allBytes.add(b);
                latestStartIndex = i + splitLen;
                i = latestStartIndex - 1;
            }
        }
    }
    byte[] bytes = new byte[allBytes.size()];
    int i = 0;
    for (Byte b : allBytes) bytes[i++] = b.byteValue();
    return bytes;
}

需要注意,用分隔標記拼接密文存在理論上的碰撞風險,生產環境更穩妥的做法是把每段的長度寫進頭部再逐段讀取。

效率實測

項目裡的方案是客戶端公鑰加密、服務器私鑰解密,理由是效率。我自己寫了段程序驗證一下。

準備 100 條測試數據並序列化:

List<Person> personList = new ArrayList<>();
int testMaxCount = 100;
for (int i = 0; i < testMaxCount; i++) {
    Person person = new Person();
    person.setAge(i);
    person.setName(String.valueOf(i));
    personList.add(person);
}
String jsonData = JsonUtils.objectToJsonForFastJson(personList);
Log.e("MainActivity", "加密前json數據 ---->" + jsonData);
Log.e("MainActivity", "加密前json數據長度 ---->" + jsonData.length());

生成密鑰對:

KeyPair keyPair = RSAUtils.generateRSAKeyPair(RSAUtils.DEFAULT_KEY_SIZE);
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

雙向加解密並計時:

// 公鑰加密
long start = System.currentTimeMillis();
byte[] encryptBytes = RSAUtils.encryptByPublicKeyForSpilt(jsonData.getBytes(), publicKey.getEncoded());
long end = System.currentTimeMillis();
Log.e("MainActivity", "公鑰加密耗時 cost time---->" + (end - start));
String encryStr = Base64Encoder.encode(encryptBytes);
Log.e("MainActivity", "加密後json數據 --1-->" + encryStr);
Log.e("MainActivity", "加密後json數據長度 --1-->" + encryStr.length());

// 私鑰解密
start = System.currentTimeMillis();
byte[] decryptBytes = RSAUtils.decryptByPrivateKeyForSpilt(
        Base64Decoder.decodeToBytes(encryStr), privateKey.getEncoded());
String decryStr = new String(decryptBytes);
end = System.currentTimeMillis();
Log.e("MainActivity", "私鑰解密耗時 cost time---->" + (end - start));
Log.e("MainActivity", "解密後json數據 --1-->" + decryStr);

// 私鑰加密
start = System.currentTimeMillis();
encryptBytes = RSAUtils.encryptByPrivateKeyForSpilt(jsonData.getBytes(), privateKey.getEncoded());
end = System.currentTimeMillis();
Log.e("MainActivity", "私鑰加密耗時 cost time---->" + (end - start));
encryStr = Base64Encoder.encode(encryptBytes);
Log.e("MainActivity", "加密後json數據 --2-->" + encryStr);
Log.e("MainActivity", "加密後json數據長度 --2-->" + encryStr.length());

// 公鑰解密
start = System.currentTimeMillis();
decryptBytes = RSAUtils.decryptByPublicKeyForSpilt(
        Base64Decoder.decodeToBytes(encryStr), publicKey.getEncoded());
decryStr = new String(decryptBytes);
end = System.currentTimeMillis();
Log.e("MainActivity", "公鑰解密耗時 cost time---->" + (end - start));
Log.e("MainActivity", "解密後json數據 --2-->" + decryStr);

運行結果:

對比下來,私鑰的加解密明顯更耗時。因此應該按需求選方案:如果服務端更在意解密效率,讓客戶端用私鑰加密、服務端用公鑰解密會更划算。

另外注意密文體積的變化,Base64 之後大約是原文的 1.5 倍:

最後補一句實踐建議:RSA 本身不適合加密大數據量,主流做法是「RSA 加密 AES 密鑰 + AES 加密業務數據」,既規避了性能與長度限制,也繼承了非對稱加密在密鑰分發上的優勢。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved