Android 使用 AES 和 RSA 进行日志加密

Android log encryption using AES and RSA

我想从我的应用程序邮寄加密的日志文件。由于日志可以更大,我使用 AES 加密数据并使用 RSA 加密密钥。由于解密日志需要 AES 密钥,因此我将加密密钥和日志发送到同一个文件中。

问题 1:这是正确的做法吗?如果不是,最好的方法是什么 scenario.Below 是相同的代码。

 public static String encrypt(String data) {
    StringBuilder encryptedData = new StringBuilder();
    try {
        // Generate AES key.
        KeyGenerator generator = KeyGenerator.getInstance("AES");
        // The AES key size in number of bits.
        generator.init(256);
        SecretKey secKey = generator.generateKey();

        // Initialize AES Cipher, IV and encrypt string.
        Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        aesCipher.init(Cipher.ENCRYPT_MODE, secKey, new IvParameterSpec(new byte[16]));
        byte[] byteCipherText = aesCipher.doFinal(data.getBytes());
        String encryptedText = Base64.encodeToString(byteCipherText, Base64.DEFAULT);

        // Initialize RSA Cipher and generate public key.
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(Base64.decode(PUBLIC_KEY, Base64.DEFAULT));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey puKey = keyFactory.generatePublic(publicSpec);
        cipher.init(Cipher.PUBLIC_KEY, puKey);

        // Encrypt key and text.
        byte[] encryptedKey = cipher.doFinal(secKey.getEncoded());
        String aesKey = Base64.encodeToString(encryptedKey, Base64.DEFAULT);
        encryptedData.append(aesKey);
        encryptedData.append(encryptedText);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return encryptedData.toString();
}

Since the AES key is required to decrypt the log, I am sending the encrypted key and logs in the same file.

Question 1: Is this right approach ? If not what is the best approach to follow in this scenario.Below is the code for the same.

该方法是正确的,我缺少的是身份验证(HMAC、GCM 等)。

有一些标准如何将加密密钥、内容和身份验证捆绑在一起(例如 CMS、PKCS7、OpenPGP 等),但是如果它用于您自己的应用程序,您可以按照自己的方式进行(不要为标准而烦恼)。

If you want to use RSA use RSA-KEM

好吧,使用 RSA KEM 跳过填充可能会节省一些性能,但如果对您来说可行,我会尝试一下。使用不同的 public 密钥加密相同的密钥 material 时也会出现问题。

我会保持简单 - 只需使用正确填充的 RSA 加密。

我建议使用 OAEP 填充 RSA/ECB/OAEPWithSHA-256AndMGF1Padding 而不是 PKCS1Padding(OAEP 被认为 newer/safer)