在Android上将输入流写入文件作为png

时间:2016-03-31 16:34:44

标签: java android inputstream fileoutputstream

你能从png文件中获取inputStream加密并作为加密流发送并保存为png图片文件吗?

加密后我想解密文件并查看,但无法看到解密流中的照片。

当我保存OutputStream时,我无法查看加密或解密的文件。我没有抛出任何异常我在解密加密版本后无法看到照片。

我的尝试解密文件看起来像这样。

public void testDecryptionOfPhoto() throws Exception{
    File file = new File(getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "encryptedTest.png");
    InputStream inputStream = new FileInputStream(file);
    InputStream decryptedPhoto = decryption.decryptInputStream(inputStream);
    File file2 = new File(getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "photo.png");
    OutputStream outputStream = new FileOutputStream(file2);
    IOUtils.copy(decryptedPhoto,outputStream);
    outputStream.close();

加密

public InputStream encryptInputStream(InputStream inputStream) throws Exception{
      KeyCipher keyCiper = new KeyCipher();
      String streamContent = CharStreams.toString(new InputStreamReader(inputStream, "UTF-8"));
      Cipher cipher = Cipher.getInstance("Blowfish");
      cipher.init(ENCRYPT_MODE, keyCipher.getSecretSpecKey(), keyCipher.getIvParameterSpec());

     InputStream encryptedStream = new ByteArrayInputStream(encodeToString(cipher.doFinal(streamContent.getBytes("UTF-8")), DEFAULT).getBytes());
    return encryptedStream;
}

解密

public InputStream decryptInputStream(InputStream inputStream) throws Exception{
    KeyCipher keyCipher = new keyCipher();
    String streamContents = CharStreams.toString(new InputStreamReader(inputStream, "UTF-8"));
    byte[] encrypted = Base64.decode(streamContents, DEFAULT);

    Cipher cipher = Cipher.getInstance("Blowfish");
    cipher.init(Cipher.DECRYPT_MODE, keyCipher.getSecretSpecKey(), keyCipher.getIvParameterSpec());

    byte[] decryptedBytes = cipher.doFinal(encrypted);
    InputStream decryptedStream = new ByteArrayInputStream(decryptedBytes);
    return decryptedStream;

1 个答案:

答案 0 :(得分:0)

您不能使用char或toString()来处理加密流。并且也没有任何方式的utf-8。它不是你正在流媒体的文字。只需流加密的字节并将其作为字节接收。