win8开发(9)——加密和解密数据

对于一些需要特列保护的数据,举个例子,刚从服务器上取到的一堆JSON数据,并保存

到本地文件中,你知道,JSON数据是文本,如果我不希望别人查看数据,可以对文件进

行加密,今天,我们来看一种比较简单的数据加密和解密。


实现这一构想,我们需要用到Windows.Security.Cryptography.DataProtection命名空间

下的DataProtectionProvider类,各位可以打开“对象浏览器”查看一下。


使用方法如下:
DataProtectionProvider类有两个构造函数,即


  • public DataProtectionProvider()   


    public DataProtectionProvider(  
  string protectionDescriptor  
)  


  • 在加密数据的时候,使用第二个构造函数,即带一个参数的,参数为字符串类型,但是
  • ,这个字符串不是乱写的,不信你试试,随便写个字符串进去,加密的时候就会抛出异常
  • 。所以,这个参数应取下面这些值


    • /****************************************************************************
    • Example Protection Descriptors:
    •   "SID=S-1-5-21-4392301 AND SID=S-1-5-21-3101812"
    •   "SDDL=O:S-1-5-5-0-290724G:SYD:(A;;CCDC;;;S-1-5-5-0-290724)(A;;DC;;;WD)"
    •   "LOCAL=user"
    •   "LOCAL=machine"
    •   "WEBCREDENTIALS=MyPasswordName"
    •   "WEBCREDENTIALS=MyPasswordName,myweb.com"
    • ****************************************************************************/

而对于本地加密,只有两个可以用,其他的都会发生异常,哪两个呢?你猜,看他们的名字

,本地使用的嘛,肯定带有“local”字样的,看看,上面的各值,哪些是带“local”的?

对,就是这两个
LOCAL=user
LOCAL=machine

那么它们有啥区别呢?看它们的值,懂了吗?一个是用户级别的加密,另一个呢?哈,当然

是机器级别的。

我估计是这样的,有兴趣的朋友可以自己做做实验。

对于user级别,例如,我以用户名“dog”登陆了当前系统,然后我运了程序App,我在App中

将文件kill加了密,如果我要将加密后的文件解密还原到kill的内容,当前电脑必须用“dog”的

用户登陆才能完成操作。

而machine级别就好理解了,就是本机,拿到其他电脑上就解不了密,虽然SDK文档没有明

地说明,但我估计应该是这样的。


虽然这种方式不能算是十分安全,但是对于一般数据就足够了。

接下来,我们通过一个实例来说一下如何使用。
1、启动VS,新建项目。
2、页面的XAML如下。


  • <Page  
  •     x:Class="App2.MainPage"  
  •     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  •     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  •     xmlns:local="using:App2"  
  •     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
  •     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
  •     mc:Ignorable="d">  
  •   
  •     <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">  
  •         <StackPanel>  
  •             <Button Name="btnPickInputFile" Content="输入文件..." Margin="5,14,0,10" Click="onInputFile"/>  
  •             <Button Name="btnPickOutputFile" Content="输出文件..." Margin="5,8,0,10" Click="onOutputFile"/>  
  •               
  •             <Line Margin="0,3,0,12" Stroke="LightGray" StrokeThickness="3"/>  
  •               
  •             <Button Content="保护文件" Click="onProtect"/>  
  •             <Button Content="解除保护" Click="onUnProtect"/>  
  •               
  •             <TextBlock Name="msgLabel" Margin="2,12,0,0" FontSize="20"/>  
  •         </StackPanel>  
  •     </Grid>  
  • </Page>  
3、转到代码视图,完成后面的代码,自己看看。



  • using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using Windows.Foundation;
    using Windows.Foundation.Collections;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Controls.Primitives;
    using Windows.UI.Xaml.Data;
    using Windows.UI.Xaml.Input;
    using Windows.UI.Xaml.Media;
    using Windows.UI.Xaml.Navigation;
    using Windows.Security.Cryptography.DataProtection;
    using Windows.Storage;
    using Windows.Storage.Streams;
    using Windows.Storage.Pickers;


  • // “空白页”项模板在  http://go.microsoft.com/fwlink/?LinkId=234238  上有介绍


  • namespace App2
    {
        /// <summary>
        /// 可用于自身或导航至 Frame 内部的空白页。
        /// </summary>
        public sealed partial class MainPage : Page
        {


  •         StorageFile inputFile, outputFile;
            public MainPage()
            {
                this.InitializeComponent();
            }


  •         /// <summary>
            /// 在此页将要在 Frame 中显示时进行调用。
            /// </summary>
            /// <param name="e">描述如何访问此页的事件数据。Parameter
            /// 属性通常用于配置页。</param>
            protected override void OnNavigatedTo(NavigationEventArgs e)
            {
            }


  •         private async void onInputFile(object sender, RoutedEventArgs e)
            {
                FileOpenPicker opPicker = new FileOpenPicker();
                opPicker.SuggestedStartLocation = PickerLocationId.Desktop;
                opPicker.FileTypeFilter.Add(".txt");
                opPicker.FileTypeFilter.Add(".data");
                this.inputFile = await opPicker.PickSingleFileAsync();
                Button btn = sender as Button;
                if (btn != null && inputFile != null)
                {
                    btn.Content = inputFile.Path;
                }
            }


  •         private async void onOutputFile(object sender, RoutedEventArgs e)
            {
                FileSavePicker fsPicker = new FileSavePicker();
                fsPicker.FileTypeChoices.Add("加密文件", new string[] { ".data" });
                fsPicker.FileTypeChoices.Add("文件文件", new string[] { ".txt" });
                fsPicker.SuggestedStartLocation = PickerLocationId.Desktop;
                this.outputFile = await fsPicker.PickSaveFileAsync();
                Button btn = sender as Button;
                if (btn != null && outputFile != null)
                {
                    btn.Content = outputFile.Path;
                }
            }


  •         private async void onProtect(object sender, RoutedEventArgs e)
            {
                if (inputFile == null || outputFile == null) return;


  •             IRandomAccessStream inputstr = await inputFile.OpenAsync(FileAccessMode.Read);
                IRandomAccessStream outputstr = await outputFile.OpenAsync(FileAccessMode.ReadWrite);


  •             DataProtectionProvider dp = new DataProtectionProvider("LOCAL=user");
                await dp.ProtectStreamAsync(inputstr, outputstr);
                this.msgLabel.Text = "完成数据加密。";


  •             inputFile = null;
                outputFile = null;
                ClearDisplay();
            }


  •         private async void onUnProtect(object sender, RoutedEventArgs e)
            {
                if (inputFile == null || outputFile == null)
                {
                    return;
                }


  •             IRandomAccessStream inputstr = await inputFile.OpenAsync(FileAccessMode.Read);
                IRandomAccessStream outputstr = await outputFile.OpenAsync(FileAccessMode.ReadWrite);


  •             DataProtectionProvider dp = new DataProtectionProvider();
                await dp.UnprotectStreamAsync(inputstr, outputstr);
                this.msgLabel.Text = "解密数据完成。";


  •             inputFile = null;
                outputFile = null;
                ClearDisplay();
            }


  •         private void ClearDisplay()
            {
                this.btnPickInputFile.Content = "输入文件...";
                this.btnPickOutputFile.Content = "输出文件...";
                //this.msgLabel.Text = string.Empty;
            }
        }
    }


  • 代码不算复杂,主要是DataProtectionProvider类的两个方法:
  • ProtectStreamAsync——对数据进行保护,第一个参数是输入流,
  • 即要加密的数据,第二个参数为输出流,也就是加密后的数据。

  • UnprotectStreamAsync——解除对数据的保护,即解密。

  • 上面两个方法是针对流操作的,如果是针对字节缓冲区,即使用
  • IBuffer的,可以用这两个方法:

  • ProtectAsync
    UnprotectAsync
    实现的效果是一样的,只是针对不同的对象而设计罢了。

    现在,运行一下程序。
    1、在桌面上新建一个txt文件,并输入一些内容,保存。

  • 2、把鼠标移到左上角,你会看到刚才运行的应用程序,点一下,
  • 就切回到应用程序。

  • 3、选择刚才新建的文本文件作为输入文件,并选择一个输出文件。
    1.png 

  • 4、点击保护文件,完成加密。这时我们用记事本打开加密后的文件,
  • 看到的是乱码。说明已加密。

  • 2.png 

  • 5、回到应用程序,把刚才加密后的文件作为输入文件,另外选取一
  • 个输入文件。点击解除保护按钮,完成后打开解密后的文件,对比
  • 一下原来的文件,看到了吧,解密成功。

  • 3.png 

    4.png 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值