C#Database Link String Encryption Tool

Some projects, especially WinForm or WPF projects, for small projects in the form of tools, do not want the software to flow out. Once you know the program, you will know the user name and password of our database at the first glance of the configuration file. If the external network can access it, it will be a big hassle.So in order to prevent the information from being seen after the project is leaked, we need to encrypt the link string or other important information and decrypt it when we use it.

Idea: Use two numbers to encrypt the connection string, and then use these two numbers to decrypt.

    <add key="ConfigString" value="4HsXBRNXTkeN0ZoKdEwFE501TKSqLZUyJ0Zf+C7s5+gPd1SbWBiuh4PG6jeFgcnCTFr0QFW8FN40m/S8xmQq+8srL8taMLO23z6GSmaQJoM="/>

  

Code directly:

1: Define a class that initializes the source data.

    public class ConfigInformation
    {
        private static ConfigInformation _configInformation;

        public ConfigInformation Instance
        {
            get
            {
                if (_configInformation == null)
                {
                    _configInformation = new ConfigInformation();
                }
                return _configInformation;
            }
        }
        // Database Link String Encryption and Decryption Key Value
        public static String Key = "27e167e9-2660-4bc1-bea0-c8781a9f01cb";
        public static String Vector = "8280d587-f9bf-4127-bbfa-5e0b4b672958";

    }

  

2: Encryption and decryption method:

    /// <summary>
    ///Encryption and Decryption
    /// </summary>
    public class DecryptAndEncryptionHelper
    {
        private readonly SymmetricAlgorithm _symmetricAlgorithm;
        private const String DefKey = "qazwsxedcrfvtgb!@#$%^&*(tgbrfvedcwsxqaz)(*&^%$#@!";
        private String _key = "";
        public String Key
        {
            get { return _key; }
            set
            {
                if (!String.IsNullOrEmpty(value))
                {
                    _key = value;
                }
                else
                {
                    _key = DefKey;
                }
            }
        }

        private const String DefIV = "tgbrfvedcwsxqaz)(*&^%$#@!qazwsxedcrfvtgb!@#$%^&*(";
        private String _iv = "";
        public String IV
        {
            get { return _iv; }
            set
            {
                if (!String.IsNullOrEmpty(value))
                {
                    _iv = value;
                }
                else
                {
                    _iv = DefIV;
                }
            }
        }
        public DecryptAndEncryptionHelper()
        {
            _symmetricAlgorithm = new RijndaelManaged();
        }

        public DecryptAndEncryptionHelper(String Key, String IV)
        {
            _symmetricAlgorithm = new RijndaelManaged();
            _key = String.IsNullOrEmpty(Key) ? DefKey : Key;
            _iv = String.IsNullOrEmpty(IV) ? DefIV : IV;
        }
        /// <summary>
        /// Get Key
        /// </summary>
        /// <returns>key </returns>
        private byte[] GetLegalKey()
        {
            _symmetricAlgorithm.GenerateKey();
            byte[] bytTemp = _symmetricAlgorithm.Key;
            int KeyLength = bytTemp.Length;
            if (_key.Length > KeyLength)
                _key = _key.Substring(0, KeyLength);
            else if (_key.Length < KeyLength)
                _key = _key.PadRight(KeyLength, '#');
            return ASCIIEncoding.ASCII.GetBytes(_key);
        }

        /// <summary>
        /// Get IV
        /// </summary>
        private byte[] GetLegalIV()
        {
            _symmetricAlgorithm.GenerateIV();
            byte[] bytTemp = _symmetricAlgorithm.IV;
            int IVLength = bytTemp.Length;
            if (_iv.Length > IVLength)
                _iv = _iv.Substring(0, IVLength);
            else if (_iv.Length < IVLength)
                _iv = _iv.PadRight(IVLength, '#');
            return ASCIIEncoding.ASCII.GetBytes(_iv);
        }

        /// <summary>
        /// Encrypto Encryption
        /// </summary>
        public string Encrypto(string Source)
        {
            byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);
            MemoryStream ms = new MemoryStream();
            _symmetricAlgorithm.Key = GetLegalKey();
            _symmetricAlgorithm.IV = GetLegalIV();
            ICryptoTransform encrypto = _symmetricAlgorithm.CreateEncryptor();
            CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
            cs.Write(bytIn, 0, bytIn.Length);
            cs.FlushFinalBlock();
            ms.Close();
            byte[] bytOut = ms.ToArray();
            return Convert.ToBase64String(bytOut);
        }

        /// <summary>
        /// Decrypto Decryption
        /// </summary>
        public string Decrypto(string Source)
        {
            byte[] bytIn = Convert.FromBase64String(Source);
            MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length);
            _symmetricAlgorithm.Key = GetLegalKey();
            _symmetricAlgorithm.IV = GetLegalIV();
            ICryptoTransform encrypto = _symmetricAlgorithm.CreateDecryptor();
            CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cs);
            return sr.ReadToEnd();
        }
    }

3: Use

// Get the encrypted link string and decrypt it
string enString = ConfigurationManager.AppSettings["ConfigString"];
DecryptAndEncryptionHelper helper = new DecryptAndEncryptionHelper(ConfigInformation.Key, ConfigInformation.Vector);

// Clear text
var configStr = helper.Decrypto(enString); 
return configStr;

  

This ensures at least no leakage of data.

Tags: C# Database ascii network

Posted on Mon, 09 Mar 2020 09:05:33 -0700 by spamoom