Windows Phone開發之客戶端本地簡單填充加密解密

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Security.Cryptography;


//創建人:vakin  時間:2011-12-15

namespace MicroBlogForWP7.Classes.Util
{
    //將輸入的字符串轉換爲字節數組
    //然後使用ProtectedData以及預先定義的字節數組進行加密
    //加密後得到的也是一個字節數據
    //最後使用Convert.ToBase64String得到其對應的字符串

    public class Encrypt
    {
        //預先定義的字節數組如下:
        byte[] opt = new byte[] { 1, 2, 4, 8, 16 };

        /// <summary>
        /// 密碼的加密操作
        /// </summary>
        /// <param name="userpassword">未加密的密碼內容</param>
        /// <returns></returns>
        private string EncryptPwd(string userpassword)
        {
            byte[] input = System.Text.Encoding.UTF8.GetBytes(userpassword);

            string result = Convert.ToBase64String(ProtectedData.Protect(input, opt)); 

            return result;
        }

        /// <summary>
        /// 解密解碼。沒有加密的情況下返回null
        /// </summary>
        /// <param name="userpassword">加密後的密碼內容</param>
        /// <returns></returns>
        private string DecryptPwd(string userpassword)
        {
            if (string.IsNullOrEmpty(userpassword))
            {
                //沒有加密的密碼
                return null;
            }

            byte[] output = Convert.FromBase64String(userpassword);

            byte[] en = ProtectedData.Unprotect(output, opt);

            string result = System.Text.Encoding.UTF8.GetString(en, 0, en.Length);

            return result; 
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章