【问题标题】:Writing Inputstream to File as png on Android在 Android 上将 Inputstream 以 png 格式写入文件
【发布时间】:2016-07-20 05:42:44
【问题描述】:

你能否从 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;

【问题讨论】:

  • “看照片”是什么意思?究竟是什么你没有看到你期望看到的?
  • 当我解密一张加密的照片时,我看不到照片。所以我加密了一张照片,然后解密并且无法查看原始照片。
  • 您遇到错误了吗?你到底看到了什么?请具体。
  • 我在 android 文件查看器中看到了我创建的文件。但是无法访问照片,我可以在文件查看器中将其视为 txt 以查看文件内容,但它只是一张黑色照片(不是原始照片)。

标签: java android inputstream fileoutputstream


【解决方案1】:

您不能使用 char 或 toString() 来处理加密流。而且无论如何也不是utf-8。它不是您正在流式传输的文本。只需流式传输加密的字节并将它们作为字节接收。

【讨论】:

    猜你喜欢
    • 2014-09-17
    • 2016-03-19
    • 2016-12-22
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 2011-09-09
    • 2012-04-12
    相关资源
    最近更新 更多