TripleDES加解密字符

TripleDES加解密,解决解密后字符缺失问题
不然解密后字符和加密前的字符可能存在不一致

using System.Security.Cryptography;
using System.Text;

namespace TripleDES.Expand
{
    public static class TripleDESClass
    {
        const string defaultKey  = "*************************";
        const string defaultIV = "********";

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="text"></param>
        /// <param name="key"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        public static string EncryptText(string text, string key = defaultKey, string iv = defaultIV)
        {
            try
            {
                var data = EncryptTextToMemory(text, Convert.FromBase64String(key), Convert.FromBase64String(iv));

                return Convert.ToBase64String(data);
            }
            catch (Exception)
            {
                return string.Empty;
            }
            
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="text"></param>
        /// <param name="key"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        public static string DecryptText(string text, string key = defaultKey, string iv = defaultIV)
        {
            try
            {
                var array = Convert.FromBase64String(text);

                return DecryptTextFromMemory(array, Convert.FromBase64String(key), Convert.FromBase64String(iv));

            }
            catch (Exception )
            {
                return string.Empty;
            }
        }


        public static void Sample()
        {
            try
            {
                // Create a new TripleDES object to generate a key
                // and initialization vector (IV).  Specify one
                // of the recognized simple names for this
                // algorithm.
                TripleDES TripleDESalg = TripleDES.Create("TripleDES");

                // Create a string to encrypt.
                string sData = "Here is some data to encrypt.";

                // Encrypt the string to an in-memory buffer.
                byte[] Data = EncryptTextToMemory(sData, TripleDESalg.Key, TripleDESalg.IV);

                // Decrypt the buffer back to a string.
                string Final = DecryptTextFromMemory(Data, TripleDESalg.Key, TripleDESalg.IV);

                // Display the decrypted string to the console.
                Console.WriteLine(Final);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }


        private static byte[] EncryptTextToMemory(string Data, byte[] Key, byte[] IV)
        {
            try
            {
                // Create a MemoryStream.
                MemoryStream mStream = new MemoryStream();

                // Create a new TripleDES object.
                TripleDES tripleDESalg = TripleDES.Create();
                // Create a CryptoStream using the MemoryStream
                // and the passed key and initialization vector (IV).
                CryptoStream cStream = new CryptoStream(mStream,
                    tripleDESalg.CreateEncryptor(Key, IV),
                    CryptoStreamMode.Write);

                // Convert the passed string to a byte array.
                byte[] toEncrypt = new ASCIIEncoding().GetBytes(Data);

                // 不足8个字节倍数补空字节,预防不足8字节倍数解码后缺失数据问题
                var flushLength = toEncrypt.Length % 8;
                if (flushLength != 0)
                {
                    var toEncryptList = toEncrypt.ToList();
                    toEncryptList.AddRange(new byte[8 - flushLength]);
                    toEncrypt = toEncryptList.ToArray();
                }

                // Write the byte array to the crypto stream and flush it.
                cStream.Write(toEncrypt, 0, toEncrypt.Length);
                cStream.FlushFinalBlock();

                // Get an array of bytes from the
                // MemoryStream that holds the
                // encrypted data.
                byte[] ret = mStream.ToArray();

                // Close the streams.
                cStream.Close();
                mStream.Close();

                // Return the encrypted buffer.
                return ret;
            }
            catch (CryptographicException e)
            {
                Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
                return null;
            }
        }

        private static string DecryptTextFromMemory(byte[] Data, byte[] Key, byte[] IV)
        {
            try
            {
                // Create a new MemoryStream using the passed
                // array of encrypted data.
                MemoryStream msDecrypt = new MemoryStream(Data);

                // Create a new TripleDES object.
                TripleDES tripleDESalg = TripleDES.Create();

                // Create a CryptoStream using the MemoryStream
                // and the passed key and initialization vector (IV).
                CryptoStream csDecrypt = new CryptoStream(msDecrypt,
                    tripleDESalg.CreateDecryptor(Key, IV),
                    CryptoStreamMode.Read);

                // Create buffer to hold the decrypted data.
                byte[] fromEncrypt = new byte[Data.Length];

                // Read the decrypted data out of the crypto stream
                // and place it into the temporary buffer.
                csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

                // Close the streams.
                csDecrypt.Close();
                msDecrypt.Close();

                //Convert the buffer into a string and return it.
                //移除空白字节
                return new ASCIIEncoding().GetString(fromEncrypt).TrimEnd('\0');
            }
            catch (CryptographicException e)
            {
                Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
                return null;
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值