繁体   English   中英

在Android上将Inputstream以PNG格式写入文件

[英]Writing Inputstream to File as png on Android

您可以从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;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM