晦涩的SharedPreference,BadPaddingException:垫块在android中损坏

时间:2018-07-11 06:36:22

标签: android

以下代码运行正常,但在少数设备(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;
  }
}

错误消息:

  

由java.lang.RuntimeException引起:   javax.crypto.BadPaddingException:填充块已损坏           在com.edaf.utils.ObscuredSharedPreferences.decrypt(SourceFile:185)           在com.edaf.utils.ObscuredSharedPreferences.getString(SourceFile:134)           在com.edaf.utils.Utils.getFromGlobals(SourceFile:145)

我在Firebase中发现了崩溃报告,无法复制。

0 个答案:

没有答案