2014年2月19日 星期三

C# 編碼 & 解碼

        //編碼
        private string Encrypt(string text)
        {
            byte[] content = Encoding.UTF8.GetBytes(text);

            string keyStr = "webgenie";     //key
            byte[] key = Encoding.UTF8.GetBytes(keyStr);
            MD5CryptoServiceProvider provider_MD5 = new MD5CryptoServiceProvider();
            byte[] byte_pwdMD5 = provider_MD5.ComputeHash(key); //hash後使得長度固定
            RijndaelManaged provider_AES = new RijndaelManaged();
            ICryptoTransform encrypt_AES = provider_AES.CreateEncryptor(byte_pwdMD5, byte_pwdMD5);

            byte[] output = encrypt_AES.TransformFinalBlock(content, 0, content.Length);
            string encryptStr = Convert.ToBase64String(output);
            return encryptStr;
        }

        //解碼
        private string Decrypt(string text)
        {
            string encryptStr = text;
            byte[] Content = Convert.FromBase64String(encryptStr);
            string keyStr = "webgenie";
            byte[] key = Encoding.UTF8.GetBytes(keyStr);
            MD5CryptoServiceProvider provider_MD5 = new MD5CryptoServiceProvider();
            byte[] byte_pwdMD5 = provider_MD5.ComputeHash(key);
            RijndaelManaged provider_AES = new RijndaelManaged();
            ICryptoTransform decrypt_AES = provider_AES.CreateDecryptor(byte_pwdMD5, byte_pwdMD5);
            byte[] decrypt = decrypt_AES.TransformFinalBlock(Content, 0, Content.Length);
            string decryptStr = Encoding.UTF8.GetString(decrypt);
            return decryptStr;
        }

標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁