Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize encryption and decryption in .NET

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article is about how to implement encryption and decryption in. Net. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Net merges the original independent API and SDK into one framework, which is very beneficial to program developers. It adapts CryptoAPI into .NET 's System.Security.Cryptography namespace, making cryptographic services get rid of the mystery of the SDK platform and become a simple use of .NET namespaces. Because cryptographic services are easier to implement as the entire framework components are shared together, you only need to learn the functionality of the System.Security.Cryptography namespace and the classes used to solve a particular solution.

Algorithms for encryption and decryption

The System.Security.Cryptography namespace contains classes that implement security schemes, such as encrypting and decrypting data, managing keys, verifying data integrity and ensuring that data is not tampered with, and so on. This article focuses on encryption and decryption.

The algorithms of encryption and decryption are divided into symmetric algorithm and asymmetric algorithm. Symmetric algorithms use the same key and initialization vector when encrypting and decrypting data, such as DES, TripleDES and Rijndael algorithms. It is suitable for situations where there is no need to transfer keys, and is mainly used for local document or data encryption. The asymmetric algorithm has two different keys, namely the public key and the private key, which are passed through the network to encrypt the data, while the private key is used to decrypt the data. Asymmetric algorithms mainly include RSA, DSA and so on, which are mainly used for network data encryption.

Encrypt and decrypt local documents

The following example encrypts and decrypts local text using the Rijndael symmetric algorithm.

The symmetric algorithm encrypts the data when it is out of date. So first you need to set up a normal flow (for example, the Imax O stream). The article uses the FileStream class to read text files into a byte array, and also uses this class as the output mechanism.

Next, define the corresponding object variables. We can specify any symmetric encryption algorithm provider when defining the object variables of the SymmetricAlgorithm abstract class. The code uses the Rijndael algorithm, but it can easily be changed to the DES or TripleDES algorithm. .net uses a powerful random key to set up an instance of the provider, it is dangerous to choose your own key, and it is a better choice to accept a computer-generated key, and the code in this paper uses a computer-generated key.

Next, the algorithm example provides an object to perform the actual data transfer. Each algorithm has two methods, CreateEncryptor and CreateDecryptor, which return the object that implements the ICryptoTransform interface.

Finally, the source file is now read using BinaryReader's ReadBytes method, which returns an array of bytes. BinaryReader reads the input stream of the source file and calls the ReadBytes method when it is an argument to the CryptoStream.Write method. The specified CryptoStream instance is told the lower flow it should operate on, and the object will perform data transfer, regardless of whether the stream is intended to read or write.

Here is a snippet of the source program that encrypts and decrypts 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

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 ()

Cstream.Close ()

FsIn.Close ()

FsOut.Close ()

Console.WriteLine ("created encrypted file {0}", tempfile)

Console.WriteLine ("will now decrypt and show contents")

/ / reverse operation-decrypt the temporary file that has just been 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 only want to see, I won't simply send it to you via e-mail. I'll encrypt it using a symmetric algorithm; 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 you can't risk the key and the document being intercepted.

Asymmetric algorithm is one kind of solution. The relationship between the two keys used by such algorithms is as follows: information encrypted with 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 the information given to you. 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.

Asymmetric algorithm is more expensive and slower than symmetric algorithm. Therefore, we do not want to use asymmetric algorithms to encrypt all information in online conversations. Instead, we use a symmetric algorithm. In the following example, we use asymmetric encryption to encrypt symmetric keys. Then the symmetric algorithm is used to encrypt it. In fact, this is how the secure Interface layer (SSL) establishes a secure conversation between the server and the browser.

The example is a TCP program, divided into server-side and client-side. The server-side workflow is as follows:

Receive a public key from the client.

Use a public key to encrypt symmetric keys for future use.

Sends the encrypted symmetric key to the client.

Information encrypted using the symmetric key is sent to the client.

The code is as follows:

The copy 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

/ / get the port

Try

{

Port = Int32.Parse (args [0])

Msg = args [1]

}

Catch

{

Console.WriteLine (USAGE)

Return

}

/ / set up 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

/ / obtain the client public key

Rsa.ImportParameters (getClientPublicKey (client))

Symm = new TripleDESCryptoServiceProvider ()

Symm.KeySize = TDES_KEY_SIZE_BITS

/ / encrypt the symmetric key using the client's public key and send it to the guest.

EncryptAndSendSymmetricKey (client, rsa, symm)

/ / encrypt the information using a symmetric key and send it

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)

{

/ / get the serialized public key from the byte stream, and write the instance of the class through serial-parallel conversion

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 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)

{

/ / encrypt information using symmetric keys and initialization vectors and send it 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 workflow of the client is:

Establish and send a public key to the server.

The encrypted symmetric key is received from the server.

Decrypt the symmetric key and treat it as a private asymmetric key.

Receive and decrypt the information using an asymmetric key.

The code is as follows:

The copy code is 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.Lengthwaters 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)

{

/ / get encrypted symmetric key, initialization vector, secret information. Public RSA keys for symmetric keys

/ / encryption. Secret information is encrypted with a symmetric key.

MemoryStream ms = new MemoryStream ()

NetworkStream ns = client.GetStream ()

Byte [] buffer = new byte [1024]

Int len=0

/ / write NetStream data to the 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 the TDES key-it is encrypted by the public RSA key and decrypted using the 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 decrypting the information, in the form of bytes, and converting 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 use symmetric algorithms to encrypt local data. We can choose a variety of algorithms while keeping the code generic, and the algorithm uses a transformation object to encrypt the data as it passes through a particular CryptoStream. When you need to send data over the network, you first encrypt the symmetric key using the received public asymmetric key.

Thank you for reading! This is the end of the article on "how to implement encryption and decryption in .NET". I hope the above content can be of some help to you, so that you can learn more knowledge. If you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report