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

Android 資料加密之 RSA 加密與分段加解密實作

編輯:關於 Android 程式設計

前言

前陣子和同事聊到資料安全傳輸,想起自己用過的 RSA 非對稱加密,趁機會整理一次。同系列主題:RSA、AES、DES、MD5、Base64 編碼、SHA 安全雜湊演算法。

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 能解開。

RSA 的安全性建立在「大數分解很難」這個假設上。由於運算量龐大,RSA 的運算速度遠慢於 DES 這類對稱演算法,因此實務上通常只用來加密少量資料,或加密對稱金鑰(即混合加密)。另外,1024 位元的 N 已被視為不安全,目前建議至少 2048 位元。

第一步:產生金鑰對

/** 隨機產生 RSA 金鑰對
 *  @param keyLength 金鑰長度,範圍 512~2048,一般取 1024(現建議 2048) */
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,兩邊對不上。跨端實作時,務必明確指定相同的 transformation 字串。

坑二:加密長度受限,必須分段

RSA 一次能加密的位元組數有上限。以 1024 位元金鑰為例,最多只能加密 117 位元組,超過就會丟出 javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytes。

規則是:可加密的明文上限 = 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;
}

私鑰分段解密的實作結構與上面完全相同,只是把 decryptByPublicKey 換成 decryptByPrivateKey,這裡不再重複貼上。

效率實測

專案採用的方案是「客戶端公鑰加密、伺服器私鑰解密」,理由是效率考量。於是自己寫了程式驗證一下。

第一步,準備 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.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", "公鑰加密耗時 ---->" + (end - start));
String encryStr = Base64Encoder.encode(encryptBytes);

start = System.currentTimeMillis();
byte[] decryptBytes = RSAUtils.decryptByPrivateKeyForSpilt(
        Base64Decoder.decodeToBytes(encryStr), privateKey.getEncoded());
end = System.currentTimeMillis();
Log.e("MainActivity", "私鑰解密耗時 ---->" + (end - start));

start = System.currentTimeMillis();
encryptBytes = RSAUtils.encryptByPrivateKeyForSpilt(
        jsonData.getBytes(), privateKey.getEncoded());
end = System.currentTimeMillis();
Log.e("MainActivity", "私鑰加密耗時 ---->" + (end - start));
encryStr = Base64Encoder.encode(encryptBytes);

start = System.currentTimeMillis();
decryptBytes = RSAUtils.decryptByPublicKeyForSpilt(
        Base64Decoder.decodeToBytes(encryStr), publicKey.getEncoded());
end = System.currentTimeMillis();
Log.e("MainActivity", "公鑰解密耗時 ---->" + (end - start));

實測結果顯示私鑰的加解密都明顯較慢。若伺服器端要求解密效率,由客戶端私鑰加密、伺服器公鑰解密會更划算,可作為方案選擇的參考。

加密後的資料量變化如下,大約是加密前的 1.5 倍:

兩個需要正視的設計問題

1. 私鑰絕對不能放在客戶端。用私鑰加密、公鑰解密的做法,等於把「簽名能力」交給了每一台裝置,任何人反編譯 apk 就能取得私鑰並偽造資料。若目的只是傳輸加密,正確做法一律是「客戶端用公鑰加密,伺服器用私鑰解密」;若需要驗證來源,則是「客戶端私鑰簽名、伺服器公鑰驗簽」,兩者用途不可混用。

2. 大資料請走混合加密。RSA 分段的開銷與密文膨脹都不划算,實務做法是每次請求隨機產生一把 AES 金鑰,用 AES 加密本文,再用 RSA 公鑰加密這把 AES 金鑰,兩者一起送出。這也是 HTTPS 的基礎思路。

以上就是本文全部內容,希望對你的學習有所幫助。

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