我想从我的应用程序邮寄加密的日志文件。由于日志可能更大,我使用 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 被认为更新/更安全)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句