SoFunction
Updated on 2025-03-07

C# implements simple string encryption

Recently, some string encryption has been used, and the encryption algorithm provided in .net is more complicated to use, so it is simply encapsulated, making it convenient for future use.

    public class Encrypt
    {
        static Encoding encoding = Encoding.UTF8;

        public static string EncryptDES(string encryptString, string key)
        {
            var input = (encryptString);
            var ouptputData = ProcessDES(input, key, true);
            var outputStr = Convert.ToBase64String(ouptputData);

            //There is a '/' symbol in the base64 encoding that cannot be used as the file name. Replace it here to enhance the scope of application            return ('/', '@');
        }

        public static string DecryptDES(string decryptString, string key)
        {
            decryptString = ('@', '/');

            var input = Convert.FromBase64String(decryptString);
            var data = ProcessDES(input, key, false);
            return (data);
        }


        private static byte[] ProcessDES(byte[] data, string key, bool isEncrypt)
        {
            using (var dCSP = new DESCryptoServiceProvider())
            {
                var keyData = Md5(key);
                var rgbKey = new ArraySegment<byte>(keyData, 0, 8).ToArray();
                var rgbIV = new ArraySegment<byte>(keyData, 8, 8).ToArray();
                var dCSPKey = isEncrypt ? (rgbKey, rgbIV) : (rgbKey, rgbIV);

                using (var memory = new MemoryStream())
                using (var cStream = new CryptoStream(memory, dCSPKey, ))
                {
                    (data, 0, );
                    ();
                    return ();
                }
            }
        }

        public static byte[] Md5(string str)
        {
            using (var md5 = ())
            {
                return (Encoding.(str));
            }
        }
    }

This package supports MD5 and DES encryption (replace RSA if you have time), and is used for string encryption. The main consideration is to be easy to use and does not pursue optimal efficiency. The following two optimizations have been made for the convenience of use:

  • The key is in a string form, without length limit

  • The string output after encryption is a modified form of Base64, which can be used for file names

This is all about this article about C# implementing string encryption. I hope it will be helpful to everyone's learning and I hope everyone will support me more.