Android文件解密和加密需要时间 [英] Android File Decryption and Encryption taking time

查看:141
本文介绍了Android文件解密和加密需要时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在android下载
时已经完成了加密和解密,但是我希望在文件解密时提高时间性能。
我的问题是当我下载任何文件,所以我在那里添加加密但在这个阶段我显示进度加载器所以它看起来不错,但是当文件完全下载并尝试打开该文件然后它被解密提交这次是因为花了太多时间。
这看起来很糟糕。如何减少解密时间?这是我的代码

I have done Encryption and Decryption in android when file downloading but I want to improve time performance when file decrypted. My problem is when I am downloading any file so I have add encryption over there but at this stage I am showing Progress loader so it looks good but but when file completely download and try to open that file then it is decrypted that file this time it's taking too much time . which is look very bad. How can I reduce decryption time? Here is my code

加密代码

byte data[] = new byte[1024];

String seed = "password";

byte[] rawKey = getRawKey(seed.getBytes());
SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

output = new CipherOutputStream(output, cipher);

long total = 0;

while ((count = input.read(data)) != -1) {
    total += count;
    publishProgress("" + (int) ((total * 100) / lenghtOfFile));

    output.write(data, 0, count);
}

解密代码在这里:

String newPath = sdCardPath + "/" + dPdfName;
File f1 = new File(newPath);
if (!f1.exists())
    try {
        f1.createNewFile();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

try {
    InputStream fis = new FileInputStream(f);
    OutputStream fos = new FileOutputStream(f1);
    String seed = "password";
    byte[] rawKey = getRawKey(seed.getBytes());
    SecretKeySpec skeySpec = new SecretKeySpec(rawKey,
            "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);

    fis = new CipherInputStream(fis, cipher);
    int b;
    byte[] data = new byte[4096];
    while ((b = fis.read(data)) != -1) {
        // fos.write(cipher.doFinal(data), 0, b);
        fos.write(data, 0, b);
    }
    fos.flush();
    fos.close();
    fis.close();

} catch (Exception e) {
    // TODO: handle exceptionpri
    e.printStackTrace();
}

获取行密钥方法:

private static byte[] getRawKey(byte[] seed) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    sr.setSeed(seed); 
    kgen.init(128, sr); 
    SecretKey skey = kgen.generateKey(); 

    byte[] raw = skey.getEncoded();
    return raw;
}


推荐答案

确保对齐数据缓冲区到加密的块大小。

Make sure you align the data buffer to the block size of the encryption.

有关示例,请参阅: https ://stackoverflow.com/a/33171612/475496

使用此方法可加快我们的加密速度。

Using this method has speedup our encryption enormous.

这篇关于Android文件解密和加密需要时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆