New Fashion Windows 8 Development (9): Data encryption and decryption

Source: Internet
Author: User
Tags blank page

In this blog, http://blog.csdn.net/tcjiaan.

 

For some data that requires special column protection, for example, a pile of JSON data just obtained from the server and saved it to a local file. As you know, JSON data is text, if I don't want others to view the data, I can encrypt the file. Today, let's look at a simple data encryption and decryption method.

 

To implement this idea, we need to use the dataprotectionprovider class in the windows. Security. cryptography. dataprotection namespace. You can open the "Object Browser" to check it.

 

The usage is as follows:

The dataprotectionprovider class has two constructors:

1,

public DataProtectionProvider()

 

2,

public DataProtectionProvider(  string protectionDescriptor)

 

When encrypting data, use the second constructor, that is, the parameter with a parameter, which is of the string type. However, this string is not gibberish. Please try again, write a string at will, and an exception will be thrown during encryption. Therefore, this parameter should take the following values.

/****************************************************************************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"****************************************************************************/

 

For local encryption, only two of them can be used, and exceptions may occur in other cases. Which two of them are available? You guess, look at their names. If they are used locally, they must carry the words "local". Let's see which values contain "local?

Yes, these two

Local = user

Local = Machine

What are their differences? Check their values. Do you understand? One is user-level encryption, and the other is? Ha, of course, at the machine level.

I guess this is the case. If you are interested, you can do experiments on your own.

For the user level, for example, I log on to the current system with the username "dog", then I run the program app, and I add the file kill secret in the app, if I want to decrypt the encrypted file and restore it to the kill content, the current computer must use the "dog" user login to complete the operation.

The machine level is easy to understand. It means that the password cannot be decrypted on other computers. Although the SDK documentation does not provide a clear description, I guess it should be like this.

 

Although this method is not safe, it is sufficient for general data.

 

Next, let's talk about how to use it through an instance.

1. Start Vs and create a project.

2. the page's XAML is as follows.

<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 = "input file... "margin =", "click =" oninputfile "/> <button name =" btnpickoutputfile "content =" output file... "margin =", "click =" onoutputfile "/> <line margin =, 0, 12 "stroke =" lightgray "strokethickness =" 3 "/> <button content =" protect files "Click =" onprotect "/> <button content =" unprotect "Click =" onunprotect "/> <textblock name =" msglabel "margin =" 2,12, 0, 0 "fontsize =" 20 "/> </stackpanel> </GRID> </Page>

 

3. Go to the Code view and complete the code.

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. dataprotecti On; using Windows. Storage; using Windows. Storage. streams; using Windows. Storage. pickers; // "blank page" item template in http://go.microsoft.com/fwlink? Linkid = 234238 introduces namespace app2 {/// <summary> /// it can be used for itself or navigation to a blank page inside the frame. /// </Summary> Public sealed partial class mainpage: Page {storagefile inputfile, outputfile; Public mainpage () {This. initializecomponent () ;}/// <summary> /// call when this page is to be displayed in the frame. /// </Summary> /// <Param name = "E"> describes how to access event data on this page. Parameter // properties are usually used on the configuration page. </Param> protected override void onnavigatedto (navigationeventargs e) {} private async void oninputfile (Object sender, Volume 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 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 ("encrypted file", new string [] {". data "}); fspicker. filetypechoices. add ("file", 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"); awa It DP. protectstreamasync (inputstr, outputstr); this. msglabel. Text = "Completes data encryption. "; 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 = "data decryption is complete. "; Inputfile = NULL; outputfile = NULL; cleardisplay ();} private void cleardisplay () {This. btnpickinputfile. content = "input file... "; this. btnpickoutputfile. content = "output file... "; // This. msglabel. TEXT = string. empty ;}}}

 

The code is not complex. It mainly involves two methods of the dataprotectionprovider class:

Protectstreamasync-protects data. The first parameter is the input stream, that is, the data to be encrypted, and the second parameter is the output stream, that is, the encrypted data.

Unprotectstreamasync -- unprotects data, that is, decryption.

The above two methods are for stream operations. If they are for byte buffers, that is, ibuffer, you can use these two methods:

Protectasync

Unprotectasync

The effects are the same, but they are designed for different objects.

 

Now, run the program.

1. Create a TXT file on the desktop, input some content, and save the file.

2. Move the mouse to the upper left corner and you will see the application you just run. Click it to switch back to the application.

3. Select the text file you just created as the input file and select an output file.

 

4. Click "protect file" to complete encryption. In this case, we use NotePad to open the encrypted file and see garbled characters. Indicates that the data has been encrypted.

 

5. Return to the application and use the encrypted file as the input file. select another input file. Click the unprotect button to open the decrypted file and compare the original file. The decryption is successful.

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.