如何在WP8中加密和解密图像

本文关键字:解密 图像 加密 WP8 | 更新日期: 2023-09-27 18:26:21

我想对图像进行加密并保存在独立存储中,并在读取时对图像进行解密。我可以做普通的文本数据,但我没有找到图像的解决方案。此外,我还需要加密和解密PDF/Doc文件。下面是我的代码

MemoryStream stream = new MemoryStream();
compressedStream.Seek(0, SeekOrigin.Begin);
using (IsolatedStorageFile isStore = IsolatedStorageFile.GetUserStoreForApplication())
{
     if (!isStore.FileExists(selectedImageName)) 
     using (IsolatedStorageFileStream targetStream = isStore.OpenFile(selectedImageName, FileMode.Create, FileAccess.Write))
     {
          byte[] readBuffer = new byte[4096];
          int bytesRead = -1;
          while ((bytesRead = compressedStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
          {
              targetStream.Write(readBuffer, 0, bytesRead);
          }
     }
}

使用以下代码加密普通文本

public static byte[] Encrypt(string text, string strCacheKey)
{
    try
    {
         return ProtectedData.Protect((Encoding.UTF8.GetBytes(text)), GetToken(strCacheKey));
    }
    catch (Exception)
    {             
    }
    return new byte[0];
}

提前谢谢。

如何在WP8中加密和解密图像

最终得到加密/解密图像的答案

加密代码:

 public static byte[] EncryptImage(byte[] encryptedimage, string strCacheKey)
    {
        try
        {
            return ProtectedData.Protect(encryptedimage, GetToken(strCacheKey));
        }
        catch (Exception)
        {
        }
        return new byte[0];
    }

解密代码:

public static byte[] DecryptImage(byte[] decryptedimage, string strCacheKey)
    {
        try
        {
            return ProtectedData.Unprotect(decryptedimage, GetToken(strCacheKey));
        }
        catch (Exception)
        {
        }
        return new byte[0];
    }

隔离存储代码:

 byte[] ibytes = new byte[attachmentStream.Length]; 
 byte[] ImageByte = TextImageEncryptionDecryption.EncryptImage(ibytes, App.cacheKey);
  using (var store = IsolatedStorageFile.GetUserStoreForApplication())
  using (IsolatedStorageFileStream targetStream = new IsolatedStorageFileStream(selectedImageName,
                                   FileMode.Create, FileAccess.Write, store))
                    {
                        targetStream.Write(ImageByte, 0, ImageByte.Length);
                    }

从ISO:读取图像的代码

   using (var stream = iso.OpenFile(name, FileMode.Open, FileAccess.Read))
                        {
                         byte[] ImgStr =  ReadFully(stream);
                         byte[] Img = TextImageEncryptionDecryption.DecryptImage(ImgStr, App.cacheKey);
                         Stream Imagestream = new MemoryStream(Img);
                         image.SetSource(Imagestream);
                         imgAttach = image;
                        }
                        return imgAttach;
                    }

干杯!!