[C#] 簡單將字串做DES加解密

  • 484
  • 0

簡單將字串做DES加解密

Key、IV自己設變數

using System.Security.Cryptography;
using System.IO;

public satic class Secret
{
    const string Key = "KeyValue";
    const string IV = "InitialVector";

    public static string EncryptValue(this string StringValue)
    {
        byte[] buffer = Encoding.UTF8.GetBytes(StringValue);
        MemoryStream ms = new MemoryStream();
        DESCryptoServiceProvider tdes = new DESCryptoServiceProvider();
        CryptoStream encStream = new CryptoStream(ms, tdes.CreateDecryptor(Encoding.UTF8.GetBytes(Key), Encoding.UTF8.GetBytes(IV)), CryptoStreamMode.Write);
        encStream.Write(buffer, 0, buffer.Length);
        encStream.FlushFinalBlock();
        return Convert.ToBase64String(ms.ToArray());
    }

    public static string DecryptValue(this string EncryptStringValue)
    {
        byte[] buffer = Convert.FromBase64String(EncryptStringValue);
        MemoryStream ms = new MemoryStream();
        DESCryptoServiceProvider tdes = new DESCryptoServiceProvider();
        CryptoStream encStream = new CryptoStream(ms, tdes.CreateDecryptor(Encoding.UTF8.GetBytes(Key), Encoding.UTF8.GetBytes(IV)), CryptoStreamMode.Write);
        encStream.Write(buffer, 0, buffer.Length);
        encStream.FlushFinalBlock();
        return Encoding.UTF8.GetString(ms.ToArray());
    }
}