Implementation method of encryption and decryption in .NET.

zhaozj2021-02-17  54

.NET combines the original API and SDK into a framework, which is very advantageous for program developers. It adapted CryptoAPI into the .NET's System.Security.cryptography namespace, enabling the password service to get rid of the mystery of the SDK platform, become a simple .NET name space. Since the entire frame assembly is shared together, the password service is easier to implement, and now only needs to learn the functionality of the System.Security.cryptography name space and the class for solving a particular scenario.

Encrypted and decryption algorithms System.Security.cryptography namespace contains classes for implementing security schemes, such as encryption and decryption data, management key, verifying the integrity of data, and ensuring that data is not tampered with, and so on. This article focuses on encryption and decryption. The algorithm of encryption and decryption is divided into symmetrical algorithm and asymmetric algorithm. Symmetric algorithms use the same key and initialization vector when encrypted and decrypt data, typically DES, TRIPLEDES, and RIJNDAEL algorithms, which apply to the case where the key is not required, mainly used for local documentation or data encryption. Asymmetric algorithms have two different keys, which are public keys and private keys, and the public key is transmitted in the network, for encrypting data, and private key is used to decrypt data. Asymmetric algorithms mainly include RSA, DSA, etc., mainly for encryption of network data.

Encryption and Decryption Local Documents The following example is encrypted and decrypt local text, use RijndAel symmetrical algorithm. The symmetric algorithm encrypts it at the time of data. Therefore, a normal stream (for example, I / O flow) is required first. The article uses the FileStream class to read text files into byte arrays, and use this class as an output mechanism. Next, define the corresponding object variable. When defining an object variable of the SymmetricalGorithm abstract class, we can specify any symmetric encryption algorithm provider. The code is used by the RijndAel algorithm, but it is easy to change to the DES or TrIPLEDES algorithm. .NET uses a powerful random key to set an instance of the provider, selecting your own key is a more dangerous, accepting the computer generated by the computer is a better choice, the code in the article uses the key generated by the computer. Next, an algorithm instance provides an object to perform actual data transmission. Each algorithm has two methods for CREATEENCRYPTOR and CREATEDECRYPTOR, which returns an object that implements the Icryptotransform interface. Finally, now use BinaryReader's ReadBytes method to read the source file, it will return a byte array. BinaryReader reads the input stream of the source file and calls the Readbytes method when the parameter as the CryptostReam.write method. The specified CryptostReam instance is informatted to operate the underlying stream that will execute data transfer, whether the purpose of the flow is read or written. Below is the source program segmentation of encryption and decryption of 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); // definition of object instances and asymmetric algorithms interfaces SymmetricAlgorithm 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 (); cstract.close (); fsin.close (); fSout.close (); console.close (); console.writeline ("created encrypted file {0}" , TempFile; "Will Now Decrypt and Show Contents"); // Reverse Operation - Decrypts the temporary file fsin = file.open (TempFile, FileMode.Open, FileAccess.Read); Transform = TRANSFORM = Symm.createdecryptor (); cstract = new cryptostream (fsin, transform, cryptostreammode.read); StreamReader SR = ne W StreamReader (CSTREAM); Console.Writeline ("Decrypted File Text: Sr.ReadToeend ()); fsin.close ();}}}

Encrypted network data If I have a document I just want to see you, I will not send it to you through E-Mail. I will use the symmetric algorithm to encrypt it; if someone intercepts it, they can't read the document because they do not have the unique key for encryption. But you don't have a key. I need to use some way to give you the key so that you can decrypt the document, but you can't make the risk of the key and the document being intercepted. The asymmetric algorithm is a solution. The two keys used by such algorithms have the following relationship: information encrypted using the public key can only be decrypted by the corresponding private key. So I first shidder you send me your public key. Someone may intercept it on the way to me, but there is no relationship because they can only use this key to encrypt your information. I use your public key encrypted document and send it to you. You decrypt this document using a private key, which is the only key that can decrypt and does not pass through the network. Upymmetric algorithm algorithm calculation is much more expensive and slow. So we don't want to use asymmetric algorithms to encrypt all information in the online dialogue. Instead, we use the symmetric algorithm. In the following example we use asymmetric encryption to encrypt the symmetric key. Then use the symmetric algorithm to encrypt. This work mode is used in the actual safety interface layer (SSL) established server and browser. An example is a TCP program divided into server-side and clients. The server-side workflow is: receive public keys from the client. Use the public key to encrypt the symmetric key used in the future. Send the encrypted symmetric key to the client. Send information using the symmetric key encryption to the client. code show as below:

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 monitor 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 {r = new} tryptoserviceProvider (); rsa.keysize = RSA_KEY_SIZE_BITS; // get the client public key rsa.ImportParameters (getClientPublicKey (client)); symm = new TripleDESCryptoServiceProvider (); symm.KeySize = TDES_KEY_SIZE_BITS; // using the client's public key to encrypt a symmetric key and send it off. EncryptandSymmetrickey (Client, RSA, SYMM); // Using symmetric key encryption information and sends EncryptandsendSecretMessage (Client, SYMM, MSG);} catch (exception e) {console.writeline (E.MESSAGE); Console.writeline (E. STACKTRACE);} Finally {Try {Client.close (); listener.stop ();} catch {}; "Server EXITING ...");}}} private static}}}} private static rAparameters getClientPublicKey (TCPCLIENT Client) {// get a serialized public key from byte stream, by string and convert the write class, 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.DSERIALIZE (MS);

Ms.close ();

Return Result;

}

Private static void encryptandsendsymmetrickey

TcpClient Client,

RSacryptoServiceProvider RSA,

Symmetricalgorithm SYMM)

{

// Encrypt the 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) {// initialization vector using the symmetric key and the encrypted information sent to the client 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 client's workflow is: establish and send a public key to the server. Receive the encrypted symmetric key from the server. Decrypt the symmetric key and use it as a private asymmetric key. Receive and use asymmetric key to decrypt information. code show as below:

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 tclient (); 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); extractSymmet RickeyInfo (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) {// Get encrypted symmetrical key, initialization vector, secret information.

Symmetric key with public RSA key // encryption, secret information symmetric key encryption MemoryStream ms = new memoryStream (); networkStream ns = client.getStream (); byte [] buffer = new byte [1024]; int LEN = 0; // Write NetStream's data to memory 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 keys - it is RSA public key encryption using a private key to decrypt 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 memory flow 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); cstractream.write (buffer, 0, len); cstractream.flushfinalBlock (); // The memory stream is now decrypted information, is the form of bytes, converting it to 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); When maintaining the code, we can select a variety of algorithms that encrypt this data when the data is used through a specific CRYPTOSTREAM algorithm. The data is required to encrypt the symmetric key using the received public asymmetric key by sending the data. This article only involves a part of the service in the System.Security.cryptography name. Although the article guarantees that only a private key can decrypt the corresponding public key encryption, it does not guarantee who is sent by the public key, the sender may also be fake. You need to use classes that process digital certificates to deal with this risk.

转载请注明原文地址:https://www.9cbs.com/read-29064.html

New Post(0)