博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C# string自己加密解密

Posted on 2009-04-30 08:33  linFen  阅读(2154)  评论(0编辑  收藏  举报
用.net framework的确有很多现成的加密解密类,但为了更灵活以及更安全对字符串加密解密,可以把string 转换成char后用自己的方法加密解密。

using System;
using System.Text;

namespace SetPassword
{
 /// <summary>
 /// .net 密码加密
 /// </summary>
 class CbsPassword
 {

  [STAThread]
  static void Main(string[] args)
  {
   string pwd = "hello你好啊";

   Console.WriteLine("原字符串:" + pwd + "," + pwd.Length.ToString());
   Console.WriteLine("字符串加密:" + StringEncoding(pwd) + "," + StringEncoding(pwd).Length.ToString());
   Console.WriteLine("字符串解密:" + StringDecoding(StringEncoding(pwd)) + "," + StringDecoding(StringEncoding(pwd)).Length.ToString());

   Console.ReadLine();
  }

  static string StringEncoding(string pwd)
  {
   char [] arrChar = pwd.ToCharArray();
   string strChar = "";
   for(int i = 0;i < arrChar.Length;i++)
   {
    arrChar[i] = Convert.ToChar(arrChar[i]+1);
    strChar = strChar + arrChar[i].ToString();
   }
   return strChar;
  }

  static string StringDecoding(string pwd)
  {
   char [] arrChar = pwd.ToCharArray();
   string strChar = "";
   for(int i = 0;i < arrChar.Length;i++)
   {
    arrChar[i] = Convert.ToChar(arrChar[i]-1);
    strChar = strChar + arrChar[i].ToString();
   }
   return strChar;
  }

 }
}