加密和解密文件 [英] Encrypt and Decrypt files

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

问题描述

我需要下载mp3文件,并在必要时进行加密,以解密临时mp3并收听。

I need to download mp3 files, encrypt, when necessary, to decrypt a temporary mp3 and listen.

在StackOverflow中已经做过此答案​​的参考

Used as reference this answer already done in StackOverflow

在Android上使用AES加密文件

所有步骤均有效。但是,当我为MediaPlayer发送生成的mp3文件时,无法识别和破坏。

All steps works. But when I send the generated mp3 file for the MediaPlayer does not recognize and break.

这些是我的下载和加密方法

These are my download and encryption method

 public void executeAsyncDownload(String urlFile, String id, int position, HandlerCallback callback) {

    String encryptedName = Cypher.md5(id);

    if (MediaUtils.containsFile(encryptedName)) {
        callback.onDownloadFinish(position);
        return;
    }

    File dir = MediaUtils.getDestinationFolder(destination);

    if (!dir.exists()) {
        dir.mkdir();
    }

    try {
        if (canceled)
            return;

        callback.onDownloadStart(position);
        URL url = new URL(urlFile);
        URLConnection connection = url.openConnection();
        connection.connect();
        int tamFile = connection.getContentLength();
        String filePath = MediaUtils.getFilePath(MediaUtils.tempPath + encryptedName).toString();

        InputStream fis = new BufferedInputStream(url.openStream());
        OutputStream fos = new FileOutputStream(filePath);
        File file = new File(filePath);

        byte data[] = new byte[80192];
        int count;
        long total = 0;

        while ((count = fis.read(data)) != -1) {
            total += count;
            if (tamFile > 0) {
                int percentage = (int) (total * 100 / tamFile);
                if (percentage % 20 == 0)
                    callback.onDownloadProgress(percentage, position);
            }

            fos.write(data, 0, count);

            if (canceled) {
                MediaUtils.deleteFile(file);
                return;
            }
        }


        if (canceled)
            return;


        byte[] key = (salt + cryptPassword).getBytes("UTF-8");
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        key = sha.digest(key);
        key = Arrays.copyOf(key, 8);
        SecretKeySpec sks = new SecretKeySpec(key, "DES");
        Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, sks);
        CipherOutputStream cos = new CipherOutputStream(fos, cipher);

        int b;
        byte[] d = new byte[8192];
        while ((b = fis.read(d)) != -1) {
            cos.write(d, 0, b);
        }

        OutputStream outputEncrypted = new FileOutputStream(dir + File.separator + encryptedName);
        outputEncrypted.write(d);
        outputEncrypted.close();


        fos.flush();
        fos.close();
        fis.close();

        MediaUtils.deleteFile(file);//delete temp file

        callback.onDownloadFinish(position);
    } catch (Exception e) {
        e.printStackTrace();
        callback.onDownloadError(position);
    }
}

这是我的解密方法

 @SafeVarargs
@Override
protected final File doInBackground(HashMap<String, Object>... params) {
    String path = (String) params[0].get(FILE_PATH);
    String fileName = String.valueOf(params[0].get(FILE_NAME));
    boolean encrypted = (boolean) params[0].get(ENCRYPTED);

    File root = android.os.Environment.getExternalStorageDirectory();
    File dir = new File(root.getAbsolutePath() + File.separator + path + File.separator);
    File file;

    if (!encrypted) {
        file = new File(dir + File.separator + fileName);
        return file;
    }

    file = new File(dir + File.separator + Cypher.md5(fileName));
    File tempMp3 = null;
    try {
        tempMp3 = File.createTempFile(TEMP, MP3, context.getCacheDir());
        tempMp3.deleteOnExit();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        FileInputStream fis = new FileInputStream(file);
        byte[] key = (DownloadManager.salt + DownloadManager.cryptPassword).getBytes("UTF-8");
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        key = sha.digest(key);
        key = Arrays.copyOf(key, 8);
        SecretKeySpec sks = new SecretKeySpec(key, "DES");
        Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, sks);
        CipherInputStream cis = new CipherInputStream(fis, cipher);

        FileOutputStream fos = new FileOutputStream(tempMp3);

        int b;
        byte[] d = new byte[80192];
        while ((b = cis.read(d)) != -1) {
            fos.write(d, 0, b);
        }

        fos.flush();
        fos.close();
        cis.close();

    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }

    return tempMp3;
}


推荐答案

这样做之后:

    CipherOutputStream cos = new CipherOutputStream(fos, cipher);

    int b;
    byte[] d = new byte[8192];
    while ((b = fis.read(d)) != -1) {
        cos.write(d, 0, b);
    }

    OutputStream outputEncrypted = new FileOutputStream(dir + File.separator + encryptedName);
    outputEncrypted.write(d);
    outputEncrypted.close();

outputEncrypted 文件将只包含最后一个缓冲区充满数据。此外,该数据不会被加密。

the outputEncrypted file will just contain the last buffer full of data. Furthermore, this data will not be encrypted.

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

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