java隐藏的SharedReference,BadPaddingException:填充块已损坏
以下代码工作正常,但在三星SM-G950F、Android OS 8.0.0上崩溃:
private String encrypt(String value) {
try {
final byte[] bytes = value != null ? value.getBytes(UTF8) : new byte[0];
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(SEKRIT));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID).getBytes(UTF8), 20));
return new String(Base64.encode(pbeCipher.doFinal(bytes), Base64.NO_WRAP), UTF8);
} catch (Exception e) {
return value;
}
}
private String decrypt(String value) {
try {
final byte[] bytes = value != null ? Base64.decode(value, Base64.DEFAULT) : new byte[0];
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(SEKRIT));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID).getBytes(UTF8), 20));
return new String(pbeCipher.doFinal(bytes), UTF8);
} catch (Exception e) {
return value;
}
}
以下是完整的错误消息:
Caused by java.lang.RuntimeException: javax.crypto.BadPaddingException: pad block corrupted
at com.edaf.utils.ObscuredSharedPreferences.decrypt(SourceFile:185)
at com.edaf.utils.ObscuredSharedPreferences.getString(SourceFile:134)
at com.edaf.utils.Utils.getFromGlobals(SourceFile:145)
我更改了崩溃时的返回值,但我确信这不会有帮助
# 1 楼答案
如果在一台设备上执行加密,而在另一台设备上执行解密,则该段代码设计为失败。如果} 构造函数的
Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID)
返回不同的字符串,那么^{salt
参数将不同一旦salt不同,那么将根据密码计算出不同的密钥,您的解密很可能会失败,并出现与填充相关的异常。salt被用来创建一个不同的值,即使密码是相同的(但仅使用ID是相当愚蠢的,因为使用相同的ID将导致相同的密码,即使在不同的应用程序中)
如果解密没有失败,那么顺便说一句,你会得到一个垃圾明文
问题代码中有无数问题,例如使用单个DES和20次迭代计数以及未经验证的加密。我可以发表一篇长达一页的评论,但我建议你们读一本关于现代加密技术的书,并尽快修改你们的协议