. NET encryption and decryption--symmetric encryption

Source: Internet
Author: User
Tags decrypt key string



One, the idea

Symmetric encryption contains a thing known as a key, before the message is sent using a key to encrypt the message, get ciphertext and send, the receiver receives the ciphertext, using the same key to decrypt, to obtain the original message.

PS : The process of encrypting a message with a key, which is done by a cryptographic algorithm, is usually public.



Two, the process of symmetric encryption

1 , the sender and receiver hold the same key and are strictly confidential

2 , the sender encrypts the message using the key, and then sends the message

3 , the receiving party decrypts the message with the same key after it receives the message

PS: in this process, third parties may intercept messages, but get the knowledge of a bunch of garbled




Three, Demo


Using system;using system.collections.generic;using system.linq;using system.text;using System.Security.Cryptography;            Note introducing this namespace using system.io;namespace symmetric encryption and decryption {class Program {static void Main (string[] args) {  String key = "Secret key";  Key string plaintext = "Hello,world";  PlainText string encryptedtext = Symmetriccryptohelper.encrypt (plaintext, key);            Encryption Console.WriteLine (ENCRYPTEDTEXT);  String cleartext = Symmetriccryptohelper.decrypt (Encryptedtext, key);            Decryption Console.WriteLine (cleartext);        Console.readkey (); }}///<summary>///symmetric encryption Help class///</summary>//<remarks>editor:v-liuhch createtime:2015 /5/15 22:05:41</remarks> public class Symmetriccryptohelper {//symmetric cryptographic algorithm provider private ICRYPTOTRANSF        ORM encryptor;//Cipher Object Private ICryptoTransform decryptor;//decryption Object Private Const int buffersize = 1024; <summary>//Initializes a new instance of the <see cref= "Symmetriccryptohelper"/> class. </summary>//<param name= "Algorithmname" >name of the algorithm.</param>//<para M name= "key" >the key.</param>//<remarks>Editor:v-liuhch</remarks> public SYMMETRICCR  Yptohelper (String algorithmname, byte[] key) {//symmetricalgorithm is the base class for the symmetric algorithm SymmetricAlgorithm            Provider = Symmetricalgorithm.create (Algorithmname); Provider. Key = key;//Specifies the key, typically 128-bit or 196-bit PROVIDER.IV = new byte[] {0x12,0x34,0x56,0x78,0x90,0xab,0xcd,0xef};//initializa tion vector, initialization vectors, avoids the related part of the text after the encryption is also a repetition problem, usually 64-bit encryptor = provider. CreateEncryptor ();//Create an Encryption object decryptor = provider. CreateDecryptor ();//Create decryption Object} public Symmetriccryptohelper (byte[] key): This ("TripleDES", key) {}/ /encryption algorithm//<summary>//encrypts the SPECIFied clear text. </summary>//<param name= "cleartext" >the clear text.</param>//<returns>syst Em. string.</returns>//<remarks>editor:v-liuhch CREATETIME:2015/5/17 16:56:15</remarks> Pub Lic string Encrypt (String cleartext) {//create clear Text stream byte[] Clearbuffer = Encoding.UTF8.GetBytes (            cleartext);            MemoryStream clearStream = new MemoryStream (clearbuffer);            Creates an empty ciphertext stream MemoryStream Encryptedstream = new MemoryStream (); /* Encryption decryption involves two streams, one is clear flow, one is a cipher stream so there must be a mediator, the clear flow into the ciphertext stream, or the ciphertext flow into the clear stream; * The broker performing this operation in. NET is a stream type called Cryptostre AM; * * Constructor parameters when encrypting: * 1,stream: Ciphertext stream (at this time the ciphertext stream does not contain data, just an empty stream); * 2,icry            Ptotransform: The created cipher, which is responsible for cryptographic computations, * 3, enumeration: Write, writes the plaintext stream flowing through CryptoStream to the ciphertext stream, and finally obtains the encrypted data from the ciphertext stream */ CryptoStream cryptostream = new CryptoStream (Encryptedstream, Encryptor, CryptoStreamMode.Write);            Writes the plaintext stream to buffer//writes data in buffer to CryptoStream int bytesread = 0;            byte[] buffer = new Byte[buffersize];                do {bytesread = clearstream.read (buffer, 0, buffersize);                            Cryptostream.write (buffer, 0, bytesread);            } while (bytesread>0);            Cryptostream.flushfinalblock ();//clear buffer//Get encrypted text after buffer = Encryptedstream.toarray ();            String encryptedtext = convert.tobase64string (buffer);                return encryptedtext; }///<summary>//decryption algorithm//</summary>//<param name= "en Cryptedtext ">the encrypted text.</param>//<returns>System.String.</returns>//< Remarks>editor:v-liuhch createtime:2015/5/17 16:56:22</remarks> public string Decrypt (string encryptedtext )        {           byte[] Encryptedbuffer = convert.frombase64string (encryptedtext);            Stream Encryptedstream = new MemoryStream (encryptedbuffer);            MemoryStream clearStream = new MemoryStream ();              /* When decrypting the constructor parameter: * 1,stream: Ciphertext stream (at this time the ciphertext stream contains data); * 2,icryptotransform: The decryption device created, responsible for the decryption calculation, * 3, enumeration: Write, the ciphertext stream of data read out into the clear stream, and then converted to clear text, the original format */CryptoStream cryptostream = new Cry            Ptostream (Encryptedstream, Decryptor, CryptoStreamMode.Read);            int bytesread = 0;            byte[] buffer = new Byte[buffersize];                do {bytesread = cryptostream.read (buffer, 0, buffersize);            Clearstream.write (buffer, 0, bytesread);            } while (bytesread>0);            Buffer = Clearstream.getbuffer ();            String cleartext = Encoding.UTF8.GetString (buffer, 0, (int) clearstream.length);                        return cleartext; }//<summAry>//Encrypts the specified clear text. </summary>//<param name= "cleartext" >the clear text.</param>//<param name= "key ">the key.</param>//<returns>System.String.</returns>//<remarks>editor:v-li            UHCH createtime:2015/5/17 16:56:40</remarks> public static string Encrypt (String cleartext, string key) {            byte[] KeyData = new BYTE[16];            byte[] SourceData = Encoding.Default.GetBytes (key);            int copybytes = 16;                            if (sourcedata.length<16) {copybytes = Sourcedata.length;            } array.copy (SourceData, KeyData, copybytes);            Symmetriccryptohelper helper = new Symmetriccryptohelper (keyData); Return helper.        Encrypt (cleartext);        }///<summary>//Decrypts the specified encrypted text. </summary>//<param Name= "Encryptedtext" >the encrypted text.</param>//<param name= "key" >the key.</param> <returns>System.String.</returns>//<remarks>editor:v-liuhch CREATETIME:2015/5/17 16:56:4  4</remarks> public static string Decrypt (string encryptedtext, String key) {byte[] KeyData            = new BYTE[16];            byte[] SourceData = Encoding.Default.GetBytes (key);            int copybytes = 16;            if (sourcedata.length<16) {copybytes = Sourcedata.length;            } array.copy (SourceData, KeyData, copybytes);            Symmetriccryptohelper helper = new Symmetriccryptohelper (keyData); Return helper.        Decrypt (Encryptedtext); }        }}





Four, hidden problems


1 , both the sender and the receiver need to hold the key and ensure that the key is not compromised.

2 , if a third party illegally obtains the key, after tampering with the message, it is re-encrypted to the receiver, and the receiver cannot discern. Since there is no way to tell if a message has been tampered with, it is not possible to determine who sent the message, which is not sufficient for completeness and authentication.











. NET encryption and decryption-symmetric 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.