C# Rijndael 大文件 分割/合并 并 加密

代码
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.IO;

namespace Rocky.Utils
{
#region Crypto
public sealed class Crypto : IDisposable
{
#region StaticMembers
#region Properties
public static string HashSecurity
{
get { return HashEncoding(new Random().Next(1, int.MaxValue).ToString()); }
}

public static string Salt
{
get
{
Random rnd
= new Random();
Byte[] buffer
= new Byte[32];
rnd.NextBytes(buffer);
return HexString(buffer);
}
}
#endregion

#region Methods
public static string HashEncoding(string security)
{
SHA512Managed arithmetic
= new SHA512Managed();
byte[] result = arithmetic.ComputeHash(Encoding.Unicode.GetBytes(security));
StringBuilder sb
= new StringBuilder(result.Length);
for (int i = 0; i < result.Length; i++)
{
sb.Append((
int)result[i]).Append("O");
}
return sb.ToString();
}

public static string HexString(string input)
{
return HexString(Encoding.Unicode.GetBytes(input));
}
public static string HexString(byte[] input)
{
byte[] result = new MD5CryptoServiceProvider().ComputeHash(input);
StringBuilder sb
= new StringBuilder(result.Length);
for (int i = 0; i < result.Length; i++)
{
sb.Append(Convert.ToString(result[i],
16).PadLeft(2, '0'));
}
return sb.ToString();
}

public static string Encrypt32Md5(string s)
{
MD5CryptoServiceProvider md5
= new MD5CryptoServiceProvider();
byte[] result = md5.ComputeHash(Encoding.UTF8.GetBytes(s));
md5.Clear();
StringBuilder value
= new StringBuilder(32);
for (int i = 0; i < result.Length; i++)
{
value.Append(result[i].ToString(
"x").PadLeft(2, '0'));
}
return value.ToString();
}

public static string Encrypt16Md5(uot;color: #0000ff;">string; s)
{
MD5CryptoServiceProvider md5
= new MD5CryptoServiceProvider();
byte[] result = md5.ComputeHash(Encoding.UTF8.GetBytes(s));
md5.Clear();
string value = BitConverter.ToString(result, 4, 8);
return value.Replace("-", string.Empty);
}
#endregion

#region base64
public static bool IsBase64(string s)
{
return (s.Length % 4) == 0 && Regex.IsMatch(s, "^[A-Z0-9/+=]*$", RegexOptions.IgnoreCase);
}

public static string Base64Encode(string s)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(s));
}

public static stringuot;color: #000000;"> Base64Decode(string s)
{
return Encoding.UTF8.GetString(Convert.FromBase64String(s));
}
#endregion
#endregion

#region Fields
private string key, iv;
private byte[] legalKey, legalIV;
private RijndaelManaged rijndael;
#endregion

#region Properties
public string Key
{
set
{
key
= value;
rijndael.GenerateKey();
if (key.Length > rijndael.Key.Length)
{
key
= key.Substring(0, rijndael.Key.Length);
}
else
{
key
= key.PadRight(rijndael.Key.Length, ' ');
}
legalKey
= Encoding.ASCII.GetBytes(key);
}
get { return key; }
}
public string IV
{
set
{
iv
= value;
rijndael.GenerateIV();
if (iv.Length > rijndael.IV.Length)
{
iv
= iv.Substring(0, rijndael.IV.Length);
}
else
{
iv
= iv.PadRight(rijndael.IV.Length, ' ');
}
legalIV
= Encoding.ASCII.GetBytes(iv);
}
get { return iv; }
}
#endregion

#region Methods
public Crypto()
{
rijndael
= new RijndaelManaged();
this.IV = this.Key = Crypto.Salt;
}

public string Encrypt(string input)
{
return Convert.ToBase64String(Encrypt(Encoding.UTF8.GetBytes(input)));
}
public byte[] Encrypt(byte[] input)
{
return rijndael.CreateEncryptor(legalKey, legalIV).TransformFinalBlock(input, 0, input.Length);
}

public string Decrypt(string input)
{
return Encoding.UTF8.GetString(Decrypt(Convert.FromBase64String(input)));
}
private byte[] Decrypt(byte[] input)
{
return rijndael.CreateDecryptor(legalKey, legalIV).TransformFinalBlock(input, 0, input.Length);
}

#region File
public void EncryptFile(string inFileName, string outFileName)
{
using (FileStream inStream = new FileStream(inFileName, FileMode.Open, FileAccess.Read))
using (CryptoStream outStream = new CryptoStream(new FileStream(outFileName, FileMode.Create, FileAccess.Write), rijndael.CreateEncryptor(legalKey, legalIV), CryptoStreamMode.Write))
{
byte[] buffer = new byte[BufferUtility.FileBufferSize];
int read;
while ((read = inStream.Read(buffer, 0, buffer.Length)) != 0)
{
outStream.Write(buffer,
0, read);
}
}
}
public void DecryptFile(string inFileName, string outFileName)
{
using (FileStream inStream = new FileStream(inFileName, FileMode.Open, FileAccess.Read))
using (CryptoStream outStream = new CryptoStream(new FileStream(outFileName, FileMode.Create, FileAccess.Write), rijndael.CreateDecryptor(legalKey, legalIV), CryptoStreamMode.Write))
{
byte[] buffer = new byte[BufferUtility.FileBufferSize];
int read;
while ((read = inStream.Read(buffer, 0, buffer.Length)) != 0)
{
outStream.Write(buffer,
0, read);
}
}
}

public void EncryptFile(string inFileName, string outFileName, long splitSize, SplitFileMode mode)
{
FileStream _inStream
= new FileStream(inFileName, FileMode.Open, FileAccess.Read);
long fileLength = _inStream.Length, oddSize, avgSize = Math.DivRem(fileLength, splitSize, out oddSize),
i
= 0L, count, size;
switch (mode)
{
case SplitFileMode.ByInputFileLength:
count
= avgSize;
size
= splitSize;
break;
default:
count
= splitSize;
size
= avgSize;
break;
}
using (ICryptoTransform encrypto = rijndael.CreateEncryptor(legalKey, legalIV))
using (CryptoStream inStream = new CryptoStream(_inStream, encrypto, CryptoStreamMode.Read))
{
byte[] buffer = new byte[BufferUtility.FileBufferSize];
while (i < count)
{
long wrote = 0L, length = (++i) == count ? size + oddSize : size;
using (FileStream outStream = new FileStream(String.Concat(outFileName, "_Part", i, ".temp"), FileMode.Create, FileAccess.Write))
{
int read;
while (wrote < length)
{
read
= inStream.Read(buffer, 0, Math.Min(buffer.Length, (int)(length - wrote)));
outStream.Write(buffer,
0, read);
wrote
+= (long)read;
}
if (i == count)
{
while ((read = inStream.Read(buffer, 0, buffer.Length)) != 0)
{
outStream.Write(buffer,
0, read);
}
BufferUtility.Write(fileLength, buffer,
0);
outStream.Write(buffer,
0, 8);
}
}
}
}
}
public void DecryptFile(string inFileName, string outFileName, long splitSize, SplitFileMode mode)
{
byte[] buffer = new byte[BufferUtility.FileBufferSize];
long i = 1, fileLength;
while (File.Exists(String.Concat(inFileName, "_Part", i, ".temp")))
{
i
++;
}
FileStream _lastInStream
= new FileStream(String.Concat(inFileName, "_Part", --i, ".temp"), FileMode.Open, FileAccess.ReadWrite);
long _lastInStreamLength = _lastInStream.Length - 8;
_lastInStream.Position
= _lastInStreamLength;
_lastInStream.Read(buffer,
0, 8);
_lastInStream.Position
= 0L;
_lastInStream.SetLength(_lastInStreamLength);
BufferUtility.Read(
out fileLength, buffer, 0);
long oddSize, avgSize = Math.DivRem(fileLength, splitSize, out oddSize),
count, size;
i
= 0L;
switch (mode)
{
case SplitFileMode.ByInputFileLength:
count
= avgSize;
size
= splitSize;
break;
default:
count
= splitSize;
size
= avgSize;
break;
}
using (ICryptoTransform decrypto = rijndael.CreateDecryptor(legalKey, legalIV))
using (CryptoStream outStream = new CryptoStream(new FileStream(outFileName, FileMode.Create, FileAccess.Write), decrypto, CryptoStreamMode.Write))
{
while (i < count)
{
long wrote = 0L, length = (++i) == count ? size + oddSize : size;
using (FileStream inStream = i == count ? _lastInStream : new FileStream(String.Concat(inFileName, "_Part", i, ".temp"), FileMode.Open, FileAccess.Read))
{
int read;
while (wrote < length)
{
read
= inStream.Read(buffer, 0, Math.Min(buffer.Length, (int)(length - wrote)));
outStream.Write(buffer,
0, read);
wrote
+= (long)read;
}
if (i == count)
{
while ((read = inStream.Read(buffer, 0, buffer.Length)) != 0)
{
outStream.Write(buffer,
0, read);
}
BufferUtility.Write(fileLength, buffer,
0);
inStream.Write(buffer,
0, 8);
}
}
}
}
}
#endregion

public void Dispose()
{
if (rijndael != null)
{
key
= iv = null;
legalKey
= legalIV = null;
rijndael.Clear();
rijndael
= null;
}
}
#endregion
}
#endregion

#region SplitFileMode
public enum SplitFileMode
{
ByOutputFileCount, ByInputFileLength
}
#endregion
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using Rocky.Utils;

namespace Test
{
public class Files
{
public static void Action()
{
string filePath = @"d:\Rocky3.5.7z";
string encryptOutFilePath = @"d:\newRocky3.5.7z";
string decryptOutFilePath = @"d:\newNewRocky3.5.7z";
Crypto c
= new Crypto();
//c.Key = "145aa0a10e266f35db72ef7311671f90";
//c.IV = "145aa0a10e266f35";
//仅加密文件
//c.EncryptFile(filePath, encryptOutFilePath);
//Thread.Sleep(1000);
//c.DecryptFile(encryptOutFilePath, decryptOutFilePath);

//加密并分割文件
c.EncryptFile(filePath, encryptOutFilePath, 2, SplitFileMode.ByOutputFileCount);
IOUtility.WriteFile(Path.Combine(Path.GetDirectoryName(filePath),
"key.txt"), "Key:" + c.Key + ",IV:" + c.IV);
Thread.Sleep(
1000);
c.DecryptFile(encryptOutFilePath, decryptOutFilePath,
2, SplitFileMode.ByOutputFileCount);
}
}
}
原文地址:https://www.cnblogs.com/Googler/p/1764651.html