C # Cryptographic Decryption string method

Source: Internet
Author: User

C # Cryptographic Decryption string method

First in Web.config | Add the following code under the app.config file:

<?xml version= "1.0"?>
<configuration>
<appSettings>
<add key= "IV" value= "sufjcemp/te="/>
<add key= "key" value= "KIPSTOILGP6FL+3GXJVMSN4IAJIZYBBT"/>
</appSettings>
</configuration>

IV: The initial vector of the cryptographic algorithm.

Key: The encryption key for the algorithm.

Next, create a new class Cryptohelper as the cryptographic help class.

First you get the IV and key from the configuration file. So the basic code is as follows:

Public class Cryptohelper
        {
            //private readonly String IV = "sufjcemp/te=";
            Private readonly string IV = String. Empty;
           //private readonly string Key = " KIPSTOILGP6FL+3GXJVMSN4IAJIZYBBT ";
            Private readonly string Key = String. Empty;

<summary>
Constructors
</summary>
Public Cryptohelper ()
{
IV = configurationmanager.appsettings["IV"];
Key = configurationmanager.appsettings["Key"];
}
}

Note adding System.Configuration.dll assembly references.

After you obtain the IV and key, you need to obtain a service class that provides cryptographic services.

Here, the use is System.Security.Cryptography; The TripleDESCryptoServiceProvider class under the namespace.

The method for obtaining TripleDESCryptoServiceProvider is as follows:

///<summary>
       ///get cryptographic service class
        ///</summary>
       ///<returns ></returns>
        Private TripleDESCryptoServiceProvider Getcryptoprovider ()
        {
             TripleDESCryptoServiceProvider Provider = new TripleDESCryptoServiceProvider ();

            Provider.iv = convert.frombase64string (IV);
            provider. Key = Convert.frombase64string (key);

            return provider;
       }

TripleDESCryptoServiceProvider Two useful methods

CreateEncryptor: Creates a symmetric cryptographic object icryptotransform.

CreateDecryptor: Create a symmetric decryption object ICryptoTransform

The cryptographic object and the decryption object can be used by the CryptoStream object. To be encrypted and decrypted by convection.

The CryptoStream constructor is as follows:

Public CryptoStream (Stream stream, ICryptoTransform transform, CryptoStreamMode mode); Convert the stream using the Transform object.

The complete cryptographic string code is as follows:

<summary>
Gets the encrypted string
</summary>
<param name= "Inputvalue" > Input value .</param>
<returns></returns>
public string Getencryptedvalue (string inputvalue)
{
TripleDESCryptoServiceProvider Provider = this. Getcryptoprovider ();

Create a memory stream to hold the encrypted stream
MemoryStream mstream = new MemoryStream ();

Creating a cryptographic transformation stream
CryptoStream cstream = new CryptoStream (Mstream,
Provider. CreateEncryptor (), cryptostreammode.write);

Gets the byte of the input string using the UTF8 encoding.
byte[] Toencrypt = new UTF8Encoding (). GetBytes (Inputvalue);

Write the bytes into the conversion stream.
Cstream.write (toencrypt, 0, toencrypt.length);
Cstream.flushfinalblock ();

After invoking the FlushFinalBlock method of the conversion stream, the interior is converted, at which point the mstream is the encrypted stream.
byte[] ret = Mstream.toarray ();

Close the streams.
Cstream.close ();
Mstream.close ();

The encrypted byte is encoded in 64.
Return convert.tobase64string (ret);
}

The decryption method is similar:

<summary>
Gets the value after decryption
</summary>
<param name= "Inputvalue" > Encrypted string .</param>
<returns></returns>
public string Getdecryptedvalue (string inputvalue)
{
TripleDESCryptoServiceProvider Provider = this. Getcryptoprovider ();

byte[] inputequivalent = convert.frombase64string (Inputvalue);

Create a memory stream to save decrypted data
MemoryStream msdecrypt = new MemoryStream ();

           //Create a transformation stream.
            CryptoStream csdecrypt = new CryptoStream ( Msdecrypt,
                                                           provider. CreateDecryptor (),
                                                           cryptostreammode.write);

Csdecrypt.write (inputequivalent, 0, inputequivalent.length);

Csdecrypt.flushfinalblock ();
Csdecrypt.close ();

Gets the string.
return new UTF8Encoding (). GetString (Msdecrypt.toarray ());
}

The complete Cryptohelper code is as follows:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Security.Cryptography;
Using System.IO;
Using System.Configuration;

Namespace WindowsFormsApplication1
{
public class Cryptohelper
{
Private readonly string IV = "sufjcemp/te=";
Private ReadOnly String IV = String. Empty;
Private readonly string Key = "KIPSTOILGP6FL+3GXJVMSN4IAJIZYBBT";
Private ReadOnly String Key = String. Empty;

Public Cryptohelper ()
{
IV = configurationmanager.appsettings["IV"];
Key = configurationmanager.appsettings["Key"];
}

<summary>
Gets the encrypted string
</summary>
<param name= "Inputvalue" > Input value .</param>
<returns></returns>
public string Getencryptedvalue (string inputvalue)
{
TripleDESCryptoServiceProvider Provider = this. Getcryptoprovider ();

Create a memory stream to hold the encrypted stream
MemoryStream mstream = new MemoryStream ();

Creating a cryptographic transformation stream
CryptoStream cstream = new CryptoStream (Mstream,

Provider. CreateEncryptor (), cryptostreammode.write);
Gets the byte of the input string using the UTF8 encoding.
byte[] Toencrypt = new UTF8Encoding (). GetBytes (Inputvalue);

Write the bytes into the conversion stream.
Cstream.write (toencrypt, 0, toencrypt.length);
Cstream.flushfinalblock ();

After invoking the FlushFinalBlock method of the conversion stream, the interior is converted, at which point the mstream is the encrypted stream.
byte[] ret = Mstream.toarray ();

Close the streams.
Cstream.close ();
Mstream.close ();

The encrypted byte is encoded in 64.
Return convert.tobase64string (ret);
}

<summary>
Getting cryptographic service Classes
</summary>
<returns></returns>
Private TripleDESCryptoServiceProvider Getcryptoprovider ()
{
TripleDESCryptoServiceProvider Provider = new TripleDESCryptoServiceProvider ();

PROVIDER.IV = convert.frombase64string (IV);
Provider. Key = Convert.frombase64string (key);

return provider;

}

<summary>
Gets the value after decryption
</summary>
<param name= "Inputvalue" > Encrypted string .</param>
<returns></returns>
public string Getdecryptedvalue (string inputvalue)
{
TripleDESCryptoServiceProvider Provider = this. Getcryptoprovider ();
byte[] inputequivalent = convert.frombase64string (Inputvalue);

Create a memory stream to save decrypted data
MemoryStream msdecrypt = new MemoryStream ();

Create a transformation stream.
CryptoStream csdecrypt = new CryptoStream (Msdecrypt,
Provider. CreateDecryptor (),
CryptoStreamMode.Write);

Csdecrypt.write (inputequivalent, 0, inputequivalent.length);
Csdecrypt.flushfinalblock ();

Csdecrypt.close ();

           //Get string.
            return new UTF8Encoding (). GetString (Msdecrypt.toarray ());
       }
   }
}

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.