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

时间:2015-12-10 11:01:28

标签: c# encryption windows-phone-8

我想在阅读时加密图像并保存在隔离存储和图像解密中。我能够做正常的文本数据,但我找不到图像的解决方案。而且我需要加密和解密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];
}

提前致谢。

1 个答案:

答案 0 :(得分:0)

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

加密代码:

 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;
                    }

干杯!!