Click here to Skip to main content
15,905,915 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I am New asp.net Developer, I want some Information regarding how we can encrypt before storing into database and Decrypt data after retrieving.
Posted

You may refer to:
PWDENCRYPT (Transact-SQL)[^]
PWDCOMPARE (Transact-SQL)[^]
regarding storage and usage of passwords with MS SQL Server.
 
Share this answer
 
Hi
Encryption/Decryption can be achieved in many ways
below is one of the way.

While saving a password from c# to SQL convert it to encrypted data
and while retrieving password from sql user Decrypt method to get the actual value for processing..




C#
 public string Encrypt(string data)
        { return data.ToEncryptedData(); }
        public string Decrypt(string data)
        { return data.ToDecryptedData(); }




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;


namespace Helper
{
    public static class CryptographyAlgorithm
    {


        static string key = "CMTOOLDEMO!00000";

        public static string ToEncryptedData(this string input)
        {

            byte[] inputArray = UTF8Encoding.UTF8.GetBytes(input);
            TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
            // tripleDES.GenerateKey();
            tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key);
            tripleDES.Mode = CipherMode.ECB;
            tripleDES.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = tripleDES.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
            tripleDES.Clear();
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

        public static string ToDecryptedData(this string input)
        {
            byte[] inputArray = Convert.FromBase64String(input);
            TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
            tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key);
            tripleDES.Mode = CipherMode.ECB;
            tripleDES.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = tripleDES.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
            tripleDES.Clear();
            return UTF8Encoding.UTF8.GetString(resultArray);
        }
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900