Zi 字媒體
2017-07-25T20:27:27+00:00
C# 檔案的加密/解密(DES)
資料來源:http://www.dotblogs.com.tw/yc421206/archive/2012/04/18/71609.aspx
https://support.microsoft.com/zh-tw/kb/307010
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;//FILE
using System.Security.Cryptography;//DESCryptoServiceProvider
namespace Console_CS_Encrypt_desDecrypt
{
class Program
{
public
static void
desEncryptFile(string sourceFile, string encryptFile)
{
if
(string.IsNullOrEmpty(sourceFile) || string.IsNullOrEmpty(encryptFile))
{
return;
}
if
(!File.Exists(sourceFile))
{
return;
}
DESCryptoServiceProvider
des = new DESCryptoServiceProvider();
byte[]
key =
Encoding.ASCII.GetBytes(“12345678”);
byte[]
iv =
Encoding.ASCII.GetBytes(“87654321”);
des.Key = key;
des.IV = iv;
using
(FileStream sourceStream = new FileStream(sourceFile,
FileMode.Open, FileAccess.Read))
using
(FileStream encryptStream = new FileStream(encryptFile,
FileMode.Create, FileAccess.Write))
{
//檔E案¡Ñ加D[密ÓK
byte[]
dataByteArray =
new byte[sourceStream.Length];
sourceStream.Read(dataByteArray, 0, dataByteArray.Length);
using
(CryptoStream cs = new CryptoStream(encryptStream,
des.CreateEncryptor(),
CryptoStreamMode.Write))
{
cs.Write(dataByteArray,
0, dataByteArray.Length);
cs.FlushFinalBlock();
}
}
}
public
static void
desDecryptFile(string encryptFile, string decryptFile)
{
if
(string.IsNullOrEmpty(encryptFile) || string.IsNullOrEmpty(decryptFile))
{
return;
}
if
(!File.Exists(encryptFile))
{
return;
}
DESCryptoServiceProvider
des = new DESCryptoServiceProvider();
byte[]
key =
Encoding.ASCII.GetBytes(“12345678”);
byte[]
iv =
Encoding.ASCII.GetBytes(“87654321”);
des.Key = key;
des.IV = iv;
using
(FileStream encryptStream = new FileStream(encryptFile,
FileMode.Open, FileAccess.Read))
using
(FileStream decryptStream = new FileStream(decryptFile,
FileMode.Create, FileAccess.Write))
{
byte[]
dataByteArray =
new byte[encryptStream.Length];
encryptStream.Read(dataByteArray, 0, dataByteArray.Length);
using
(CryptoStream cs = new CryptoStream(decryptStream,
des.CreateDecryptor(),
CryptoStreamMode.Write))
{
cs.Write(dataByteArray,
0, dataByteArray.Length);
cs.FlushFinalBlock();
}
}
}
static
void Main(string[]
args)
{
string
sourceFile=“C:\\Users\\RD\\Desktop\\06.nsi”;
string
encryptFile=“C:\\Users\\RD\\Desktop\\06_e.nsi”;
string
decryptFile=“C:\\Users\\RD\\Desktop\\06_d.nsi”;
desEncryptFile(sourceFile,encryptFile);
desDecryptFile(encryptFile,
decryptFile);
Pause();
}
public static void Pause()
{
Console.Write(“Press any key to continue . . . “);
Console.ReadKey(true);
}
}
}
寫了
5860316篇文章,獲得
23313次喜歡