【发布时间】:2020-02-11 19:10:31
【问题描述】:
我想从我的应用程序中邮寄加密的日志文件。由于日志可以更大,我使用 AES 加密数据并使用 RSA 加密密钥。由于解密日志需要 AES 密钥,因此我将加密密钥和日志发送到同一个文件中。
问题 1:这是正确的方法吗?如果不是这种情况下最好的方法是什么。下面是相同的代码。
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();
}
【问题讨论】:
-
如果您想使用 RSA,请使用 RSA-KEM。
-
@kelalaka 使用 RSA-KEM 有什么好处?
-
专为Key encapsulation Mechanism设计。无需填充。
-
@kelalaka:由于 Android API 不支持 KEM,OP 必须自己实现它。结果可能不如使用已经支持的东西(如 RSA OAEP)安全。
-
@JamesKPolk 不是 Android API,但 Bouncy Castle 有它。此外,在 RSA 密钥生成之后,所有人都需要一个好的随机源和一个 KDF。不像 PKCS#1 v1.5 填充或 OAEP 那样复杂。 OAEP 实际上应该使用 xof 而不是 MFG 进行更新。
标签: android encryption aes rsa