On. NET encryption and decryption implementation method sharing _ practical skills

Source: Internet
Author: User
Tags decrypt getstream asymmetric encryption

. NET merges the original standalone APIs and SDK into one framework, which is very beneficial for program developers. It adapts the CryptoAPI into the. Net System.Security.Cryptography namespace, which makes the password service free from the mystery of the SDK platform and becomes the use of a simple. Net namespace. Because password services are easier to implement as the entire framework component is shared, it is now only necessary to learn the features of the System.Security.Cryptography namespace and the classes used to resolve specific scenarios.
  Algorithms for encryption and decryption

The System.Security.Cryptography namespace contains classes that implement security scenarios, such as encrypting and decrypting data, managing keys, validating the integrity of data, and ensuring that data has not been tampered with, and so on. This article focuses on encryption and decryption.

The algorithms for encryption and decryption are divided into symmetric (symmetric) algorithms and asymmetric (asymmetric) algorithms. Symmetric algorithms use the same key and initialization vectors when encrypting and decrypting data, typically DES, tripledes, and Rijndael algorithms, which apply to situations where the key is not required to be passed, primarily for encryption of local documents or data. The asymmetric algorithm has two different keys, the public key and the private key, and the public key is passed over the network to encrypt the data, while the private key is used to decrypt the data. The asymmetric algorithm mainly includes RSA, DSA and so on, mainly uses in the network data encryption.

  Encrypt and decrypt local documents

The following example is the encryption and decryption of local text, using the Rijndael symmetric algorithm.

The symmetric algorithm encrypts the data when it is in circulation. So first you need to create a normal stream (for example I/O stream). The article uses the FileStream class to read a text file into a byte array, and uses that class as an output mechanism.

Next, define the corresponding object variables. We can specify any symmetric cryptographic algorithm provider when defining object variables for SymmetricAlgorithm abstract classes. The code uses the Rijndael algorithm, but it's easy to change to des or tripledes algorithms. NET uses a powerful random key to set the instance of the provider, it is more dangerous to choose your own key, it is a better choice to accept the key generated by the computer, the code in this article uses the computer generated key.

Next, an algorithm instance provides an object to perform the actual data transfer. Each algorithm has CreateEncryptor and createdecryptor two methods that return objects that implement the ICryptoTransform interface.

Finally, the source file is now read using the BinaryReader Readbytes method, which returns a byte array. BinaryReader reads the input stream of the source file and invokes the Readbytes method as an argument to the Cryptostream.write method. The specified CryptoStream instance is informed of the underlying stream that it should operate, and the object will perform data transfer regardless of whether the stream is intended to be read or written.

The following is a fragment of the source program that encrypts and decrypts a text file:

Copy Code code as follows:

Namespace Com.billdawson.crypto
{
Class Textfilecrypt
{
public static void Main (string[] args)
{
string file = Args[0];
String tempfile = Path.gettempfilename ();
Opens the specified file
FileStream Fsin = File.Open (File,filemode.open,
FileAccess.Read);
FileStream fsout = File.Open (Tempfile, FileMode.Open,
FileAccess.Write);
Defining symmetric algorithm object instances and interfaces
SymmetricAlgorithm symm = new RijndaelManaged ();
ICryptoTransform transform = symm. CreateEncryptor ();
CryptoStream cstream = new CryptoStream (Fsout,transform,
Ryptostreammode.write);

BinaryReader br = new BinaryReader (fsin);
Read source files to CryptoStream
Cstream. Write (Br. Readbytes ((int) fsin.length), 0, (int) fsin.length);
Cstream. FlushFinalBlock ();
Cstream. Close ();
Fsin.close ();
Fsout.close ();

Console.WriteLine ("Created encrypted file {0}", tempfile);
Console.WriteLine ("'ll now decrypt and show contents");

Reverse--Decrypt the temporary file that was just encrypted
Fsin = File.Open (Tempfile,filemode.open,fileaccess.read);
Transform = symm. CreateDecryptor ();
Cstream = new CryptoStream (Fsin,transform,
CryptoStreamMode.Read);

StreamReader sr = new StreamReader (cstream);
Console.WriteLine ("Decrypted file text:" + Sr.) ReadToEnd ());
Fsin.close ();
}
}
}

Encrypt network data

If I have a document that I just want to see myself, I won't send it to you simply by e-mail. I'll encrypt it using a symmetric algorithm, and if someone intercepts it, they can't read the document because they don't have a unique key for encryption. But you don't have a key either. I need to give you the key in some way so that you can decrypt the document, but not the risk of the key and the document being intercepted.

An asymmetric algorithm is a solution. The two keys used by such algorithms are related to the following: Information encrypted using a public key can only be decrypted by the corresponding private key. Therefore, I first ask you to send me your public key. Someone may intercept it on the way to me, but it doesn't matter, because they can only use the key to encrypt your information. I use your public key to encrypt the document and send it to you. You use a private key to decrypt the document, which is the only key that can be decrypted and is not delivered over the network.

The asymmetric algorithm calculates more cost and slower than the symmetric algorithm. So we don't want to use an asymmetric algorithm to encrypt all the information in an online conversation. Instead, we use a symmetric algorithm. In the example below we use asymmetric encryption to encrypt the symmetric key. The symmetric algorithm is then used to encrypt the. In fact, the Secure Interface Layer (SSL) establishes a security dialog between the server and the browser that works in this way.
The example is a TCP program that is divided into server side and client. The workflow on the server side is:

Receives a public key from the client.

Use a public key to encrypt future symmetric keys used.

Sends the encrypted symmetric key to the client.

Sends information that is encrypted using this symmetric key to the client.

The code is as follows:

Copy Code code as follows:

Namespace Com.billdawson.crypto
{
public class Cryptoserver
{
Private Const int rsa_key_size_bits = 1024;
Private Const int rsa_key_size_bytes = 252;
Private Const int tdes_key_size_bits = 192;

public static void Main (string[] args)
{
int port;
String msg;
TcpListener Listener;
TcpClient client;
SymmetricAlgorithm symm;
RSACryptoServiceProvider RSA;
Get port
Try
{
Port = Int32.Parse (Args[0]);
msg = args[1];
}
Catch
{
Console.WriteLine (USAGE);
Return
}
Establish monitoring
Try
{
Listener = new TcpListener (port);
Listener. Start ();
Console.WriteLine ("Listening on port {0}", port);

Client = listener. AcceptTcpClient ();
Console.WriteLine ("Connection.");
}
catch (Exception e)
{
Console.WriteLine (E.message);
Console.WriteLine (E.stacktrace);
Return
}

Try
{
RSA = new RSACryptoServiceProvider ();
Rsa. KeySize = rsa_key_size_bits;

Get client public key
Rsa. ImportParameters (Getclientpublickey (client));

Symm = new TripleDESCryptoServiceProvider ();
Symm. KeySize = tdes_key_size_bits;

Use the client's public key to encrypt the symmetric key and send it to the guest.
Encryptandsendsymmetrickey (client, RSA, SYMM);

Encrypt information using symmetric keys and send
Encryptandsendsecretmessage (client, symm, MSG);
}
catch (Exception e)
{
Console.WriteLine (E.message);
Console.WriteLine (E.stacktrace);
}
Finally
{
Try
{
Client. Close ();
Listener. Stop ();
}
Catch
{
Error
}
Console.WriteLine ("Server exiting");
}
}

private static RSAParameters Getclientpublickey (TcpClient client)
{
To obtain a serialized public key from a byte stream and write an instance of the class by string and transformation
byte[] buffer = new Byte[rsa_key_size_bytes];
NetworkStream ns = client. GetStream ();
MemoryStream ms = new MemoryStream ();
BinaryFormatter bf = new BinaryFormatter ();
RSAParameters result;

int len = 0;
int totallen = 0;

while (Totallen
(len = ns.) Read (Buffer,0,buffer. Length)) >0)
{
Totallen+=len;
Ms. Write (buffer, 0, Len);
}

Ms. position=0;

result = (RSAParameters) bf. Deserialize (MS);
Ms. Close ();

return result;

}

private static void Encryptandsendsymmetrickey (
TcpClient Client,
RSACryptoServiceProvider RSA,
SymmetricAlgorithm symm)
{
Encrypt a symmetric key using the client's public key
Byte[] symkeyencrypted;
Byte[] symivencrypted;

NetworkStream ns = client. GetStream ();

symkeyencrypted = RSA. Encrypt (symm. Key, false);
symivencrypted = RSA. Encrypt (Symm.iv, false);

Ns. Write (symkeyencrypted, 0, symkeyencrypted.length);
Ns. Write (symivencrypted, 0, symivencrypted.length);

}

private static void Encryptandsendsecretmessage (TcpClient client,
SymmetricAlgorithm Symm,
String secretmsg)
{
Using symmetric keys and initializing vector encryption information to send to clients
Byte[] msgasbytes;
NetworkStream ns = client. GetStream ();
ICryptoTransform transform =
Symm. CreateEncryptor (symm. KEY,SYMM.IV);
CryptoStream cstream =
New CryptoStream (NS, transform, cryptostreammode.write);

Msgasbytes = Encoding.ASCII.GetBytes (secretmsg);

Cstream. Write (msgasbytes, 0, msgasbytes.length);
Cstream. FlushFinalBlock ();
}
}

The workflow for the client is:

Establish and send a public key to the server.

Receives the encrypted symmetric key from the server.

Decrypts the symmetric key and takes it as a private asymmetric key.

Receives and decrypts information using an asymmetric key.

The code is as follows:

Copy Code code as follows:

Namespace Com.billdawson.crypto
{
public class Cryptoclient
{
Private Const int rsa_key_size_bits = 1024;
Private Const int rsa_key_size_bytes = 252;
Private Const int tdes_key_size_bits = 192;
Private Const int tdes_key_size_bytes = 128;
Private Const int tdes_iv_size_bytes = 128;
public static void Main (string[] args)
{
int port;
string host;
TcpClient client;
SymmetricAlgorithm symm;
RSACryptoServiceProvider RSA;

if (args. length!=2)
{
Console.WriteLine (USAGE);
Return
}

Try
{
host = Args[0];
Port = Int32.Parse (args[1]);
}
Catch
{
Console.WriteLine (USAGE);
Return
}

Try//Connection
{
Client = new TcpClient ();
Client. Connect (Host,port);
}
catch (Exception e)
{
Console.WriteLine (E.message);
Console.Write (E.stacktrace);
Return
}

Try
{
Console.WriteLine ("Connected.") Sending public key. ");
RSA = new RSACryptoServiceProvider ();
Rsa. KeySize = rsa_key_size_bits;
Sendpublickey (RSA. Exportparameters (FALSE), client);
Symm = new TripleDESCryptoServiceProvider ();
Symm. KeySize = tdes_key_size_bits;

MemoryStream ms = Getrestofmessage (client);
Extractsymmetrickeyinfo (RSA, SYMM, MS);
Showsecretmessage (symm, MS);
}
catch (Exception e)
{
Console.WriteLine (E.message);
Console.Write (E.stacktrace);
}
Finally
{
Try
{
Client. Close ();
}
Catch {//error
}
}
}

private static void Sendpublickey (
RSAParameters Key,
TcpClient client)
{
NetworkStream ns = client. GetStream ();
BinaryFormatter bf = new BinaryFormatter ();
Bf. Serialize (Ns,key);
}

private static MemoryStream Getrestofmessage (TcpClient client)
{
Gets the encrypted symmetric key, initialization vector, and secret information. Public RSA key for symmetric key
Encrypted, secret information encrypted with symmetric key
MemoryStream ms = new MemoryStream ();
NetworkStream ns = client. GetStream ();
byte[] buffer = new byte[1024];

int len=0;

Writes NetStream data to a memory stream
while (len = ns. Read (buffer, 0, buffer.) Length)) >0)
{
Ms. Write (buffer, 0, Len);
}
Ms. Position = 0;
return MS;
}

private static void Extractsymmetrickeyinfo (
RSACryptoServiceProvider RSA,
SymmetricAlgorithm Symm,
MemoryStream Msorig)
{
MemoryStream ms = new MemoryStream ();

Get Tdes Key--It is encrypted by public RSA key, decrypted with private key
byte[] buffer = new Byte[tdes_key_size_bytes];
Msorig.read (Buffer,0,buffer. Length);
Symm. Key = RSA. Decrypt (Buffer,false);

Get Tdes initialization vector
Buffer = new Byte[tdes_iv_size_bytes];
Msorig.read (buffer, 0, buffer. Length);
SYMM.IV = RSA. Decrypt (Buffer,false);
}

private static void Showsecretmessage (
SymmetricAlgorithm Symm,
MemoryStream Msorig)
{
All data in the memory stream is encrypted.
byte[] buffer = new byte[1024];
int len = Msorig.read (buffer,0,buffer. Length);

MemoryStream ms = new MemoryStream ();
ICryptoTransform transform =
Symm. CreateDecryptor (symm. KEY,SYMM.IV);
CryptoStream cstream =new CryptoStream (MS, transform,
CryptoStreamMode.Write);
Cstream. Write (buffer, 0, Len);
Cstream. FlushFinalBlock ();

The memory stream is now decrypted, is the byte form, converts it to a string
Ms. Position = 0;
Len = Ms. Read (buffer,0, (int) Ms. Length);
Ms. Close ();

String msg = Encoding.ASCII.GetString (Buffer,0,len);
Console.WriteLine ("The host sent me this secret message:");
Console.WriteLine (msg);
}
}
}

It is more appropriate to encrypt local data using a symmetric algorithm. We can choose a variety of algorithms to keep the code generic, and when the data is passed through a specific CryptoStream, the algorithm uses the transform object to encrypt the data. When you need to send data over the network, you first encrypt the symmetric key with the public asymmetric key that you receive.

This article deals only with part of the System.Security.Cryptography namespaces service. Although the article guarantees that only a private key can decrypt information about the corresponding public key encryption, it does not guarantee who sent the public key and the sender may be false. You need to use a class that handles digital certificates to counter that risk.

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.