`
caocao
  • 浏览: 267027 次
  • 来自: 上海
社区版块
存档分类
最新评论

Blowfish.NET的简单封装

    博客分类:
  • .NET
阅读更多

作者:caocao(网络隐士),http://www.caocao.namehttp://www.caocao.mobi
转载请注明来源:http://caocao.iteye.com/blog/96902

隐士为了在asp.net环境里应用Blowfish加密技术实现单点登录,对Blowfish.NET进行了简单的封装。要下载Blowfish.NET包可自行Google之。

闲话不多说,上代码:

c# 代码
  1. public string Decrypt(string inString,string keyString)   
  2. {   
  3.     UTF8Encoding ue = new UTF8Encoding();   
  4.     byte[] key=ue.GetBytes(keyString);   
  5.     byte[] inBuffer=ue.GetBytes(inString);   
  6.     BlowfishECB ecb=new BlowfishECB(key, 0, key.Length);   
  7.     try  
  8.     {   
  9.         inBuffer=Convert.FromBase64String(inString);   
  10.         if (inBuffer.Length % BlowfishECB.BLOCK_SIZE != 0)   
  11.         {   
  12.             return null;   
  13.         }   
  14.     }   
  15.     catch (FormatException)   
  16.     {   
  17.         return null;   
  18.     }   
  19.   
  20.     byte[] outBuffer = new byte[inBuffer.Length];   
  21.     Array.Clear(outBuffer, 0, outBuffer.Length);   
  22.     ecb.Decrypt(inBuffer,   
  23.         0,   
  24.         outBuffer,   
  25.         0,   
  26.         inBuffer.Length);   
  27.     return ue.GetString(outBuffer, 0, outBuffer.Length);   
  28. }   
  29.   
  30. public string Encrypt(string inString,string keyString)   
  31. {   
  32.     UTF8Encoding ue = new UTF8Encoding();   
  33.     byte[] key=ue.GetBytes(keyString);   
  34.     byte[] inStringBytes=ue.GetBytes(inString);   
  35.     int length=inStringBytes.Length;   
  36.     length=Convert.ToInt32(Math.Ceiling(1.0*length/BlowfishECB.BLOCK_SIZE))*BlowfishECB.BLOCK_SIZE;   
  37.   
  38.     byte[] inBuffer = new byte[length];   
  39.     byte[] outBuffer = new byte[length];   
  40.     Array.Clear(inBuffer, 0, inBuffer.Length);   
  41.     Array.Clear(outBuffer, 0, outBuffer.Length);   
  42.     Array.Copy(inStringBytes, inBuffer, inStringBytes.Length);   
  43.   
  44.     BlowfishECB ecb=new BlowfishECB(key, 0, key.Length);   
  45.     int nCount=ecb.Encrypt(inBuffer,   
  46.         0,   
  47.         outBuffer,   
  48.         0,   
  49.         inBuffer.Length);   
  50.     return Convert.ToBase64String(outBuffer);   
  51. }  

实现类似功能的PHP代码很简洁:

PHP 代码
  1. $outString=base64_encode(@mcrypt_encrypt(MCRYPT_BLOWFISH, $key, $inString, MCRYPT_MODE_ECB));   
  2. $outString=@mcrypt_decrypt(MCRYPT_BLOWFISH, $key, base64_decode($inString), MCRYPT_MODE_ECB);  

至此彻底打通PHP,asp.net之间Blowfish加密的任督二脉。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics