本文整理汇总了C#中CipherMode类的典型用法代码示例。如果您正苦于以下问题:C#CipherMode类的具体用法?C#CipherMode怎么用?C#CipherMode使用的例子?这里精选的类代码示例或许可以为您提供帮助。
示例1:Decrypt
//DecryptabytearrayintoabytearrayusingakeyandanIV
publicstaticbyte[]Decrypt(byte[]cipherData,byte[]Key,byte[]IV,CipherModecipherMode,PaddingModepaddingMode)
{
//CreateaMemoryStreamthatisgoingtoacceptthe
//decryptedbytes
MemoryStreamms=newMemoryStream();
//Createasymmetricalgorithm.
//WearegoingtouseRijndaelbecauseitisstrongand
//availableonallplatforms.
//Youcanuseotheralgorithms,todososubstitutethenext
//linewithsomethinglike
//TripleDESalg=TripleDES.Create();
Rijndaelalg=Rijndael.Create();
//NowsetthekeyandtheIV.
//WeneedtheIV(InitializationVector)becausethealgorithm
//isoperatinginitsdefault
//modecalledCBC(CipherBlockChaining).TheIVisXORedwith
//thefirstblock(8byte)
//ofthedataafteritisdecrypted,andtheneachdecrypted
//blockisXORedwiththeprevious
//cipherblock.Thisisdonetomakeencryptionmoresecure.
//ThereisalsoamodecalledECBwhichdoesnotneedanIV,
//butitismuchlesssecure.
alg.Mode=cipherMode;
alg.Padding=paddingMode;
alg.Key=Key;
alg.IV=IV;
//CreateaCryptoStreamthroughwhichwearegoingtobe
//pumpingourdata.
//CryptoStreamMode.Writemeansthatwearegoingtobe
//writingdatatothestream
//andtheoutputwillbewrittenintheMemoryStream
//wehaveprovided.
CryptoStreamcs=newCryptoStream(ms,
alg.CreateDecryptor(),CryptoStreamMode.Write);
//Writethedataandmakeitdothedecryption
cs.Write(cipherData,0,cipherData.Length);
//Closethecryptostream(ordoFlushFinalBlock).
//Thiswilltellitthatwehavedoneourdecryption
//andthereisnomoredatacomingin,
//anditisnowagoodtimetoremovethepadding
//andfinalizethedecryptionprocess.
cs.Close();
//NowgetthedecrypteddatafromtheMemoryStream.
//SomepeoplemakeamistakeofusingGetBuffer()here,
//whichisnottherightway.
byte[]decryptedData=ms.ToArray();
returndecryptedData;
}
原文链接:
http://www.jxszl.com/biancheng/C/556747.html