还剩7页未读,继续阅读
文本内容:
对称加密之AES及压缩加密解密解压综合实战对称加密:就是采用这种加密方法的双方使用方式用同样的密钥进行加密和解密密钥是控制加密及解密过程的指令算法是一组规则,规定如何进行加密和解宓LJjO因此加密的安全性不仅取决于加密算法本身,密钥管理的安全性更是重要因为加密和解密都使用同一个密钥,如何把密钥安全地传递到解密者手上就成了必须要解决的问题由此可见密钥传递也是比较重要的一环,一般都是通过对密钥二次加密的方式,进行密钥的传输加密实现代码publicstaticbyte口encryptStringToBytesAESbyte口fileContentBytesbyte口Keybyte口IV//Checkarguments.byte口decryptContent=Encryption.decryptBytesFile.ReadAllBytesencryptfilepathmd5EncryptedKeyK2initVectorBytes;stringdecryptfilepathZ1Environment.CurrentDirectory+pt〃+filename;File.WriteAllBytesdecryptfilepathdecryptContent;压缩解压stringfilename〃〃NewTextDocument.txt〃〃stringfilepath=Environment.CurrentDirectory+〃\\me;+filenastringzipfilepath=Environment.CurrentDirectory+\\NewTextDocumentzip”;thrownewArgumentNullException^plainText^;ifKey二二null||Key.Length〈二0thrownewArgumentNullException/zKey,z;ifIV==null||IV.Length=0thrownewArgumentNullException〃IV〃;MemoryStreammsEncrypt=null;AesCryptoServiceProvideraesAlg=null;try{aesAlg=newAesCryptoServiceProvider;aesAlg.Padding=PaddingMode.PKCS7;aesAlg.KeyZ1Key;apsAlg.TV=TV;ICryptoTransformencryptor=aesAlg.CreateEncryptoraesAlg.KeyaesAlg.IV;msEncrypt=newMemoryStreamusingCryptoStreamcsEncryptncryptorCryptoStreamMode.Write=newCryptoStreammsEncrypte0fileContentBytes.Length;csEncrypt.WritefileContentBytescsEncrypt.FlushFinalBlock;catchExceptionexfinallyifaesAlg!=nullaesAlg.Clear;returnmsEncrypt.ToArray;解密代码实现publicstaticbyte口decryptBytesbyte[]cipherTextbyte口Keybyte口IV{ifcipherText=null||cipherText.Length=0thrownewArgumentNullException/zcipherText/z;ifKey==null||Key.Length=0thrownewArgumentNullExceptionz/Keyz/;ifIV==null||IV.Length〈二0thrownewArgumentNullException〃IV〃;AesCryptoServiceProvideraesAlg=null;byte[]buffer=null;tryusingaesAlg=newAesCryptoServiceProvider0aesAlg.Padding=PaddingMode.PKCS7;aesAlg.Key=Key;aesAlg.IV=IV;ICryptoTransformdecryptor二aesAlg.CreateDecryptoraesAlg.KeyaesAlg.IV;usingMemoryStreammsDecrypt=newMemoryStreamcipherTextCryptoStreamcsDecrypt=newCryptoStreammsDecryptdecryptorCryptoStreamMode.Read;byte口tempbuffer=newbyte[cipherText.Length];inttotalBytesRead=csDecrypt.Readtempbuffer0tempbuffer.Length;buffer=tempbuffer.TaketotalBytesRead.ToArray;catchExceptionex}finallyifaesAlg!=nullaesAlg.Clear;returnbuffer;}客户端加密解密文本文件实战:///summary///加密解密////summaryprivatestaticvoid_EncryptAndDecryptASCIIEncodingasciiEnc二newASCIIEncodingO;byte口initVectorBytes=asciiEnc.GetBytesz,@lB2c3D4e5F6g7H8z,;//RandomlygenerateorBookkey-keyK2一KeytoencryptxmlcontentstringkeyK2=Generator.RandomString10;//Generatethe128bitstringusingMD5forkeyK2MD5hashProvider=MD
5.Create;byte[]md5EncryptedKeyK2=hashProvider.ComputeHashasciiEnc.GetByteskeyK2;stringfilename=NewTextDocument.txt”;stringfilepath二Environment.CurrentDirectory+〃\\〃+filename;byte[]Content=Encryption.encryptStringToBytesAESFile.ReadAllBytesfilepathmd5EncryptedKeyK2initVectorBytes;stringencryptfilepath=Environment.CurrentDirectory+〃\\encrypt〃+filename;File.WriteAllBytesencryptfilepathContent;。
个人认证
优秀文档
获得点赞 0