安卓上的加密对象序列化,无法从文件加载



First.以前从未在这里发过帖子,如果我违反了任何规则,对不起!

我正在尝试为 android 制作一个应用程序,该应用程序序列化包含文件数组(有点像加密卷(的类的密封对象。

我已经设法创建了该文件,但由于某种原因无法从中加载数据。不确定 android 序列化与常规桌面应用程序有何不同,每次我在谷歌上搜索如何做到这一点时,我都会得到几年前帖子的链接。

在应用程序启动时,我运行检查文件是否存在,如果不存在,则创建它。注意:这部分非常粗略,因为它是为了快速测试应用程序本身,将来会更改它。这是它的样子:

if (!Files.exists(Paths.get("android.resource://" + getPackageName() + "/vault.vlt")))

要创建文件:

final Cipher cipher = generateCipher();
final FileOutputStream fileOutputStream = openFileOutput("vault.vlt",
MODE_PRIVATE);
final CipherOutputStream cipherOutputStream = new CipherOutputStream(fileOutputStream, cipher);
final ObjectOutputStream objectOutputStream = new ObjectOutputStream(cipherOutputStream);
objectOutputStream.writeObject(Core.getVault());
objectOutputStream.close();
Toast.makeText(this,"Saved",Toast.LENGTH_SHORT).show();

要加载文件:

final Cipher cipher = generateCipher();
final FileInputStream fileInputStream = openFileInput("vault.vlt");
final CipherInputStream cipherInputStream = new CipherInputStream(fileInputStream, cipher);
final ObjectInputStream objectInputStream = new ObjectInputStream(cipherInputStream);
Core.setVault((Vault) objectInputStream.readObject());
objectInputStream.close();
Toast.makeText(this,Core.getVault().apples,Toast.LENGTH_SHORT).show();

这就是我使用 Guava 生成密码方法的样子:

// key size
final byte keySize = 32; // 256
// Hashing
final String hash =
Hashing.sha256()
.hashString(Core.getVault().getPassword(), Charsets.UTF_8)
.toString().substring(0, keySize);
// Creating keys
final byte[] key = hash.getBytes();
final String transformation = "AES";
final SecretKeySpec secretKeySpec = new SecretKeySpec(key, transformation);
// Creating cipher
@SuppressLint("GetInstance") final Cipher cipher = Cipher.getInstance(transformation);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
return cipher;

这是我错误的堆栈跟踪:

W/System.err: java.io.StreamCorruptedException: invalid stream header: 02FD0D3D
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:808)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:302)
at theredspy15.vault115.EntranceActivity.loadVault(EntranceActivity.java:70)
at theredspy15.vault115.EntranceActivity.enter(EntranceActivity.java:41)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

从文件读取时,您需要将Cipher放入DECRYPT_MODE中。

最新更新