文字列の暗号化
文字列を暗号可・復号するクラスです。
http://www.microsoft.com/japan/msdn/thisweek/300x10/phase2/encrypt/cs.aspxを参考につくりました。
共有キーと初期化ベクタは適当に変更してください。
using System.Text; using System.Security.Cryptography; using System.IO; using System.Collections;
class Crypto { // 共有キー private byte[] desKey = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, }; // 初期化ベクタ private byte[] desIV = { 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10, 0x0F, 0x0E, 0x0D, 0x0C, 0x0B, 0x0A, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00, }; internal class Crypto { // 共有キー private byte[] desKey = new byte[] { 0xE1, 0x43, 0xB4, 0x78, 0xD6, 0x84, 0x60, 0xD4, 0xB2, 0xF3, 0x78, 0x0B, 0x84, 0x43, 0xD2, 0x52, 0x09, 0x8E, 0xA3, 0x0B, 0xA4, 0x9A, 0x49, 0x7E, }; // 初期化ベクタ private byte[] desIV = new byte[] { 0xCA, 0x58, 0xBE, 0x60, 0x75, 0x6E, 0xDF, 0xD9, 0x5F, 0xE5, 0x28, 0x02, 0xAC, 0x27, 0x64, 0xE5, 0x7A, 0xA5, 0x54, 0x78, 0xC3, 0x5A, 0xD4, 0x43, }; private TripleDESCryptoServiceProvider des; internal Crypto() { des = new TripleDESCryptoServiceProvider(); } /// <summary> /// 文字列を暗号化する。 /// </summary> /// <param name="text">暗号化する文字列。</param> /// <returns>暗号化結果。</returns> internal byte[] Encrypto(string text) { byte[] source = Encoding.Unicode.GetBytes(text); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write); cs.Write(source, 0, source.Length); cs.Close(); byte[] cryptData = ms.ToArray(); ms.Close(); return cryptData; } /// <summary> /// 復号する。 /// </summary> /// <param name="source">暗号データ。</param> /// <returns>復号した文字列。</returns> internal string Decrypto(byte[] source) { MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write); cs.Write(source, 0, source.Length); cs.Close(); byte[] destination = ms.ToArray(); ms.Close(); return Encoding.Unicode.GetString(destination); } } /// <summary> /// 暗号用の拡張。 /// </summary> static public class CryptExpand { static private Crypto cripto = null; // シングルトン /// <summary> /// シングルトンオブジェクトを取得する。 /// </summary> static private Crypto Crypt { get { if (cripto == null) cripto = new Crypto(); return cripto; } } /// <summary> /// 文字列を暗号化する。 /// </summary> /// <param name="text"></param> /// <returns>暗号化したバイトの配列。</returns> static public ArrayList Encrypt(this string text) { return new ArrayList(Crypt.Encrypto(text)); } /// <summary> /// 暗号を復号する。 /// </summary> /// <param name="list">暗号。</param> /// <returns>復号した文字列。</returns> static public string Decrypto(this ArrayList list) { int count = list.Count; byte[] buf = new byte[count]; for (int i = 0; i < count; i++) buf[i] = (byte)list[i]; return Crypt.Decrypto(buf); } } }
こういう風に使います*1。
password = password.Encrypt(); password = password.Decrypto();
*1:うーむ。ひどいな。まあ、あとで