TripleDESCryptoServiceProvider 加密解密

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

namespace Mobizone.Common
{
    public class TrippleDESCSPEncrypt
    {
        //12個字符
        private static string customIV = "4vHKRj3yfzU=";
        //32個字符
        private static string customKey = "xhVs6DRXLfUGxw+AhtfQdpQGoa+8SA9d";

        /// <summary>
        /// 加密字符串
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public string EncryptPassword(string password)
        {
            string encryptPassword = string.Empty;

            SymmetricAlgorithm algorithm = new TripleDESCryptoServiceProvider();
            algorithm.Key = Convert.FromBase64String(customKey);
            algorithm.IV = Convert.FromBase64String(customIV);
            algorithm.Mode = CipherMode.ECB;
            algorithm.Padding = PaddingMode.PKCS7;

            ICryptoTransform transform = algorithm.CreateEncryptor();

            byte[] data = (new System.Text.ASCIIEncoding()).GetBytes(password);
            MemoryStream memoryStream = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write);

            cryptoStream.Write(data, 0, data.Length);
            cryptoStream.FlushFinalBlock();
            encryptPassword = Convert.ToBase64String(memoryStream.ToArray());

            memoryStream.Close();
            cryptoStream.Close();

            return encryptPassword;
        }

        /// <summary>
        /// 解密字符串
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public string DecryptPassword(string password)
        {
            string decryptPassword = string.Empty;

            SymmetricAlgorithm algorithm = new TripleDESCryptoServiceProvider();
            algorithm.Key = Convert.FromBase64String(customKey);
            algorithm.IV = Convert.FromBase64String(customIV);
            algorithm.Mode = CipherMode.ECB;
            algorithm.Padding = PaddingMode.PKCS7;

            ICryptoTransform transform = algorithm.CreateDecryptor(algorithm.Key, algorithm.IV);

            byte[] buffer = Convert.FromBase64String(password);
            MemoryStream memoryStream = new MemoryStream(buffer);
            CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Read);
            StreamReader reader = new StreamReader(cryptoStream, System.Text.Encoding.ASCII);
            decryptPassword = reader.ReadToEnd();

            reader.Close();
            cryptoStream.Close();
            memoryStream.Close();

            return decryptPassword;
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章