不应使用具有 ECB 模式的密码

Cipher With ECB Mode Should Not Be Used

我正在尝试将 Cipher 和 RSA 密钥对与 "AndroidKeyStore" 一起使用。在我能找到的所有 Android 文档中,示例显示 Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding") or Cipher.getInstance("RSA/ECB/PKCS1Padding")。两者都在 Android Studio 上提出了相同的警告:

ECB Encryption should not be used

Cipher#getInstance should not be called with ECB as the cipher mode or without setting the cipher mode because the default mode on android is ECB, which is insecure.

显然我不能省略它,或者将模式设置为None,因为默认是ECB。如果 ECB 模式不安全,我应该使用哪种模式?

如果我使用任何其他模式(我知道),我会得到 NoSuchAlgorithmException: No provider found for RSA/{mode}/OAEPWithSHA-256AndMGF1Padding。填充可能是问题所在吗?

无论哪种方式,根据 Android KeyStore System 文档,ECB 模式似乎是它在使用 RSA 时支持的唯一密码块模式。

这看起来像是 Android Studio 用来查找问题的 Android Lint 中的错误。该警告的目的是警告将 ECB 块模式与对称密码(例如 AES)一起使用。但是,对于 RSA,没有必要警告这一点,因为 RSA/ECB/... Cipher accepts/processes 只有一个输入块。

我建议您在 https://code.google.com/p/android/ 中针对 Android Lint 提交错误。

我喜欢这个解释 (from Maarten Bodewes):

"RSA/ECB/PKCS1Padding" actually doesn't implement ECB mode encryption. It should have been called "RSA/None/PKCS1Padding" as it can only be used to encrypt a single block of plaintext (or, indeed a secret key). This is just a naming mistake of Sun/Oracle.

如果 您的 Android 版本包含 BouncyCastle,那么您可以使用 None 而不是 ECB

通过将 "AES/ECB/PKCS5PADDING" 更改为 "AES/CBC/PKCS5PADDING" 修复了这个 lint 安全警告。