Encryption && Decryption

来源:互联网 发布:yum install wget 编辑:程序博客网 时间:2024/05/22 12:59
using System;using System.IO;using System.Security.Cryptography;using System.Text;
<span style="white-space:pre"></span>public static class Encryption{#region Fieldsprivate static stringERROR = "Error \"{0}\" is not valid";private static byte[]RGBIV = new byte[] {0x19, 0x21, 0xA5, 0xbe, 0x11, 0xFF, 0x19, 0xD1};#endregion#region Methods/// <summary>/// Decrypt the text string using the salt/// </summary>/// <param name="text">The ecnrypted string to decrypt</param>/// <param name="salt">The salt to decrypt to text string</param>public static string Decrypt(string value, string key){if (string.IsNullOrEmpty(value)){return string.Empty;}else{byte[]inputByteArray = new byte[value.Length + 1];try{byte[]byKey = System.Text.Encoding.UTF8.GetBytes(key.Substring(0, RGBIV.Length));DESCryptoServiceProviderprovider = new DESCryptoServiceProvider();inputByteArray = Convert.FromBase64String(value);MemoryStreammemory = new MemoryStream();CryptoStreamstream = new CryptoStream(memory, provider.CreateDecryptor(byKey, RGBIV), CryptoStreamMode.Write);stream.Write(inputByteArray, 0, inputByteArray.Length);stream.FlushFinalBlock();Encoding encoding = Encoding.UTF8;return encoding.GetString(memory.ToArray());}catch{return string.Format(ERROR, value);}}}/// <summary>/// Encrypt the text string using the salt/// </summary>/// <param name="text">The text to encrypt</param>/// <param name="salt">The salt encrypt the text string</param>public static string Encrypt(string value, string key){if (string.IsNullOrEmpty(value)){return string.Empty;}else{try{byte[]bykey = Encoding.UTF8.GetBytes(key.Substring(0, RGBIV.Length)),InputByteArray = Encoding.UTF8.GetBytes(value);DESCryptoServiceProviderprovider = new DESCryptoServiceProvider();MemoryStreammemory = new MemoryStream();CryptoStreamstream = new CryptoStream(memory, provider.CreateEncryptor(bykey, RGBIV), CryptoStreamMode.Write);stream.Write(InputByteArray, 0, InputByteArray.Length);stream.FlushFinalBlock();return Convert.ToBase64String(memory.ToArray());}catch{return string.Format(ERROR, value);}}}#endregion}

0 0
原创粉丝点击