• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
激情 希望 斗志昂扬
Records of growth process 专注微软技术
博客园    首页    新随笔    联系   管理    订阅  订阅

DESCryptoServiceProvider 类加密和解密

using System.Security.Cryptography;
        
/// <summary>
        
/// 加密
        
/// </summary>
        
/// <param name="pToEncrypt"></param>
        
/// <param name="sKey"></param>
        
/// <returns></returns>
        public string Encrypt(string pToEncrypt, string sKey)
        {
            DESCryptoServiceProvider des 
= new DESCryptoServiceProvider();
            
byte[] inputByteArray = Encoding.GetEncoding("UTF-8").GetBytes(pToEncrypt);

            
//建立加密对象的密钥和偏移量 
            
//原文使用ASCIIEncoding.ASCII方法的GetBytes方法 
            
//使得输入密码必须输入英文文本 
            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            des.IV 
= ASCIIEncoding.ASCII.GetBytes(sKey);
            MemoryStream ms 
= new MemoryStream();
            CryptoStream cs 
= new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);

            cs.Write(inputByteArray, 
0, inputByteArray.Length);
            cs.FlushFinalBlock();

            StringBuilder ret 
= new StringBuilder();
            
foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat(
"{0:X2}", b);
            }
            ret.ToString();
            
return ret.ToString();
        }
        
/// <summary>
        
/// 解密
        
/// </summary>
        
/// <param name="pToDecrypt"></param>
        
/// <param name="sKey"></param>
        
/// <returns></returns>
        public string Decrypt(string pToDecrypt, string sKey)
        {
                DESCryptoServiceProvider des 
= new DESCryptoServiceProvider();

                
byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
                
for (int x = 0; x < pToDecrypt.Length / 2; x++)
                {
                    
int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
                    inputByteArray[x] 
= (byte)i;
                }

                des.Key 
= ASCIIEncoding.ASCII.GetBytes(sKey);
                des.IV 
= ASCIIEncoding.ASCII.GetBytes(sKey);
                MemoryStream ms 
= new MemoryStream();
                CryptoStream cs 
= new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 
0, inputByteArray.Length);
                cs.FlushFinalBlock();

                StringBuilder ret 
= new StringBuilder();

                
return System.Text.Encoding.Default.GetString(ms.ToArray());
        }
详见http://msdn.microsoft.com/zh-cn/community/system.security.cryptography.descryptoserviceprovider.aspx
posted @ 2009-05-01 14:14  贤  阅读(1280)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3