"WP Development" encryption chapter: two-way encryption

Source: Internet
Author: User

Speaking of bidirectional encryption, if previously in. NET development in the addition/decryption of friends are not unfamiliar, commonly used algorithms have DES, AES and so on. In the RT application, also provides the encryption related API, the algorithm naturally is the same, only the API encapsulation way is different, because RT is not completely managed code, but also resembles the form of the COM public, this for the low-end device, the performance can improve, of course, for the high-end device does not matter.

In the RT application of WP, involved in the addition/decryption of the API are in the following several namespaces, we want to use in the inside to find, not all classes will be used, encryption is generally used in two categories: the need to restore the content of the use of bidirectional encryption, such as DES, AES algorithm; If you do not need to restore the encrypted content, Use the MD5 and other hashing algorithms that we are seriously familiar with. such as passwords .

1, Windows.Security.Cryptography

2, Windows.Security.Cryptography.Core

3, Windows.Security.Cryptography.DataProtection

Among them, DataProtection is used by the system implementation of the algorithm to encrypt and decrypt data, more convenient, but not convenient transmission, more suitable for use in this machine, not suitable for encryption and decryption over the network transmission of encrypted data, universality is not so strong.

Today, we give you a brief introduction to the two-way encryption, I this personal character is bad, do not like a class to introduce, and then a table to say this class has what properties, methods and other ways of writing. I compare BS to people who are always copying MSDN. Therefore, do not expect me to explain mechanically to you, the old weeks do not like this, the old week has always been to the case of a unique sentiment.

However, some of the necessary saliva still want, no matter what algorithm you use to encrypt and decrypt the data, you need to use the Cryptographicengine class, this class character value is very high, is static, encryption and decryption directly call its method can, not new its instance. The Encrypt method is called when encrypting, and the decrypt method is called when decrypting.

Two-way encryption is usually prepared for two things, one is key key, one is the initial vector iv,iv is not required, but key is not limited. The key and IV are used for encryption, and decryption is also used when decrypting with the same key and IV as the encryption. I believe this is not my nonsense, this is the first grade of elementary school knowledge.

Let's talk about the next steps:

In the first step, a Symmetrickeyalgorithmprovider instance is obtained by Symmetrickeyalgorithmprovider static method Openalgorithm (), and the method parameter is the name of the Add/decrypt algorithm to be used. This string does not need us to guess how to write, directly through the static property of Symmetricalgorithmnames can return the corresponding name of the algorithm.

  Symmetrickeyalgorithmprovider SYPRD = Symmetrickeyalgorithmprovider.openalgorithm (SYMMETRICALGORITHMNAMES.DESCBC) ;

The second step, create a key, actually key is a set of bytes, I This example is the DES algorithm for example, the key is 64 bits, that is, 8 bytes, how these bytes generated, everyone to play their own imagination, for the sake of simplicity, I directly use 12345678来 to act as the 8 bytes.

        //A byte array that represents a key        byte[] Keybtarray = {1,2,3,4,5,6,7,8 }; //an array of bytes representing the initial vector (iv)        byte[] Ivbtarray = {1,2,3,4,5,6,7,8 }; //an object that represents the encryption/decryption keyCryptographickey MyKey =NULL;

The method to generate the key is to invoke the Createsymmetrickey method of the Symmetrickeyalgorithmprovider instance you just created. Here, let me show you a situation. Because the RT API inside the processing byte buffer is often used to ibuffer, the implementation of the interface type is the buffer class. The. NET API for byte[] defines an extension method that can produce a buffer object by means of the Asbuffer method.

            IBuffer Keybuffer = keybtarray.asbuffer ();             = Syprd. Createsymmetrickey (Keybuffer);

Step three, encrypt. Encryption is simple, call the Cryptographicengine.encrypt method directly, and return the encrypted data.

            // to encrypt            this. Cryptbuffer = Cryptographicengine.encrypt (MyKey, Txtbuffer, Ivbtarray.asbuffer ());

Fourth step, decrypt. Decryption is also simple to invoke.

            // decryption            this. Cryptbuffer, Ivbtarray.asbuffer ());

This example allows the user to enter text in a textbox, encrypt the text before decrypting it, and display the decrypted text.

    <StackPanel>        <stackpanel.resources>            <StyleTargetType= "TextBlock">                <Setter Property= "FontSize"Value= "All"/>            </Style>        </stackpanel.resources>        <TextBlockText= "Please enter what you want to encrypt:"/>        <TextBoxName= "Txtinput"/>        <ButtonMargin= "0,25,0,0"Content= "Encrypted"Click= "Onencryptclick"/>        <ButtonClick= "Ondecryptoclick">Decrypt</Button>        <TextBlockMargin= "0,25,0,0"Text= "After decryption:"/>        <TextBlockName= "Tbdecrypto"FontSize= "+"Foreground= "Skyblue"/>    </StackPanel>
        Private Async voidOnencryptclick (Objectsender, RoutedEventArgs e) {            //converts the input text to a byte bufferIBuffer Txtbuffer =cryptographicbuffer.convertstringtobinary (Txtinput.text, Binarystringencoding.utf8); Button b= Sender asButton; B.isenabled=false; //to encrypt             This. Cryptbuffer =Cryptographicengine.encrypt (MyKey, Txtbuffer, Ivbtarray.asbuffer ()); Windows.UI.Popups.MessageDialog Msgdlg=NewWindows.UI.Popups.MessageDialog ("encryption is complete. "); awaitMsgdlg.            Showasync (); B.isenabled=true; }        Private Async voidOndecryptoclick (Objectsender, RoutedEventArgs e) {Button B= Sender asButton; B.isenabled=false; //decryptionIBuffer Decryptbuffer = Cryptographicengine.decrypt (MyKey, This. Cryptbuffer, Ivbtarray.asbuffer ()); Tbdecrypto.text=cryptographicbuffer.convertbinarytostring (Binarystringencoding.utf8, Decryptbuffer); Windows.UI.Popups.MessageDialog MsgBox=NewWindows.UI.Popups.MessageDialog ("decryption is complete. "); awaitMsgBox.            Showasync (); B.isenabled=true; }

To convert text to buffer, can use the Cryptographicbuffer.convertstringtobinary method, in turn can use the cryptographicbuffer.convertbinarytostring, the encoding method generally uses the utf-8, such generality is good.

It seems that everything is ready, but after moving the line, an exception occurs when encrypting, prompting for an invalid buffer input. Many people have encountered this error, and I have seen many friends asking questions in the MSDN community, as well as in other communities, regardless of DES or AES algorithms. Why is there an error when encrypting?

That's because the encrypted byte blocks are not aligned. You can use the following code to get the block size of a cryptographic algorithm.

System.Diagnostics.Debug.WriteLine (" block Size:" + SYPRD. Blocklength);

is the Blocklength attribute of the Symmetrickeyalgorithmprovider instance, the DES algorithm outputs the following result:

8 is 8 bytes, if the total number of bytes of data to be encrypted is not a multiple of 8, it will be an error, if the encrypted data size is 16 bytes, can be divisible by 8, no error, if 23, cannot be divisible by 8, an exception occurs.

OK, find out the reason, the solution is targeted, one way is you do it yourself, try to get the length of the encrypted data into multiples of 8. For example, 23 bytes, you would try to add a byte to make it into 24 bytes.

In fact, there is a way to be more simple, is to let the algorithm itself to fill, the method is in the new Symmetrickeyalgorithmprovider instance, We used to use the SYMMETRICALGORITHMNAMES.DESCBC, to change it to SYMMETRICALGORITHMNAMES.DESCBCPKCS7 on the line. Because the PKCS7 mode automatically populates the block of bytes.

     Symmetrickeyalgorithmprovider SYPRD = Symmetrickeyalgorithmprovider.openalgorithm ( SYMMETRICALGORITHMNAMES.DESCBCPKCS7);

In such a change, encryption will not be error, because the byte block is automatically populated.

Look at the results of the operation:

AES's cryptographic decryption is also similar to DES.

Look at the time, almost dinner, first of all, let's talk about one-way encryption.

SOURCE Download: Http://files.cnblogs.com/files/tcjiaan/CryptoApp.zip

"WP Development" encryption chapter: two-way encryption

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.