C#暗号化

3059 ワード


using System;

using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text;
namespace ConsoleApplication1 {
public class Crypt
{
    static private readonly SymmetricAlgorithm MobjCryptoService = new DESCryptoServiceProvider();
    private const string Key = "               ";
    private const string IVKey = "E5ghj*Ghg7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk";

    /// <summary>   
    ///       IV   
    /// </summary>   
    /// <returns>    IV</returns>   
    static private byte[] GetLegalIV()
    {
        string sTemp = IVKey;
        MobjCryptoService.GenerateIV();
        byte[] bytTemp = MobjCryptoService.IV;
        int IVLength = bytTemp.Length;
        if (sTemp.Length > IVLength)
            sTemp = sTemp.Substring(0, IVLength);
        else if (sTemp.Length < IVLength)
            sTemp = sTemp.PadRight(IVLength, ' ');
        return ASCIIEncoding.ASCII.GetBytes(sTemp);
    }
    /// <summary>   
    ///        
    /// </summary>   
    /// <param name="Source">     </param>   
    /// <returns>      </returns>   
    static public string Encrypto(string Source)
    {
        byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);
        MemoryStream ms = new MemoryStream();
        MobjCryptoService.Key = GetLegalKey();
        MobjCryptoService.IV = GetLegalIV();
        ICryptoTransform encrypto = MobjCryptoService.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>   
    ///        
    /// </summary>   
    /// <param name="Source">     </param>   
    /// <returns>      </returns>   
    static public string Decrypto(string Source)
    {
        byte[] bytIn = Convert.FromBase64String(Source);
        MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length);
        MobjCryptoService.Key = GetLegalKey();
        MobjCryptoService.IV = GetLegalIV();
        ICryptoTransform encrypto = MobjCryptoService.CreateDecryptor();
        CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);
        StreamReader sr = new StreamReader(cs);
        return sr.ReadToEnd();
    }

    static private byte[] GetLegalKey()
    {

        string sTemp = Key;

        MobjCryptoService.GenerateKey();

        byte[] bytTemp = MobjCryptoService.Key;

        int KeyLength = bytTemp.Length;

        if (sTemp.Length > KeyLength)

            sTemp = sTemp.Substring(0, KeyLength);

        else if (sTemp.Length < KeyLength)

            sTemp = sTemp.PadRight(KeyLength, ' ');

        return ASCIIEncoding.ASCII.GetBytes(sTemp);

    }

}

}