[★]. Net-based encryption and decryption algorithm summary [2]

Source: Internet
Author: User

Encryption and decryption methods in. net

1. encryption.

Response. Redirect ("detailinfo. aspx? Id = "+ convert. tobase64string (system. Text. encoding. Default. getbytes

("Sp10006"). Replace ("+", "% 2B "));

2. decryption.

String id = system. Text. encoding. Default. getstring (convert. frombase64string (request. querystring ["ID"]. tostring (). Replace

("% 2B", "+ ")));

. Net combines the original independent API and SDK into a framework.ProgramDevelopers are very helpful. It adapted the CryptoAPI into the. NET system. Security. Cryptography

The namespace frees the cryptographic service from the mystery of the SDK platform and becomes a simple. Net namespace. As the entire framework component is shared, the cryptographic service is easier to implement.

Now, you only need to learn about the features of the system. Security. cryptography namespace and the classes used for specific solutions.

Encrypted and decryptedAlgorithm

The system. Security. cryptography namespace contains classes for implementing security solutions, such as encrypting and decrypting data, managing keys, verifying data integrity, and ensuring that data does not have

Tampered with and so on. This article focuses on encryption and decryption.

Encryption and decryption algorithms are classified into symmetric and asymmetric algorithms. Symmetric algorithms use the same key and initialization vector to encrypt and decrypt data.

Typical algorithms include des, tripledes, and Rijndael. They are suitable for encryption of local documents or data without passing keys. Asymmetric algorithms have two different secrets.

The public key and private key are used to encrypt data, while the private key is used to decrypt data. Asymmetric algorithms include RSA and DSA.

Encryption of network data.

Encrypt and decrypt local documents

The following example uses the Rijndael symmetric algorithm to encrypt and decrypt local text.

Symmetric algorithms encrypt data when data passes through. Therefore, you must first create a normal stream (such as an I/O Stream ).ArticleUse the filestream class to read text files into byte Arrays

This class is also used as the output mechanism.

Next, define the corresponding object variables. When defining the object variable of the symmetricalgorithm abstract class, we can specify any symmetric encryption algorithm provider.CodeUsed

It is the Rijndael algorithm, but it is easy to change to the DES or tripledes algorithm .. Net uses a powerful random key to set the instance of the provider. It is dangerous to select your own key,

It is a better choice to accept keys generated by computers. The code in this article uses keys generated by computers.

Next, the algorithm instance provides an object for actual data transmission. Each algorithm has two methods: createencryptor and createdecryptor.

The object of the icryptotransform interface.

Finally, the source file is read using the readbytes method of binaryreader, which returns a byte array. Binaryreader reads the input stream of the source file.

The readbytes method is called when the parameter of the cryptostream. Write method is used. The specified cryptostream instance is told that it should operate on the lower-layer stream. this object will execute data transmission regardless of the stream

Is to read or write data.

The following is the source code snippet for encrypting and decrypting a text file:

 

Namespace com. billdawson. crypto
{
Class textfilecrypt
{
Public static void main (string [] ARGs)
{
String file = ARGs [0];
String tempfile = path. gettempfilename ();
// Open the specified file
Filestream FSIN = file. Open (file, filemode. Open,
Fileaccess. Read );
Filestream fsout = file. Open (tempfile, filemode. Open,
Fileaccess. Write );
// Define symmetric algorithm object instances and interfaces
Repeated ricalgorithm symm = new rijndaelmanaged ();
Icryptotransform transform = symm. createencryptor ();
Cryptostream cstream = new cryptostream (fsout, transform,
Ryptostreammode. Write );

Binaryreader BR = new binaryreader (FSIN );
// Read the source file 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 ("will now decrypt and show contents ");

// Reverse operation -- decrypts the temporary file encrypted just now
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 only want to see a document, I will not simply send it to you via email. I will use symmetric algorithms to encrypt it. If someone intercepts it, they cannot read it either.

This document because they do not have a unique key for encryption. But you do not have a key. I need to give the key to you in some way so that you can decrypt the document, but you cannot take the key and

Risk of document being intercepted.

Asymmetric algorithms are a solution. The two keys used by these algorithms have the following relationship: Information encrypted with a public key can only be decrypted by the corresponding private key. Therefore, my first

Ask you to send me your public key. Someone may intercept it while sending it to me, but it doesn't matter, because they can only use this key to encrypt your information. I use your

The public key encryption document is sent to you concurrently.

Use a private key to decrypt the document. This is the only key that can be decrypted and is not transmitted over the network.

Asymmetric algorithms are more costly and slow than symmetric algorithms. Therefore, we do not want to encrypt all information using asymmetric algorithms in online conversations. Instead, we use symmetric algorithms. Lower

In the preceding example, asymmetric encryption is used to encrypt symmetric keys. Then we use symmetric encryption. In fact, the security Interface Layer (SSL) establishes a secure conversation between the server and the browser.

This method is used.
The example is a TCP program, which can be divided into the server side and the client side. The workflow on the server side is as follows:

Receives the public key from the client.

Use a public key to encrypt future symmetric keys.

Send the encrypted symmetric key to the client.

Send the Information encrypted with this symmetric key to the client.

The Code is 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;
// Obtain the port
Try
{
Port = int32.parse (ARGs [0]);
MSG = ARGs [1];
}
Catch
{
Console. writeline (usage );
Return;
}
// Create a listener
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;

// Obtain the public key of the Client
RSA. importparameters (getclientpublickey (client ));

Symm = new tripledescryptoserviceprovider ();
Symm. keysize = tdes_key_size_bits;

 
// Use the public key of the client to encrypt the symmetric key and send it to the client.
Encryptandsend1_rickey (client, RSA, symm );

// Use symmetric keys to encrypt and send information
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)
{
// Obtain the serialized public key from the byte stream, and convert it to the instance of the writing class through a string
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;

Byte [] inputbytearray = new byte [ptodecrypt. Length/2];
For (INT x = 0; x <ptodecrypt. Length/2; X ++)
{
Int I = (convert. toint32 (ptodecrypt. substring (x * 2, 2), 16 ));
Inputbytearray [x] = (byte) I;
}

// Create the key and offset of the encryption object. This value is important and cannot be modified.
Des. Key = asciiencoding. ASCII. getbytes (skey );
Des. IV = asciiencoding. ASCII. getbytes (skey );
Memorystream MS = new memorystream ();
Cryptostream cs = new cryptostream (MS, Des. createdecryptor (), cryptostreammode. Write );
// Flush the data through the crypto stream into the memory stream
CS. Write (inputbytearray, 0, inputbytearray. Length );
CS. flushfinalblock ();

// Get the decrypted data back from the memory stream
// Create a stringbuild object. createdecrypt uses a stream object. The decrypted text must be converted to a stream object.
Stringbuilder ret = new stringbuilder ();

Return System. Text. encoding. Default. getstring (Ms. toarray ());
}

 

2.2 example
Four steps to encrypt messages using asymmetric algorithms
1. Obtain the private key of the sender and the public key of the receiver.
2. Use random keys and Initialization vectors to encrypt messages using symmetric algorithms.
3. Use the recipient's public key to encrypt the key and initialization vector in step 2.
4. Use the sender's private key to digitally sign the message.

The corresponding decryption steps
1. Obtain the sender's public key and receiver's private key.
2. Verify the digital signature.
3. decrypt the key and initialization vector.
4. Use the decrypted key and initialization vector to decrypt the message.

Code Analysis:

1. Get the key
...{
X509certificatestore x509store = NULL;
If (location = "currentuser ")
...{
X509store = x509certificatestore. currentuserstore (x509certificatestore. mystore );
}
Else
...{
X509store = x509certificatestore. localmachinestore (x509certificatestore. mystore );
}
Bool open = x509store. openread ();
X509certificate sender_cert = NULL;
X509certificate receiver_cert = NULL;

If (! Open)
...{
Throw new exception ("unable to open the certificate store ");
}

Sender_cert = x509store. findcertificatebysubjectname ("cn = XinChen, E = none@none.com") [0];
Receiver_cert = x509store. findcertificatebysubjectname ("cn = sherry, E = none@none.com") [0];

Rsaparameters sender_privatekey = sender_cert.key.exportparameters (true );
Rsaparameters receiver_publickey = receiver_cert.publickey.exportparameters (false );
}

2. symmetric algorithm encryption (automatically generated by the system if the initial key and initial vector are not specified)
...{
Using ricalgorithm symatrix rovider = Using ricalgorithm. Create ("tripledes ");

Encryptor = symatrix rovider. createencryptor ();

Cryptostream encstream = new cryptostream (data, encryptor, cryptostreammode. Read );
Memorystream encrypted = new memorystream ();
Byte [] buffer = new byte [1024];
Int COUNT = 0;
While (COUNT = encstream. Read (buffer, 0,1024)> 0)
...{
Encrypted. Write (buffer, 0, count );
}
}
3. Use the recipient's public key to encrypt the key and initialization vector in step 2.
...{
Byte [] key;
Byte [] IV;
Rsacryptoserviceprovider asypolicricprovider = new rsacryptoserviceprovider ();
Asypolicricprovider. importparameters (receiver_publickey );

Key = asypolicricprovider. Encrypt (symatrix rovider. Key, false );
IV = asypolicricprovider. Encrypt (symatrix rovider. IV, false );
}
4. Create a digital signature
Encrypt messages using keys
...{
Byte [] signature;
Asypolicricprovider. importparameters (sender_privatekey );
Signature = asypolicricprovider. signdata (encrypted. toarray (), new sha1cryptoserviceprovider ());
}

The last output of the above four steps is encrypted, key, IV, and signature.

DEMO code for decryption:
1. Get the key
...
2. Verify the Digital Signature
...{
Asyuncricprovider. importparameters (sender_publickey );
Bool verify = asypolicricprovider. verifydata (encrypted, new sha1cryptoserviceprovider (), signature)
}
3. decrypt the key and initialization Vector
...{
Asypolicricprovider. importparameters (receiver_privatekey );
Byte [] decryptedkey = asyuncricprovider. decrypt (Key, false );
Byte [] decryptediv = asyuncricprovider. decrypt (IV, false );
}
4. Use the decrypted key and initialization vector to decrypt the message.
...{
Using ricalgorithm symatrix rovider = Using ricalgorithm. Create ("tripledes ");
Icryptotransform decryptor = symatrix rovider. createdecryptor (decryptedkey, decryptediv );
Cryptostream decstream = new cryptostream (encrypted, decryptor, cryptostreammode. Read );
}

3. Hash hash example
...{
System. Security. cryptography. hashalgorithm
System. Security. cryptography. keyedhashalgorithm
System. Security. cryptography. MD5
System. Security. cryptography. sha1
System. Security. cryptography. sha256
System. Security. cryptography. sha384
System. Security. cryptography. sha512
}
Public static string encrypt (string password)
...{
Password = password. tolower ();

Byte [] clearbytes = new unicodeencoding (). getbytes (password );

 

Byte [] hashedbytes = (hashalgorithm) cryptoconfig. createfromname ("MD5"). computehash (clearbytes );

Return bitconverter. tostring (hashedbytes );
}

 

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.