日期:2013-09-01  浏览次数:20465 次

在.net Flamework完全版中对System.Security.Cryptography名字空间下的加密类支持得很好。但在精简版中却没有提供这个名字空间中的相应的类。在用.net写Pocket PC程序的时候用的加密算法的时候确实比较麻烦。一般有两种方法来解决这个问题。OpenNetCF(www.openetcf.org)提供了System.Security.Cryptography名字空间下的各个类的模拟,但它的提供缺乏灵活性:比如在对称加密的时候,用户无法设置Padding, CipherMode等属性。而且它的提供方式和完全版的.net下的类的接口不一致,这样给用户造成困惑。另一种方法就是自己动手对cryptoAPI进行自己封装。

最近出于工作需要对MD5CryptoServiceProvider进行了实现,这个类的接口和完整版下面的接口完全一致。

Implementation of the "System.Security.Cryptography.MD5CryptoServiceProvider" class.







public sealed class MD5CryptoServiceProvider : MD5



{



public MD5CryptoServiceProvider()



{



Initialize();



m_Disposed = false;



}



public override void Initialize()



{



if (m_Disposed)



throw new ObjectDisposedException(this.GetType().FullName);



if (m_Hash != IntPtr.Zero)



{



Crypto.CryptDestroyHash(m_Hash);



}



m_Prov = Crypto.AcquireContext(ProvType.RSA_FULL);



bool retVal=Crypto.CryptCreateHash(m_Prov, (uint)CalgHash.MD5, IntPtr.Zero, 0, out m_Hash);







}



protected override void HashCore(byte[] array, int ibStart, int cbSize)



{



if (m_Disposed)



throw new ObjectDisposedException(this.GetType().FullName);



byte[] copy = (byte[]) array.Clone();



//Array.Copy(array, ibStart, copy, 0, cbSize);



bool retVal=false;



retVal=Crypto.CryptHashData(m_Hash, copy, copy.Length, 0);



}



protected override byte[] HashFinal()



{



if (m_Disposed)



throw new ObjectDisposedException(this.GetType().FullName);



byte [] data = new byte[0];



uint dataLen = 0;



uint flags = 0;



//size



bool retVal = Crypto.CryptGetHashParam(m_Hash, (uint) HashParam.HASHVAL, data, ref dataLen, flags);



if(234 == Marshal.GetLastWin32Error())//MORE_DATA = 234,



{



//data



data = new byte[dataLen];



retVal = Crypto.CryptGetHashParam(m_Hash, (uint) HashParam.HASHVAL, data, ref dataLen, flags);



}



return data;



}



protected override void Dispose(bool disposing)



{



if (!m_Disposed)



{



if (m_Hash != IntPtr.Zero)



{



bool retVal=Crypto.CryptDestroyHash(m_Hash);



m_Hash = IntPtr.Zero;



}



if(m_Prov!=IntPtr.Zero)



{



Crypto.CryptReleaseContext(m_Prov, 0);



m_Prov=IntPtr.Zero;