[英]Java Encryption with AES-RSA works in Eclipse but not in Android Studio
[英]Android log encryption using AES and RSA
我想从我的应用程序中邮寄加密的日志文件。 由于日志可以更大,我使用 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();
}
由于解密日志需要 AES 密钥,因此我将加密密钥和日志发送到同一个文件中。
问题1:这是正确的方法吗? 如果不是这种情况下最好的方法是什么。下面是相同的代码。
该方法是正确的,我缺少的是身份验证(HMAC,GCM,...)。
有一些标准如何将加密的密钥、内容和身份验证捆绑在一起(例如CMS 、PKCS7、OpenPGP、..),但是如果它用于您自己的应用程序,您可以按照自己的方式进行(不要打扰标准)。
如果您想使用 RSA,请使用 RSA-KEM
好吧,使用 RSA KEM 可以节省一些跳过填充的性能,但如果它对你可行,我会尝试。 使用不同的公钥加密相同的密钥材料时也会出现问题。
我会保持简单 - 只需使用正确填充的 RSA 加密。
我建议使用 OAEP 填充RSA/ECB/OAEPWithSHA-256AndMGF1Padding
而不是 PKCS1Padding(OAEP 被认为更新/更安全)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.