"WP development" transfers encrypted data between different clients

Source: Internet
Author: User
Tags sendfile

In the previous article, it was said that this time will provide an example of transferring encrypted data between clients. A few days ago to write, just because some human technology unpredictable things happen, so dragged to today.

This example is not technical content, there are no bright spots, bugs, but to provide friends with the need for entertainment, like a dead friend is best not to look, otherwise you will make a runny nose a tear.

All right, that's enough nonsense.

Because the RT application on the Windows Add/Decrypt method and the previous article I told you the WP Plus decryption method is the same, after all, it is a shared API. In order to achieve the full force of the effect, I prepared the server application for the Windows Forms application, such projects believe that everyone is very familiar with, if you do not know what Windows Forms is, there is no way.

The client is of course WP mobile. In order to be forced and not complicated, my train of thought is this:

1. Select a. jpg image on the WP side, encrypt it through the DES algorithm, and then post to the server application via HTTP.

2. When the Windows Forms application as a server receives a file, it decrypts it with the DES Algorithm and saves the received file.

3, in order to facilitate processing, encryption and decryption keys are fixed. Key is 12345678 a total of eight bytes, and IV is 12345678 total eight bytes.

First say the server side, because everyone is familiar with. So, if you set up a temporary HTTP server to listen to the connection. Just for the sake of convenience, so I do not build ASP. NET application, such a small demo, do not bother IIS June. In fact, under the System.Net namespace, there is a HttpListener class that can write code to build a simple HTTP server and add a list of bound URIs that can listen for HTTP requests and then make the processing.

Before using HttpListener, it is a good idea to call its static IsSupported property to confirm that your current system can support HTTP snooping.

            if (! httplistener.issupported)            {                MessageBox.Show (" your current system is too broken to support HTTP snooping.) ");                  This . Close ();            }

After passing this check, the system is supported, and then the later functions are implemented. Here, by the way, there are a few things to note when configuring server addresses.

1. The bound URI is added to the prefixes collection.

2, the path of the URI can be arranged by itself, such as http://192.168.1.101:8080/sv/, can also http://192.168.1.101:8080/a/b/c/, Suppose your IP is 192.168.1.101, should not use localhost, because it is only native to access, is actually 127.0.0.1.

The URI must begin with HTTP, end with/, especially at the end, not less/otherwise an exception will occur.

If you are not sure of my IP, or to bind the IP, you can http://+:80/rec/, 80 is the port number, you can be specified according to the actual.

Call the Start method to start listening, and call the Stop method to stop. I use a task here to loop through the connection. The main code is as follows:

             This. Mhttplistener.start (); Task Backtask=NewTask (Workinback, Mhttplistener);            Backtask.start (); ...Private Async voidWorkinback (Objectobj) {HttpListener HTTPSVR= obj asHttpListener;  while(httpsvr.islistening) {HttpListenerContext context=awaitHttpsvr.getcontextasync (); //extracting a file name from the header                stringFileName = context. Request.Headers.Get ("file_name"); FileName= Path.Combine ( This. Docfolderpath, FileName); if(file.exists (filename)) {file.delete (filename); }                using(FileStream OutStream =File.openwrite (FileName)) {MemoryStream Tempstream=NewMemoryStream (); //decryption                    byte[] key = {1,2,3,4,5,6,7,8 }; byte[] IV = {1,2,3,4,5,6,7,8 }; DESCryptoServiceProvider des=NewDESCryptoServiceProvider (); CryptoStream Streamcrypt=NewCryptoStream (Tempstream, Des.                    CreateDecryptor (Key, iv), CryptoStreamMode.Write); Context.                    Request.InputStream.CopyTo (Streamcrypt); //Streamcrypt.flush (); //copy memory stream to file streamTempstream.position =0L;                    Tempstream.copyto (OutStream);                    Streamcrypt.dispose ();                Tempstream.dispose (); }            }        }

Using des plus decryption in traditional. NET programs I'm not going to introduce you. The Islistening property can tell if the listener is working, and if it stops, it will no longer receive the connection request.

The file name is obtained from the file_name header, which is customized to add this header when the WP client sends the file.

The following is the implementation of the WP client.

Here's what I used to say about file selectors. As I said in the previous article, Fileopenpicker's Picksinglefileandcontinue method call will temporarily leave the current app, and when the user finishes selecting it, it will reactivate the app and pass the user-selected file through the Onactivated method.

        protected Override voidOnActivated (Iactivatedeventargs args) {if(args. Kind = =activationkind.pickfilecontinuation) {Fileopenpickercontinuationeventargs e=(Fileopenpickercontinuationeventargs) args; if(E.files.count >0) {StorageFile thefile= e.files[0]; Frame Root= Window.Current.Content asFrame; if(Root! =NULL) {MainPage page=root. Content asMainPage; if(Page! =NULL) {page.                        SendFile (thefile);        }}}} Window.Current.Activate (); }

The Sendfile method is a custom method that is exposed in the MainPage page class, with the following code:

         Public Async voidSendFile (StorageFile file) {Irandomaccessstream Encryptedstream=NULL; using(Irandomaccessstream instream =awaitfile. OpenReadAsync ()) {Encryptedstream=await encryptodataasync(instream); }            using(HttpClient client =NewHttpClient ()) {Client. Defaultrequestheaders.add ("file_name", file.                Name); Httpresponsemessage Response=NULL; using(Httpstreamcontent content =Newhttpstreamcontent (Encryptedstream)) {Response=awaitClient. Postasync (NewUri (Txtserver.text), content); }                if(Response! =NULL&& Response. StatusCode = =Httpstatuscode.ok) {//sent successfully                }            }        }

The better part of HttpClient is that it can be encapsulated in different content formats for the content to be sent.

For example, to send a string, use Httpstringcontent; multipart/form-data MIME data is sent with Httpmultipartformdatacontent. Here, send a file, should be sent in the form of httpstreamcontent, stream.

In the above code, Encryptodataasync is a method I define, which is, of course, encrypting the input file stream, storing it in the memory stream, and returning the memory stream. Code:

        /// <summary>        ///Encrypt/// </summary>        /// <param name= "InputStream" ></param>        /// <returns></returns>        Private AsyncTask<irandomaccessstream>Encryptodataasync (Irandomaccessstream inputstream) {byte[] Bytekey = {1,2,3,4,5,6,7,8 }; byte[] Byteiv = {1,2,3,4,5,6,7,8 }; IBuffer Key=Bytekey.            Asbuffer (); IBuffer IV=Byteiv.            Asbuffer (); Symmetrickeyalgorithmprovider PRD=Symmetrickeyalgorithmprovider.openalgorithm (SYMMETRICALGORITHMNAMES.DESCBCPKCS7); //Create keyCryptographickey Crykey =PRD.            Createsymmetrickey (key); //Encrypt DataInmemoryrandomaccessstream MMS =NewInmemoryrandomaccessstream (); IBuffer Orgdata=NULL; using(DataReader reader =NewDataReader (InputStream)) {                UINTLen= (UINT) Inputstream.size; awaitReader.                LoadAsync (len); Orgdata=Reader.            Readbuffer (len); } IBuffer Res=Cryptographicengine.encrypt (Crykey, Orgdata, iv); awaitMMS.            WriteAsync (RES); MMs. Seek (0UL); returnMMS; }

The process of encrypting and decrypting in RT API is described in the preceding two-way encryption.

Get an instance first through Symmetrickeyalgorithmprovider.openalgorithm (SYMMETRICALGORITHMNAMES.DESCBCPKCS7).
Then, create the Cryptographickey instance as the key for encryption.

Finally, use the Cryptographicengine class to complete the encryption.

==============================

The sample core section has been introduced to you. The rest of the section omits more than 5,000 words, and later I will pack the source code to upload.

Note that when using the source code, run vs as an administrator, so that the HTTP service can listen, the phone end with a real machine test easy to connect, if not, first shut the firewall and then try again, after the test is turned on the firewall.

: Http://files.cnblogs.com/files/tcjiaan/Sample.zip

"WP development" transfers encrypted data between different clients

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.