C # symmetric encryption (3DES) and asymmetric Encryption (RSA) algorithms

Source: Internet
Author: User

C # Implementation of 3DES encryption/decryption algorithm: (Many ways of implementation, for reference only)

public static bool DecryptFromBase64 (string base64string, String Key,out string decryptstring) {Decrypt            String = "";                try {//encode to bytes byte[] key = Hexstringtobytearray (key);                byte[] cryptstring = convert.frombase64string (base64string);                Set IV and key byte[] Tmpiv = {49, 50, 51, 52, 53, 54, 55, 56};                Byte[] Tmpkey = {0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7};                for (int II = 0; II < ii++) {Tmpkey[ii] = Key[ii];                } TripleDESCryptoServiceProvider DSP = new TripleDESCryptoServiceProvider (); Dsp.                Mode = System.Security.Cryptography.CipherMode.CBC; Dsp.                Padding = System.Security.Cryptography.PaddingMode.PKCS7; ICryptoTransform tridesencrypt = DSP.                CreateDecryptor (Tmpkey, TMPIV); Using (var ms = new MemoryStream (cryptstring))                        {using (var cs = new CryptoStream (MS, Tridesencrypt, CryptoStreamMode.Read)) {                        var sr = new StreamReader (cs, Encoding.UTF8); 2015/11/11 changes to read the entire content, rather than read the first line, this problem is the algorithm bug decryptstring = Sr. ReadToEnd ();//SR.                    ReadLine (); }} DSP.                Clear ();            return true;            } catch (Exception e) {return false;            }} public static bool Crypt3destobase64 (string cryptstring, String Key, out string decryptstring) {            decryptstring = "";                try {//encode to bytes byte[] key = Hexstringtobytearray (key);                byte[] cryptstring = System.Text.Encoding.UTF8.GetBytes (cryptstring); Set IV and key byte[] Tmpiv = {49, 50, 51, 52, 53, 54, 55, 56};                Byte[] Tmpkey = {0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7};                for (int II = 0; II < ii++) {Tmpkey[ii] = Key[ii];                } TripleDESCryptoServiceProvider DSP = new TripleDESCryptoServiceProvider (); Dsp.                Mode = System.Security.Cryptography.CipherMode.CBC; Dsp.                Padding = System.Security.Cryptography.PaddingMode.PKCS7; ICryptoTransform tridesencrypt = DSP.                CreateEncryptor (Tmpkey, TMPIV); Byte[] results = tridesencrypt. TransformFinalBlock (cryptstring, 0, cryptstring.                Length);                decryptstring = convert.tobase64string (results); Dsp.                Clear ();            return true;            } catch (Exception e) {return false; }} public static byte[] Hexstringtobytearray (string s) {byte[] bUF = new BYTE[S.LENGTH/2]; for (int i = 0; i < BUF. Length; i++) {Buf[i] = (byte) (Chr2hex (S.substring (i * 2, 1)) * 0x10 + chr2hex (s.substring (i * 2 + 1, 1)            ));        } return BUF;                    } private static Byte Chr2hex (string chr) {switch (CHR) {case "0":                return 0x00;                Case "1": Return 0x01;                Case "2": return 0x02;                Case "3": Return 0x03;                Case "4": Return 0x04;                Case "5": Return 0x05;                Case "6": Return 0x06;                Case "7": Return 0x07;                Case "8": return 0x08;                Case "9": return 0x09;                Case "A": Return 0x0a;          Case "B":          return 0x0b;                Case "C": return 0x0c;                Case "D": return 0x0d;                Case "E": Return 0x0e;            Case "F": return 0x0f;        } return 0x00; }

In the above algorithm, the key is a 48-bit string, the other is not specifically to pay attention to.

RSA encryption algorithm (implemented according to MSDN documentation):

        <summary>////Use RSA Asymmetric encryption algorithm to encrypt text content///</summary>//<param name= "Contentby TES "> Encrypted content byte array </param>//<param name=" PublicKey "> Public key </param>//<param name=" D Ooaeppadding "> Recommended for false</param>//<returns> byte[]</returns> public static after encryption byte[] R                Saencryptcontent (byte[]contentbytes,rsaparameters publickey,bool dooaeppadding) {try {                Byte[] EncryptedData; using (RSACryptoServiceProvider Provider = new RSACryptoServiceProvider ()) {provider.                    ImportParameters (PublicKey); EncryptedData = provider.                Encrypt (Contentbytes, dooaeppadding);            } return EncryptedData;            } catch (Exception e) {return null; }}///<summary>//decryption using RSA Asymmetric encryption algorithm//&LT;/SUmmary>//<param name= "cryptcontentbytes" > byte array after encryption </param>//<param name= "Privatekey" &G t; private key </param>///<param Name= "dooaeppadding" > Recommended for false</param>//<returns> decrypted content Group </returns> public Static byte[] Rsadescryptcontent (byte[]cryptcontentbytes,rsaparameters privatekey,bool DoO                aeppadding) {try {byte[] decryptdata; using (RSACryptoServiceProvider Provider = new RSACryptoServiceProvider ()) {provider.                    ImportParameters (Privatekey); Decryptdata = provider.                Decrypt (Cryptcontentbytes, dooaeppadding);            } return decryptdata;                } catch (Exception e) {Console.WriteLine (e.message);            return null; }        }

Methods for using RSA encryption/decryption algorithms:

         
Content is the string to be encrypted
byte[] contentbytes = byteconverter.getbytes (content); Byte[] encryptbytes; Byte[] decryptbytes; The number of bytes to be encrypted cannot exceed the length value of the key by 8 minus 11 (i.e.: RSACRYPTOSERVICEPROVIDER.KEYSIZE/8-one) int maxblocksize; using (RSACryptoServiceProvider provider=new RSACryptoServiceProvider ()) {maxblocksize = provide R.KEYSIZE/8-11; RSAParameters PublicKey = provider. Exportparameters (FALSE); Less than the maximum block value, directly encrypt if (Contentbytes.length <= maxblocksize) {encryptbytes = Encryptcontent (Contentbytes, PublicKey, false); } else {//chunked encryption using (MemoryStream plaintstream=new MemoryStream (Contentbytes)) using (MemoryStream cryptstream=new MemoryStream ()) { byte[] buffer = new Byte[maxblocksize]; int blockSize = plaintstream.read (buffer, 0, maxblocksize); while (blocksize>0) {byte[] Encryptblock = new Byte[blocksize]; Array.copy (buffer, encryptblock, blockSize); Byte[]encryptedblock=encryptcontent (Encryptblock,publickey,false); Cryptstream.write (encryptedblock, 0, encryptedblock.length); BlockSize = plaintstream.read (buffer, 0, maxblocksize); } encryptbytes = Cryptstream.toarray (); }}//encrypted string encryptstring = Byteconverter.getstring (encryptbytes); Console.WriteLine ("End of Encryption"); Console.ReadLine (); Console.ReadLine ();
The following is the decryption process, the decryption process will also have a length limit, can be decrypted by reference to encryption//string encryptstring = byteconverter.getstring (encryptbytes); RSAParameters Privatekey = provider. Exportparameters (TRUE); Decryptbytes = Decryptcontent (Encryptbytes, Privatekey, false); String decryptstring = Byteconverter.getstring (decryptbytes); Console.WriteLine (decryptstring); }

  

C # symmetric encryption (3DES) and asymmetric Encryption (RSA) algorithms

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.