作者:caocao(网络隐士),http://www.caocao.name,http://www.caocao.mobi
转载请注明来源:http://caocao.iteye.com/blog/96902
隐士为了在asp.net环境里应用Blowfish加密技术实现单点登录,对Blowfish.NET进行了简单的封装。要下载Blowfish.NET包可自行Google之。
闲话不多说,上代码:
c# 代码
- public string Decrypt(string inString,string keyString)
- {
- UTF8Encoding ue = new UTF8Encoding();
- byte[] key=ue.GetBytes(keyString);
- byte[] inBuffer=ue.GetBytes(inString);
- BlowfishECB ecb=new BlowfishECB(key, 0, key.Length);
- try
- {
- inBuffer=Convert.FromBase64String(inString);
- if (inBuffer.Length % BlowfishECB.BLOCK_SIZE != 0)
- {
- return null;
- }
- }
- catch (FormatException)
- {
- return null;
- }
- byte[] outBuffer = new byte[inBuffer.Length];
- Array.Clear(outBuffer, 0, outBuffer.Length);
- ecb.Decrypt(inBuffer,
- 0,
- outBuffer,
- 0,
- inBuffer.Length);
- return ue.GetString(outBuffer, 0, outBuffer.Length);
- }
- public string Encrypt(string inString,string keyString)
- {
- UTF8Encoding ue = new UTF8Encoding();
- byte[] key=ue.GetBytes(keyString);
- byte[] inStringBytes=ue.GetBytes(inString);
- int length=inStringBytes.Length;
- length=Convert.ToInt32(Math.Ceiling(1.0*length/BlowfishECB.BLOCK_SIZE))*BlowfishECB.BLOCK_SIZE;
- byte[] inBuffer = new byte[length];
- byte[] outBuffer = new byte[length];
- Array.Clear(inBuffer, 0, inBuffer.Length);
- Array.Clear(outBuffer, 0, outBuffer.Length);
- Array.Copy(inStringBytes, inBuffer, inStringBytes.Length);
- BlowfishECB ecb=new BlowfishECB(key, 0, key.Length);
- int nCount=ecb.Encrypt(inBuffer,
- 0,
- outBuffer,
- 0,
- inBuffer.Length);
- return Convert.ToBase64String(outBuffer);
- }
实现类似功能的PHP代码很简洁:
PHP 代码
- $outString=base64_encode(@mcrypt_encrypt(MCRYPT_BLOWFISH, $key, $inString, MCRYPT_MODE_ECB));
- $outString=@mcrypt_decrypt(MCRYPT_BLOWFISH, $key, base64_decode($inString), MCRYPT_MODE_ECB);
至此彻底打通PHP,asp.net之间Blowfish加密的任督二脉。