C # implements network transfer data encryption

Source: Internet
Author: User
Tags getstream

1. Block password

The block cipher is the grouping of the number sequence divided into n after the plaintext message is encoded, and each group is transformed and output by the function of the key, which is the cipher text. Encrypt one data group at a time, and decryption uses the same key, so it is often referred to as symmetric encryption. Division leader n various symmetric encryption algorithm values are different (DES and tripledes are 64 bits, AES default is 128 bits, can also be 192-bit and 256-bit), when the text message is grouped when the last packet is less than n, then the data is populated, Make the division leader reach N to perform subsequent cryptographic processing. The cryptographic classes provided by the. NET platform are well handled by the above problems, so the actual coding in the C # language can be easily done with encryption and decryption operations.

The Rijndael algorithm, as one of the AES, has replaced TripleDES (Triple DES) as the new data Encryption standard. Its packet length and key length are variable, and it is longer than DES algorithm, which also has higher security. The example program in this article uses the Rijndael algorithm.

2. Operating mode

When the block cipher is encrypted, the length of the plaintext packet is fixed, and the amount of data to be encrypted in the utility is uncertain, and if the adjacent two packets are correlated with decryption, a different mode of operation is produced. The following main introduction of two commonly used block cipher operation mode

1. ECB mode

The ECB mode is the simplest mode of operation, with each grouping using the same key for encryption, as shown in 1.


Figure 1. ECB mode

When the key is timed, each packet of clear text has a unique ciphertext corresponding to it. This also creates the largest feature of the ECB mode, where the same plaintext groupings are repeated in the message, and the ciphertext groupings that are generated are the same. Therefore, the ECB may not be secure for long messages, and if the message has a fixed structure, the attacker could identify the relationship. However, because in the ECB mode, each packet encryption and decryption are independent, so it is convenient to parallel computing, improve the operation efficiency of large-scale data encryption and decryption.

2. CBC mode

In order to solve the security flaw of ECB mode, it is possible to create different cipher groupings for repeated plaintext groupings, which can be satisfied by CBC mode. 2, in the CBC mode, one plaintext packet encryption at a time, each encryption using the same key, the input of the encryption algorithm is the current clear text grouping and the previous ciphertext group XOR, so the input of the encryption algorithm does not show the fixed relationship between the plaintext, Therefore, repeated plaintext groupings do not expose this repeating relationship in the ciphertext.


Figure 2 CBC Mode

When generating the first ciphertext grouping, you need to have an IV with the first plaintext group XOR. When decrypting, the IV and decryption algorithms XOR the output of the first ciphertext packet to restore the first plaintext group. IV is known for both the transceiver and the key, and for maximum security, iv should be protected as a key.

The packet encryption classes provided on the. NET platform use CBC mode by default, but you can change this default setting as needed.

3. Data encryption and decryption

In the implementation of data encryption and decryption are mainly related System.Security.Cryptography to the next RijndaelManaged and CryptoStream class. mentioned earlier. NET platform of the packet encryption class by default is the CBC mode, so the first to generate the key key and IV. When the RijndaelManaged instance is generated, a set of 16-byte random keys and IV is generated by default, in order to eliminate the key exchange process for both sides of the communication, the key and IV are specified directly, and the encryption and decryption are the same. Look at the code, see the comments.

Data encryption
 1//Create RijndaelManaged instance 2 rijndaelmanaged rmcrypto = new RijndaelManaged (); 3//byte[] key = Rmcrypto.key; 4//byte[] IV = RMCRYPTO.IV; 5//Initialize KEY,IV 6 byte[] Key = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0 x16}; 7 byte[] IV = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16}; 8 9 Console.WriteLine ("Connecte successed! Enter the message to send: "); string smessage = Console.ReadLine (); 11//Convert plaintext message to UTF8 encoded byte stream, avoid garbled byte[] Messagebyte = E Ncoding. UTF8. GetBytes (smessage); 13//Instantiate a MemoryStream for storing encrypted data streams MemoryStream mstream = new MemoryStream (); 15// Create a CryptoStream instance for encryption CryptoStream cryptstream = new CryptoStream (mstream,17 rmcrypto.createencryptor (Key, IV), 18 CryptoStreamMode.Write); 19//writes the plaintext message byte stream to the CryptoStream, encrypts the Cryptstream.write (messagebyte,0, MESSAGEBYTE.LENGTH); 21//Update the data in CryptoStream to MemoryStream Cryptstream.flushfinalblock (); 23//Convert encrypted data flow to byte stream 24 Byte[] EncryptoByte = Mstream.toarray (); 
Data decryption
1//Create an MemoryStream instance that holds the encrypted data byte stream received 2 MemoryStream encryptostream = new MemoryStream (encryptobyte); 3//Create RijndaelManaged instance 4 rijndaelmanaged rmcrypto = new RijndaelManaged (); 5//byte[] key = Rmcrypto.key; 6//byte[] IV = RMCRYPTO.IV; 7//Initialize KEY,IV 8 byte[] Key = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0 x16}; 9 byte[] IV = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16};10 11 12 Create a CryptoStream instance for decryption CryptoStream cryptstream = new CryptoStream (encryptostream,14    Rmcrypto.createdecryptor (Key, IV),    cryptostreammode.read); 16 17//Create StreamReader instance, read data from CryptoStream, 18// StreamReader defaults to read data using UTF8 encoding StreamReader sreader = new StreamReader (cryptstream), 20 21//Output decrypted message. 22 Console.WriteLine ("The decrypted original message: {0}", Sreader.readtoend ());
4. Data transfer

The data transfer uses a TCP connection, and the. NET platform also encapsulates the socket well, making network IO operations very convenient. Before the ciphertext data is sent to the Base64 form of string, one is convenient for the normal display of encrypted data, on the other hand, it is convenient for the data receiving end in the receiving byte stream data to facilitate transcoding into a string. Base64 is used to represent binary data with 64 printable ASCII characters, so the conversion of the BASE64 string to the byte stream is a one-to-many conversion, that is, one character corresponds to the other, so that the conversion between the byte stream and the string does not deviate from the encoding method. Causes a subsequent decryption operation to occur unexpectedly.

Client
1//Create TCP connection 2 TcpClient TCP = new TcpClient ("localhost", 11000); 3  4//Get network traffic from the TCP connection  5 NetworkStream NetStream = tcp. GetStream (); 6  7//for easy display, stream the encrypted data bytes into a Base64 encoded string of 8 string encryptBase64 = Convert.tobase64string (encryptobyte); 9//convert string to byte stream 10 Encryptobyte = Encoding.ASCII.GetBytes (encryptBase64); 11 12//writes the encrypted data to the NetworkStream and sends it to the server. Netstream.write (encryptobyte, 0, Encryptobyte.length); Console.WriteLine ("The encryptoed message: {0}", ENCRYPTBASE64); Console.WriteLine ("The message was sent.");
Service side
 1//Initialize Tcplisten bound IP address and listening port 2 tcplistener tcplisten = new TcpListener (Ipaddress.any, 11000); 3 4//Start monitoring 5 Tcplisten . Start (); 6 7//Every five seconds, check if there is a connection 8 while (! Tcplisten.pending ()) 9 {Console.WriteLine ("Still listening. Would try in 5 seconds. "); Thread.Sleep (5000); 12}13 14//Accept TCP connection. TcpClient TCP = Tcplisten.accepttcpclient (); 16 17//Create networkstream.1 for this connection 8 NetworkStream NetStream = TCP. GetStream (); 19 20//loop reads data from NetworkStream string encryptostring = ""; int bytes;23 while (true) byte[ essage = new Byte[10];26 bytes = Netstream.read (bytemessage, 0, ten), if (bytes <= 0); 30}31//Encrypted data is sent by BASE64 encoded into a string, can be directly ASCII encoded byte into ASCII code character 32//assembled into a complete BAS64 encoded string encryptostring + = Enco Ding. Ascii. GetString (bytemessage,0,bytes);}35 Console.WriteLine ("The encryptoed Message: {0}", encryptostring); 36// Convert Base64 encoded string to byte stream byte[] Encryptobyte = convert.frombase64string (encryptostring); 

The CryptoStream class uses a class derived from stream to initialize, so in this sample program you can create CryptoStream samples directly using the Networstream override MemoryStream. See msdn-encrypted data in the sample program. The sample program uses MemoryStream to facilitate the acquisition of encrypted data.

C # implements network transfer data 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.