主要问题是您使用的密码没有完整性,并且使用了硬编码的加密密钥。如果使用“ 查找安全性错误”来分析源,则会收到CIPHER_INTEGRITY和HARD_CODE_KEY警告:
The cipher does not provide data integrity [com.lloyds.keystorage.AESCrypt] At AESCrypt.java:[line 25] CIPHER_INTEGRITYThe cipher does not provide data integrity [com.lloyds.keystorage.AESCrypt] At AESCrypt.java:[line 15] CIPHER_INTEGRITYHard pred cryptographic key found [com.lloyds.keystorage.AESCrypt] At AESCrypt.java:[line 35] HARD_CODE_KEY
解决方案是使用包含基于哈希的消息认证码(HMAC)的密码来对数据进行签名:
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");并将密钥存储在单独的配置文件或密钥库中。
下面是经过完全重构的整个类:
import android.util.base64import static java.nio.charset.StandardCharsets.UTF_8;import java.security.Key;import javax.crypto.Cipher;import javax.crypto.spec.SecretKeySpec;public class AESCrypt { private static final String TRANSFORMATION = "AES/GCM/NoPadding"; public static String encrypt(String value) throws Exception { Key key = generateKey(); Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] encryptedBytevalue = cipher.doFinal(value.getBytes(UTF_8)); return base64.enpreToString(encryptedBytevalue, base64.DEFAULT); } public static String decrypt(String value) throws Exception { Key key = generateKey(); Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.DECRYPT_MODE, key); byte[] decryptedValue64 = base64.depre(value, base64.DEFAULT); byte[] decryptedBytevalue = cipher.doFinal(decryptedValue64); return new String(decryptedBytevalue, UTF_8); } private static Key generateKey() { return new SecretKeySpec(Configuration.getKey().getBytes(UTF_8), TRANSFORMATION); }}


