---
title: "AES对媒体文件的加密与解密"
author: "devgis"
date: "2012-11-16T10:38:00Z"
tags: []
slug: "aes"
draft: false
lastmod: "2012-11-21T09:21:02Z"
id: 1731477
url: "https://devgis.iteye.com/blog/1731477"
---

`usingSystem.Text;`

`002` `usingSystem.Collections;`

`003` `usingSystem.ComponentModel;`

`004` `usingSystem.Data;`

`005` `usingSystem.Net;`

`006` `usingSystem.Net.Sockets;`

`007` `usingSystem.Threading;`

`008` `usingSystem.IO;`

`009` `usingSystem.Security.Cryptography;`

`010`

`011` `publicclassAESEncryption`

`012` `{`

`013`

`014` `staticstringstrKey="dongbinhuiasxiny";//密钥,128位，也可以改为192位（24字节）或256位（32字节）。`

`015` `staticvoidMain(string[] args)`

`016` `{`

`017` `RijndaelManaged rij =newRijndaelManaged();`

`018` `rij.KeySize = 128;//指定密钥长度`

`019`

`020` `stringfp =@"...";//待加密文件`

`021` `stringsPhysicalFilePath =@"...";//加密后的文件`

`022` `stringfw =@"...";//解密后的文件`

`023` `Console.WriteLine("Encrypting begin...");`

`024` `encryption(rij, fp, sPhysicalFilePath);`

`025` `decryption(rij,sPhysicalFilePath,fw);`

`026`

`027` `}`

`028` `//用于加密的函数`

`029` `publicstaticvoidencryption(RijndaelManaged rij,stringreadfile,stringwritefile)`

`030` `{`

`031` `try`

`032` `{`

`033` `//byte[] key = rij.Key;`

`034` `byte[] key=Encoding.UTF8.GetBytes (strKey);`

`035` `byte[] iv = rij.IV;`

`036` `byte[] buffer =newbyte[4096];`

`037` `Rijndael crypt = Rijndael.Create();`

`038` `ICryptoTransform transform = crypt.CreateEncryptor(key, iv);`

`039` `//写进文件`

`040` `FileStream fswrite =newFileStream(writefile, FileMode.Create);`

`041` `CryptoStream cs =newCryptoStream(fswrite, transform, CryptoStreamMode.Write);`

`042` `//打开文件`

`043` `FileStream fsread =newFileStream(readfile, FileMode.Open);`

`044`

`045` `/*------------------定位要加密的部分-----------------*/`

`046` `long_file_size=fsread.Length;`

`047` `byte[] _header =newbyte[8];`

`048` `//定位GUID`

`049` `fsread.Seek(16, SeekOrigin.Begin);`

`050` `//读取header size`

`051` `fsread.Read(_header, 0, _header.Length);`

`052` `//头部长度`

`053` `long_header_size = (long)BitConverter.ToInt32(_header, 0);`

`054` `byte[] _header_buffer=newbyte[_header_size];`

`055` `fsread.Seek(0,SeekOrigin.Begin);`

`056` `fsread.Read(_header_buffer,0,_header_buffer.Length);`

`057` `//头部写入新文件`

`058` `fswrite.Write(_header_buffer,0,_header_buffer.Length);`

`059` `//定位到头部，准备读取需要加密的部分`

`060` `fsread.Seek(_header_size,SeekOrigin.Begin);`

`061` `/*-----------------定位加密部分完成-------------------*/`

`062` `intlength;`

`063` `//while ((length = fsread.ReadByte()) != -1)`

`064` `//cs.WriteByte((byte)length);`

`065` `while((length = fsread.Read(buffer, 0, 4096)) > 0){`

`066` `cs.Write(buffer, 0, (int)length);`

`067` `}`

`068`

`069` `fsread.Close();`

`070` `cs.Close();`

`071` `fswrite.Close();`

`072` `Console.WriteLine("Encrypt Success");`

`073` `}`

`074` `catch(Exception e)`

`075` `{`

`076` `Console.WriteLine("Encrypt Faile"+e.ToString());`

`077` `}`

`078` `}`

`079` `//用于解密的函数`

`080` `publicstaticvoiddecryption(RijndaelManaged rij,stringreadfile,stringwritefile)`

`081` `{`

`082` `try`

`083` `{`

`084` `//byte[] key = rij.Key;`

`085` `byte[] key=Encoding.UTF8.GetBytes (strKey);`

`086` `byte[] iv = rij.IV;`

`087` `byte[] buffer=newbyte[4096];`

`088` `Rijndael crypt = Rijndael.Create();`

`089` `ICryptoTransform transform = crypt.CreateDecryptor(key, iv);`

`090` `//读取加密后的文件`

`091` `FileStream fsopen =newFileStream(readfile, FileMode.Open);`

`092` `CryptoStream cs =newCryptoStream(fsopen, transform, CryptoStreamMode.Read);`

`093` `//把解密后的结果写进文件`

`094` `FileStream fswrite =newFileStream(writefile, FileMode.OpenOrCreate);`

`095` `/*------------------定位要解密的部分-----------------*/`

`096` `long_file_size=fsopen.Length;`

`097` `byte[] _header =newbyte[8];`

`098` `//定位GUID`

`099` `fsopen.Seek(16, SeekOrigin.Begin);`

`100` `//读取header size`

`101` `fsopen.Read(_header, 0, _header.Length);`

`102` `//头部长度`

`103` `long_header_size = (long)BitConverter.ToInt32(_header, 0);`

`104` `byte[] _header_buffer=newbyte[_header_size];`

`105` `fsopen.Seek(0,SeekOrigin.Begin);`

`106` `fsopen.Read(_header_buffer,0,_header_buffer.Length);`

`107` `//头部写入新文件`

`108` `fswrite.Write(_header_buffer,0,_header_buffer.Length);`

`109` `//定位到头部，准备读取需要加密的部分`

`110` `fsopen.Seek(_header_size,SeekOrigin.Begin);`

`111` `/*-----------------定位要解密的部分完成-------------------*/`

`112`

`113` `intlength;`

`114` `//while ((length = cs.ReadByte()) != -1)`

`115` `//fswrite.WriteByte((byte)length);`

`116` `while((length = cs.Read(buffer, 0, 4096)) > 0){`

`117` `fswrite.Write(buffer, 0, (int)length);`

`118` `}`

`119` `fswrite.Close();`

`120` `cs.Close();`

`121` `fsopen.Close();`

`122` `Console.WriteLine("Decrypt Success");`

`123` `}`

`124` `catch(Exception e)`

`125` `{`

`126` `Console.WriteLine("Decrypt Failed"+e.ToString());`

`127` `}`

`128` `}`

`129` `}`

`usingSystem;`

`002` `usingSystem.IO;`

`003` `usingSystem.Security;`

`004` `usingSystem.Security.Cryptography;`

`005` `usingSystem.Runtime.InteropServices;`

`006` `usingSystem.Text;`

`007`

`008` `namespaceCSEncryptDecrypt`

`009` `{`

`010` `classClass1`

`011` `{`

`012` `// Call this function to remove the key from memory after use for security`

`013` `[System.Runtime.InteropServices.DllImport("KERNEL32.DLL", EntryPoint="RtlZeroMemory")]`

`014` `publicstaticexternboolZeroMemory(IntPtr Destination,intLength);`

`015`

`016` `// Function to Generate a 64 bits Key.`

`017` `staticstringGenerateKey()`

`018` `{`

`019` `// Create an instance of Symetric Algorithm. Key and IV is generated automatically.`

`020` `DESCryptoServiceProvider desCrypto =(DESCryptoServiceProvider)DESCryptoServiceProvider.Create();`

`021`

`022` `// Use the Automatically generated key for Encryption.`

`023` `returnASCIIEncoding.ASCII.GetString(desCrypto.Key);`

`024` `}`

`025`

`026` `staticvoidEncryptFile(stringsInputFilename,`

`027` `stringsOutputFilename,`

`028` `stringsKey)`

`029` `{`

`030` `FileStream fsInput =newFileStream(sInputFilename,`

`031` `FileMode.Open,`

`032` `FileAccess.Read);`

`033`

`034` `FileStream fsEncrypted =newFileStream(sOutputFilename,`

`035` `FileMode.Create,`

`036` `FileAccess.Write);`

`037` `DESCryptoServiceProvider DES =newDESCryptoServiceProvider();`

`038` `DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);`

`039` `DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);`

`040` `ICryptoTransform desencrypt = DES.CreateEncryptor();`

`041` `CryptoStream cryptostream =newCryptoStream(fsEncrypted,`

`042` `desencrypt,`

`043` `CryptoStreamMode.Write);`

`044`

`045` `byte[] bytearrayinput =newbyte[fsInput.Length];`

`046` `fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);`

`047` `cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);`

`048` `cryptostream.Close();`

`049` `fsInput.Close();`

`050` `fsEncrypted.Close();`

`051` `}`

`052`

`053` `staticvoidDecryptFile(stringsInputFilename,`

`054` `stringsOutputFilename,`

`055` `stringsKey)`

`056` `{`

`057` `DESCryptoServiceProvider DES =newDESCryptoServiceProvider();`

`058` `//A 64 bit key and IV is required for this provider.`

`059` `//Set secret key For DES algorithm.`

`060` `DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);`

`061` `//Set initialization vector.`

`062` `DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);`

`063`

`064` `//Create a file stream to read the encrypted file back.`

`065` `FileStream fsread =newFileStream(sInputFilename,`

`066` `FileMode.Open,`

`067` `FileAccess.Read);`

`068` `//Create a DES decryptor from the DES instance.`

`069` `ICryptoTransform desdecrypt = DES.CreateDecryptor();`

`070` `//Create crypto stream set to read and do a`

`071` `//DES decryption transform on incoming bytes.`

`072` `CryptoStream cryptostreamDecr =newCryptoStream(fsread,`

`073` `desdecrypt,`

`074` `CryptoStreamMode.Read);`

`075` `//Print the contents of the decrypted file.`

`076` `StreamWriter fsDecrypted =newStreamWriter(sOutputFilename);`

`077` `fsDecrypted.Write(newStreamReader(cryptostreamDecr).ReadToEnd());`

`078` `fsDecrypted.Flush();`

`079` `fsDecrypted.Close();`

`080` `}`

`081`

`082` `staticvoidMain()`

`083` `{`

`084` `// Must be 64 bits, 8 bytes.`

`085` `// Distribute this key to the user who will decrypt this file.`

`086` `stringsSecretKey;`

`087`

`088` `// Get the Key for the file to Encrypt.`

`089` `sSecretKey = GenerateKey();`

`090`

`091` `// For additional security Pin the key.`

`092` `GCHandle gch = GCHandle.Alloc( sSecretKey,GCHandleType.Pinned );`

`093`

`094` `// Encrypt the file.`

`095` `EncryptFile(@"C:\MyData.txt",`

`096` `@"C:\Encrypted.txt",`

`097` `sSecretKey);`

`098`

`099` `// Decrypt the file.`

`100` `DecryptFile(@"C:\Encrypted.txt",`

`101` `@"C:\Decrypted.txt",`

`102` `sSecretKey);`

`103`

`104` `// Remove the Key from memory.`

`105` `ZeroMemory(gch.AddrOfPinnedObject(), sSecretKey.Length * 2);`

`106` `gch.Free();`

`107` `}`

`108` `}`

`109` `}`

### \[代码]大文件分块加密和解密

[view source](http://www.oschina.net/code/snippet_222150_15438#viewSource "view source")

[print](http://www.oschina.net/code/snippet_222150_15438#printSource "print")[?](http://www.oschina.net/code/snippet_222150_15438#about "?")

`01` `usingSystem.Text;`

`02` `usingSystem.Collections;`

`03` `usingSystem.ComponentModel;`

`04` `usingSystem.Data;`

`05` `usingSystem.Net;`

`06` `usingSystem.Net.Sockets;`

`07` `usingSystem.Threading;`

`08` `usingSystem.IO;`

`09` `usingSystem.Security.Cryptography;`

`10`

`11` `namespaceVideoEncrypt`

`12` `{`

`13` `classProgram`

`14` `{`

`15` `staticvoidMain(string[] args)`

`16` `{`

`17` `RijndaelManaged rij =newRijndaelManaged();`

`18` `rij.KeySize = 128;`

`19`

`20` `stringfp =@"E://friends//3//3.mkv";`

`21` `stringsPhysicalFilePath =@"E://friends//3//o3.mkv";`

`22` `stringfw =@"E://friends//3//dd3.mkv";`

`23` `Console.WriteLine("Encrypting begin...");`

`24` `encryption(rij, fp, sPhysicalFilePath);`

`25` `decryption(rij,sPhysicalFilePath,fw);`

`26`

`27` `}`

`28` `//用于加密的函数`

`29` `publicstaticvoidencryption(RijndaelManaged rij,stringreadfile,stringwritefile)`

`30` `{`

`31` `try`

`32` `{`

`33` `byte[] key = rij.Key;`

`34` `byte[] iv = rij.IV;`

`35` `byte[] buffer =newbyte[4096];`

`36` `Rijndael crypt = Rijndael.Create();`

`37` `ICryptoTransform transform = crypt.CreateEncryptor(key, iv);`

`38` `//写进文件`

`39` `FileStream fswrite =newFileStream(writefile, FileMode.Create);`

`40` `CryptoStream cs =newCryptoStream(fswrite, transform, CryptoStreamMode.Write);`

`41` `//打开文件`

`42` `FileStream fsread =newFileStream(readfile, FileMode.Open);`

`43` `intlength;`

`44` `//while ((length = fsread.ReadByte()) != -1)`

`45` `//cs.WriteByte((byte)length);`

`46` `while((length = fsread.Read(buffer, 0, 4096)) > 0)`

`47` `cs.Write(buffer, 0, (int)length);`

`48`

`49` `fsread.Close();`

`50` `cs.Close();`

`51` `fswrite.Close();`

`52` `Console.WriteLine("Encrypt Success");`

`53` `}`

`54` `catch(Exception e)`

`55` `{`

`56` `Console.WriteLine("Encrypt Faile"+e.ToString());`

`57` `}`

`58` `}`

`59` `//用于解密的函数`

`60` `publicstaticvoiddecryption(RijndaelManaged rij,stringreadfile,stringwritefile)`

`61` `{`

`62` `try`

`63` `{`

`64` `byte[] key = rij.Key;`

`65` `byte[] iv = rij.IV;`

`66` `byte[] buffer=newbyte[4096];`

`67` `Rijndael crypt = Rijndael.Create();`

`68` `ICryptoTransform transform = crypt.CreateDecryptor(key, iv);`

`69` `//读取加密后的文件`

`70` `FileStream fsopen =newFileStream(readfile, FileMode.Open);`

`71` `CryptoStream cs =newCryptoStream(fsopen, transform, CryptoStreamMode.Read);`

`72` `//把解密后的结果写进文件`

`73` `FileStream fswrite =newFileStream(writefile, FileMode.OpenOrCreate);`

`74`

`75` `intlength;`

`76` `//while ((length = cs.ReadByte()) != -1)`

`77` `//fswrite.WriteByte((byte)length);`

`78` `while((length = cs.Read(buffer, 0, 4096)) > 0)`

`79` `fswrite.Write(buffer, 0, (int)length);`

`80` `fswrite.Close();`

`81` `cs.Close();`

`82` `fsopen.Close();`

`83` `Console.WriteLine("Decrypt Success");`

`84` `}`

`85` `catch(Exception e)`

`86` `{`

`87` `Console.WriteLine("Decrypt Failed"+e.ToString());`

`88` `}`

`89` `}`

`90` `}`

`91` `}`