gpt4 book ai didi

android - 同时读/写 Android 加密附加字节和重复

转载 作者:行者123 更新时间:2023-11-29 02:14:15 31 4
gpt4 key购买 nike

我目前正在尝试安全地读取、加密然后同时加密同一个文件(出于安全原因)。我在下面编写的代码几乎可以实现这一点,但会向解密文件添加额外的字节。除了 c.init 处于 DECRYPT_MODE 之外,解密方法几乎完全相同。

    public static void encryptFile(String path, byte[] key) throws Exception {

Cipher c = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec k = new SecretKeySpec(key, "AES");
c.init(Cipher.ENCRYPT_MODE, k);
RandomAccessFile raf = new RandomAccessFile(path, "rw");

byte[] buf = new byte[256];
byte[] output;
int bytesRead = 0;
int totalBytes = 0;
while ((bytesRead = raf.read(buf)) >= 0) {
int len = buf.length;
if (bytesRead < len) {
byte[] out2 = c.doFinal(buf, 0 , bytesRead);
raf.seek(totalBytes);
raf.write(out2);
} else {
output = c.update(buf, 0, bytesRead);
raf.seek(totalBytes);
raf.write(output);
}
totalBytes += bytesRead;
}
raf.getFD().sync();
raf.close();
}

解密示例

Some graduates could end up paying back double their original student loans under the new fees system in England, figures calculated for the BBC suggest.

The figures, by leading accountants, show that a student borrowing £39,000 for a three-year course \ܯ]£^*z§DþÒÐùN\ܯ]£^*z§DþÒÐùNree-year course ree-year course could pay back up to £83,000 in total, in cash terms.

Under the regime, due to begin in 2012, graduates will pay back 9% of their earnings for up to 30 years.

The government says the system is fair and From 2012, univeable to charge up to £9,000 per year, which will paid up front by the government but paid off once the student starts earning £21,000 or more.

它的调试和功能如我所料,我仍然对这些字节/重复是如何到达这里感到困惑。 (可能是 padding 或不正确的 doFinal)任何建议将不胜感激 :]谢谢!

最佳答案

好的,问题似乎是我没有考虑到每次更新的最后 16 个字节被附加到下一次调用。通过向 raf.seek 添加 16 个字节,我们与数据保持一致并正确附加 doFinal。还使用 output.length 似乎将正确的参数授予文件指针.. in 和输出的 md5s 是准确的,所以似乎有效! :] 解密函数使用 raf.setLength(totalBytes+output.length);

    public static void encryptFile(String path, byte[] key) throws Exception {

Cipher c = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec k = new SecretKeySpec(key, "AES");
c.init(Cipher.ENCRYPT_MODE, k);
RandomAccessFile raf = new RandomAccessFile(path, "rw");

byte[] buf = new byte[128];
int bytesRead = 0;
int totalBytes = 0;
byte[] output;
while ((bytesRead = raf.read(buf)) >= 0) {
output = c.update(buf, 0, bytesRead);
raf.seek(totalBytes);
raf.write(output);
totalBytes += output.length;
raf.seek(totalBytes+16);
}
output = c.doFinal();
raf.seek(totalBytes);
raf.write(output);
raf.getFD().sync();
raf.close();

}

关于android - 同时读/写 Android 加密附加字节和重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5336141/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com