首页 > 代码库 > .net aes加密视频等文件
.net aes加密视频等文件
公司学习平台在app端下载下来的视频需要加密
随查找资料参考一些写法
写了aes的加密方法
记录防止忘记
using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Security.Cryptography;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication1{ class Class1 { private const string SKey = "_?73^?dVT3st5har3"; private const string SaltKey = "!2S@LT&KT3st5har3EY"; private const int Iterations = 1042; // Recommendation is >= 1000 static byte[] GetBytes(string str) { var bytes = new byte[str.Length * sizeof(char)]; Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); return bytes; } static string GenerateKey() { // Create an instance of Symetric Algorithm. Key and IV is generated automatically. DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create(); // Use the Automatically generated key for Encryption. return ASCIIEncoding.ASCII.GetString(desCrypto.Key); } public static void EncryptFile(string srcFilename, string destFilename) { var aes = new AesManaged(); aes.BlockSize = 128; aes.KeySize = 256; var salt = GetBytes(SaltKey); var key = new Rfc2898DeriveBytes(SKey, salt, Iterations); aes.Key = key.GetBytes(aes.KeySize / 8); aes.IV = key.GetBytes(aes.BlockSize / 8); aes.Mode = CipherMode.CBC; ICryptoTransform transform = aes.CreateEncryptor(aes.Key, aes.IV); using (var dest = new FileStream(destFilename, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { using (var cryptoStream = new CryptoStream(dest, transform, CryptoStreamMode.Write)) { using (var source = new FileStream(srcFilename, FileMode.Open, FileAccess.Read, FileShare.Read)) { source.CopyTo(cryptoStream); } } } } public static void DecryptFile(string srcFilename, string destFilename) { var aes = new AesManaged(); aes.BlockSize = 128; aes.KeySize = 256; var salt = GetBytes(SaltKey); var key = new Rfc2898DeriveBytes(SKey, salt, Iterations); aes.Key = key.GetBytes(aes.KeySize / 8); aes.IV = key.GetBytes(aes.BlockSize / 8); aes.Mode = CipherMode.CBC; ICryptoTransform transform = aes.CreateDecryptor(aes.Key, aes.IV); using (var dest = new FileStream(destFilename, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { using (var cryptoStream = new CryptoStream(dest, transform, CryptoStreamMode.Write)) { try { using (var source = new FileStream(srcFilename, FileMode.Open, FileAccess.Read, FileShare.Read)) { source.CopyTo(cryptoStream); } } catch (CryptographicException exception) { throw new ApplicationException("Decryption failed.", exception); } } } } }}
运行
static void Main(string[] args) { // Class1.EncryptFile(@"C:\kc_Page_2.mp4", @"C:\kc_Page_3.mp4"); //Class1.DecryptFile(@"C:\kc_Page_3.mp4", @"C:\kc_Page_4.mp4"); Class1.EncryptFile(@"C:\1.docx", @"C:\2.docx"); Class1.DecryptFile(@"C:\2.docx", @"C:\3.docx"); }
.net aes加密视频等文件
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。