如何在不丢失数据的情况下下载加密的png文件?

时间:2013-08-19 17:37:15

标签: android encryption imagedownload

我是android的新手。我正在做一个应用程序,它可以将加密的png图像文件下载到SD卡,然后在解密后显示它。但是我注意到在解密下载的图像时我得到了“javax.crypto.IllegalBlockSizeException: last block incomplete in decryption image decryption”。然后我发现下载的图像大小为0KB(原始 - 150KB)。然后我从浏览器下载了加密图像并进行了检查。我得到原始图像大小。我确定我的图像下载课有问题。但我无法弄明白。请帮我。提前谢谢。

图像下载AsyncTask类

public class DownloadImagesTask extends AsyncTask<String, Void, Bitmap>
{
    private String fileName;

    @Override
    protected Bitmap doInBackground(String... urls)
    {
        //Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
        return download_Image(urls[0]);
    }

    @Override
    protected void onPostExecute(Bitmap result)
    {
        storeImage(result);

    }

    private Bitmap download_Image(String url)
    {
        Bitmap bm = null;
        File file = new File(url);
        fileName = file.getName();
        try
        {
            URL aURL = new URL(url);
            URLConnection conn = aURL.openConnection();
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            bm = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();
        }
        catch (OutOfMemoryError e)
        {
            Log.e("Hub", "Error getting the image from server : " + e.getMessage().toString());
        }
        catch (IOException e)
        {
            Log.e("Hub", "Error getting the image from server : " + e.getMessage().toString());
        }

        return bm;
    }

    public void storeImage(Bitmap bm)
    {
        BitmapFactory.Options bmOptions;
        bmOptions = new BitmapFactory.Options();
        bmOptions.inSampleSize = 1;
        String extStorageDirectory = CommonUtils.getDataFromPreferences("metaPath", "");

        Log.d("extStorageDirectory", extStorageDirectory);
        OutputStream outStream = null;

        File wallpaperDirectory = new File(extStorageDirectory);
        if (!wallpaperDirectory.exists())
        {
            wallpaperDirectory.mkdirs();
        }
        File outputFile = new File(wallpaperDirectory, fileName);
        if (!outputFile.exists() || outputFile.length() == 0)
        {
            try
            {
                outStream = new FileOutputStream(outputFile);
            }
            catch (FileNotFoundException e1)
            {
                e1.printStackTrace();
            }

            try
            {
                bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
                outStream.flush();
                outStream.close();
                Log.d("ScratchActivtiy", "Image Saved");

            }
            catch (FileNotFoundException e)
            {
                e.printStackTrace();

            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}

(所有图片都是由我加密的。我将它们托管在服务器中。加密或解密都没有问题。我测试了它们。一切正常。)

CryptClass

public class CryptClass
{

    public byte[] encrypt(String seed, byte[] cleartext) throws Exception
    {

        byte[] rawKey = getRawKey(seed.getBytes());
        byte[] result = encrypt(rawKey, cleartext);
        //  return toHex(result);
        return result;
    }

    public byte[] decrypt(String seed, byte[] encrypted) throws Exception
    {
        byte[] rawKey = getRawKey(seed.getBytes());
        byte[] enc = encrypted;
        byte[] result = decrypt(rawKey, enc);

        return result;
    }

    //done
    private 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;
    }

    private byte[] encrypt(byte[] raw, byte[] clear) throws Exception
    {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(clear);
        return encrypted;
    }

    private byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception
    {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] decrypted = cipher.doFinal(encrypted);
        return decrypted;
    }
}

1 个答案:

答案 0 :(得分:2)

如果我理解正确您首先下载图像

BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);

然后将其保存到PNG压缩文件:

bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);

在对文件进行解密之后,对吧?

我认为您可能希望在将字节保存为png之前解密字节,甚至可能在使用decodeStream之前解密。否则,您正在解密解码流和PNG压缩的加密字节。

尝试跳过所有BitmapFactory内容,然后按原样保存初始文件,然后运行解密。在AsyncTask中:

String saveFilePath = <path to the temporary encrypted file>;

FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[4096];
while ((bytesRead = is.read(buffer)) != -1) {
    outputStream.write(buffer, 0, bytesRead);
}

outputStream.close();
inputStream.close();

然后在保存的文件上运行解密内容