Asp.net,c# Encrypting and decrypting strings

Source: Internet
Author: User
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 secret key of the cryptographic algorithm.



The new class Cryptohelper is then used as the cryptographic helper class.

The first step is to 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>
constructor function
</summary>
Public Cryptohelper ()
{
IV = configurationmanager.appsettings["IV"];
Key = configurationmanager.appsettings["Key"];
}
}





Note Add System.Configuration.dll assembly references.



After you have obtained 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.

Here's how to get TripleDESCryptoServiceProvider:
<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 cipher object ICryptoTransform.

CreateDecryptor: Creating a symmetric decryption object ICryptoTransform

The cryptographic object and the decryption object can be used by the CryptoStream object. To encrypt and decrypt the stream.

The CryptoStream constructor is as follows:
Public CryptoStream (Stream stream, ICryptoTransform transform, CryptoStreamMode mode);

Converts a 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 ();

Create an encrypted transform stream
CryptoStream cstream = new CryptoStream (Mstream,
Provider. CreateEncryptor (), cryptostreammode.write);

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

Writes bytes to the transform stream.
Cstream.write (toencrypt, 0, toencrypt.length);
Cstream.flushfinalblock ();

After invoking the FlushFinalBlock method of the transform stream, the internal conversion is done, and the mstream is the encrypted stream.
byte[] ret = Mstream.toarray ();

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

Encode the encrypted bytes to 64.
Return convert.tobase64string (ret);
}





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

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

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

Creates a transform 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 ();

Create an encrypted transform stream
CryptoStream cstream = new CryptoStream (Mstream,

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

Writes bytes to the transform stream.
Cstream.write (toencrypt, 0, toencrypt.length);
Cstream.flushfinalblock ();

After invoking the FlushFinalBlock method of the transform stream, the internal conversion is done, and the mstream is the encrypted stream.
byte[] ret = Mstream.toarray ();

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

Encode the encrypted bytes to 64.
Return convert.tobase64string (ret);
}

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

}

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

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

Creates a transform 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 ());
}
}
}
  • Related Article

    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.