本文整理汇总了C#中System.Security.Cryptography.AesCryptoServiceProvider.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# AesCryptoServiceProvider.Dispose方法的具体用法?C# AesCryptoServiceProvider.Dispose怎么用?C# AesCryptoServiceProvider.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Security.Cryptography.AesCryptoServiceProvider
的用法示例。
在下文中一共展示了AesCryptoServiceProvider.Dispose方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Decrypt
static void Decrypt(string[] args)
{
//Precheck if a tmp file already exists.
//If so delete it.
if (File.Exists(args[0] + ".tmp"))
{
Display("Destroying old .tmp files.");
DestroyFile(args[0] + ".tmp");
Display("Done.");
}
//SET UP STREAMS//
FileStream Output;
FileStream Input;
CryptoStream CryptStream;
//SET UP SERVICE PROVIDERS//
AesCryptoServiceProvider ACSP = new AesCryptoServiceProvider();
//AES PARAMETERS//
ACSP.Padding = PaddingMode.PKCS7;
Display("Creating keys.");
ACSP.IV = GenerateIV(args[2]); //initialization vector
ACSP.Key = GenerateKey(args[2]); //32 byte key
Display("Done.");
Input = new FileStream(args[0], FileMode.Open);
Output = new FileStream(args[0] + ".tmp", FileMode.CreateNew);
CryptStream = new CryptoStream(Input, ACSP.CreateDecryptor(), CryptoStreamMode.Read);
Display("Starting decryption.");
CryptStream.CopyTo(Output);
Display("Done.");
Input.Flush();
Input.Dispose();
CryptStream.Flush();
//CryptStream.Dispose(); <-- Is disposed with input.
Output.Flush();
Output.Dispose();
Display("Destroying old raw file.");
DestroyFile(args[0]);
Display("Done.");
//Rename .tmp to the original file.
Display("Renaming new file.");
File.Move(args[0] + ".tmp", args[0]);
Display("Done.");
ACSP.Dispose();
Display("Decryption process completed.");
Console.ReadKey();
return;
}
示例2: Decrypt
internal byte[] Decrypt(byte[] input, byte[] key)
{
var aes = new AesCryptoServiceProvider();
aes.Padding = PaddingMode.Zeros;
aes.Mode = CipherMode.CBC;
aes.Key = key;
aes.IV = key;
var crypto = aes.CreateDecryptor();
var decrypted = crypto.TransformFinalBlock(input, 4, input.Length - 4);
aes.Dispose();
this.LastData = decrypted;
return decrypted;
}
示例3: Encrypt
internal string Encrypt(byte[] input, byte[] key)
{
var aes = new AesCryptoServiceProvider();
aes.Padding = PaddingMode.Zeros;
aes.Mode = CipherMode.CBC;
aes.Key = key;
aes.IV = key;
var crypto = aes.CreateEncryptor();
var crypted = crypto.TransformFinalBlock(input, 0, input.Length);
var newCryptedValue = new byte[crypted.Length + 4];
Buffer.BlockCopy(BitConverter.GetBytes(input.Length), 0, newCryptedValue, 0, 4);
Buffer.BlockCopy(crypted, 0, newCryptedValue, 4, crypted.Length);
aes.Dispose();
this.LastData = newCryptedValue;
return Convert.ToBase64String(newCryptedValue);
}
示例4: btn_dencrypt_Click
private void btn_dencrypt_Click(object sender, EventArgs e)
{
String toDecrypt = tb_toDencryptUTF8.Text;
if (String.IsNullOrEmpty(toDecrypt)) return;
AesCryptoServiceProvider aes = null;
MemoryStream ms = null;
CryptoStream cs = null;
try
{
aes = new AesCryptoServiceProvider();
aes.Key = key;
aes.IV = iv;
var encrypted = Convert.FromBase64String(tb_toDencryptB64.Text);
ms = new MemoryStream(encrypted);
cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read);
byte[] buffer = new byte[encrypted.Length];
int offset = cs.Read(buffer, 0, buffer.Length);
tb_dencrypted.Text = Encoding.UTF8.GetString(buffer, 0, offset);
}
catch (Exception ex)
{
Console.WriteLine(ex);
throw;
}
finally
{
if (aes != null) aes.Dispose();
if (cs != null) cs.Dispose();
if (ms != null) ms.Dispose();
}
}
示例5: Crypt
/// <summary>
/// Encrypts/decrypts a byte array
/// </summary>
/// <param name="buffer">Bytes to crypt</param>
/// <param name="key">"Password" for encryption</param>
/// <param name="iv">"Salt" for encryption. A starting point for encryption.</param>
/// <param name="encrypt">Do you wish to encrypt or decrypt?</param>
/// <param name="algorithm">Encryption algorithm. AES/DES/TripleDES</param>
/// <returns></returns>
public static byte[] Crypt(byte[] buffer, byte[] key, byte[] iv, bool encrypt = true, string algorithm = "aes")
{
AesCryptoServiceProvider aes = null;
DESCryptoServiceProvider des = null;
TripleDESCryptoServiceProvider tripsDes = null;
ICryptoTransform cryptor;
switch (algorithm.ToLower())
{
case "aes":
aes = new AesCryptoServiceProvider();
aes.Key = key;
aes.IV = iv;
//aes.Padding = PaddingMode.None;
if (encrypt) cryptor = aes.CreateEncryptor();
else cryptor = aes.CreateDecryptor();
break;
case "des":
des = new DESCryptoServiceProvider();
des.Key = key;
des.IV = iv;
//des.Padding = PaddingMode.None;
if (encrypt) cryptor = des.CreateEncryptor();
else cryptor = des.CreateDecryptor();
break;
case "tripledes":
tripsDes = new TripleDESCryptoServiceProvider();
tripsDes.Key = key;
tripsDes.IV = iv;
//tripsDes.Padding = PaddingMode.None;
if (encrypt) cryptor = tripsDes.CreateEncryptor();
else cryptor = tripsDes.CreateDecryptor();
break;
default:
throw new ArgumentException(algorithm + " is not an implemented encryption algorithm. Use AES/DES/TripleDES.");
}
try
{
return cryptor.TransformFinalBlock(buffer, 0, buffer.Length);
}
catch (CryptographicException)
{
throw new ArgumentException("Ensure you have the right key/IV.");
}
finally
{
cryptor.Dispose();
if (aes != null) aes.Dispose();
if (des != null) des.Dispose();
if (tripsDes != null) tripsDes.Dispose();
}
}
示例6: Main
static void Main(string[] args)
{
const int n = 100 * 1000;
var sw = new Stopwatch();
Random r = new Random();
var data = new byte[1024];
var key8B = new byte[8];
var key16B = new byte[16];
var key24B = new byte[24];
var key32B = new byte[32];
r.NextBytes(data);
r.NextBytes(key8B);
r.NextBytes(key16B);
r.NextBytes(key24B);
r.NextBytes(key32B);
Action<string> outputToConsole = (s) =>
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(s);
};
// AES
Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.WriteLine("AES");
var aes = new AesCryptoServiceProvider();
aes.Padding = PaddingMode.PKCS7;
aes.Key = key16B;
Action doAes = () => EncryptDecryptAndDispose(aes.CreateEncryptor(), aes.CreateDecryptor(), data);
doAes.Repeat(n)
.OutputPerformance(sw, outputToConsole)();
aes.Dispose();
// RSA
Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.WriteLine("DES");
var des = new DESCryptoServiceProvider();
des.IV = key8B;
des.Key = key8B;
Action doDes = () => EncryptDecryptAndDispose(des.CreateEncryptor(), des.CreateDecryptor(), data);
doDes.Repeat(n)
.OutputPerformance(sw, outputToConsole)();
des.Dispose();
// RC2
Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.WriteLine("RC2");
var rc2 = new RC2CryptoServiceProvider();
rc2.IV = key8B;
rc2.Key = key8B;
Action doRc2 = () => EncryptDecryptAndDispose(rc2.CreateEncryptor(), rc2.CreateDecryptor(), data);
doRc2.Repeat(n)
.OutputPerformance(sw, outputToConsole)();
rc2.Dispose();
// Rijndael
Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.WriteLine("Rijndael");
var rijndael = new RijndaelManaged();
rijndael.IV = key16B;
rijndael.Key = key16B;
Action doRijndael = () => EncryptDecryptAndDispose(rijndael.CreateEncryptor(), rijndael.CreateDecryptor(), data);
doRijndael.Repeat(n)
.OutputPerformance(sw, outputToConsole)();
rijndael.Dispose();
// 3DES
Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.WriteLine("3DES");
var tripleDes = new TripleDESCryptoServiceProvider();
tripleDes.IV = key8B;
tripleDes.Key = key24B;
Action do3des = () => EncryptDecryptAndDispose(tripleDes.CreateEncryptor(), tripleDes.CreateDecryptor(), data);
do3des.Repeat(n)
.OutputPerformance(sw, outputToConsole)();
tripleDes.Dispose();
// RSA
Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.WriteLine("RSA");
RSAParameters param = new RSAParameters();
param.Exponent = new byte[] {0, 1, 0};
var store = new X509Store(StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
X509Certificate cert = null;
foreach (X509Certificate cer in store.Certificates)
{
if (cer != null)
{
cert = cer;
break;
}
}
param.Modulus = cert.GetPublicKey();
var rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(param);
Action doRsa = () =>
{
//.........这里部分代码省略.........
示例7: btn_encrypt_Click
private void btn_encrypt_Click(object sender, EventArgs e)
{
String toEncrypt = tb_toEncrypt.Text;
if (String.IsNullOrEmpty(toEncrypt)) return;
AesCryptoServiceProvider aes = null;
MemoryStream ms = null;
CryptoStream cs = null;
try
{
var data = Encoding.UTF8.GetBytes(toEncrypt);
aes = new AesCryptoServiceProvider();
iv = aes.IV;
key = aes.Key;
ms = new MemoryStream();
cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(data, 0, data.Length);
cs.Flush();
if (!cs.HasFlushedFinalBlock)
cs.FlushFinalBlock();
cs.Close();
var encrypted = ms.ToArray();
tb_toDencryptUTF8.Text = Encoding.UTF8.GetString(encrypted);
tb_toDencryptB64.Text = Convert.ToBase64String(encrypted);
}
catch (Exception)
{
throw;
}
finally
{
if (aes != null) aes.Dispose();
if (cs != null) cs.Dispose();
if (ms != null) ms.Dispose();
}
}
示例8: DecryptData
/// <summary>
/// Decrypts plain text data using AES in CBC mode
/// </summary>
/// <param name="plainText"> cipher text data to be decrypted</param>
/// <param name="iv">IV to be used for decryption</param>
/// <returns>Returns decrypted plain text data</returns>
private byte[] DecryptData(byte[] iv, byte[] cipherText, int offset, int count) {
Debug.Assert((iv != null) && (cipherText != null));
Debug.Assert (offset > -1 && count > -1);
Debug.Assert ((count+offset) <= cipherText.Length);
byte[] plainText;
AesCryptoServiceProvider aesAlg;
// Try to get a provider from the pool.
// If no provider is available, create a new one.
if (!_cryptoProviderPool.TryDequeue(out aesAlg)) {
aesAlg = new AesCryptoServiceProvider();
try {
// Set various algorithm properties
aesAlg.Key = _columnEncryptionKey.EncryptionKey;
aesAlg.Mode = _cipherMode;
aesAlg.Padding = _paddingMode;
}
catch (Exception) {
if (aesAlg != null) {
aesAlg.Dispose();
}
throw;
}
}
try {
// Always set the IV since it changes from cell to cell.
aesAlg.IV = iv;
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream()) {
// Create an encryptor to perform the stream transform.
using (ICryptoTransform decryptor = aesAlg.CreateDecryptor()) {
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write)) {
// Decrypt the secret message and get the plain text data
csDecrypt.Write(cipherText, offset, count);
csDecrypt.FlushFinalBlock();
plainText = msDecrypt.ToArray();
}
}
}
}
finally {
// Return the provider to the pool.
_cryptoProviderPool.Enqueue(aesAlg);
}
return plainText;
}
示例9: EncryptData
/// <summary>
/// Encryption Algorithm
/// cell_iv = HMAC_SHA-2-256(iv_key, cell_data) truncated to 128 bits
/// cell_ciphertext = AES-CBC-256(enc_key, cell_iv, cell_data) with PKCS7 padding.
/// (optional) cell_tag = HMAC_SHA-2-256(mac_key, versionbyte + cell_iv + cell_ciphertext + versionbyte_length)
/// cell_blob = versionbyte + [cell_tag] + cell_iv + cell_ciphertext
/// </summary>
/// <param name="plainText">Plaintext data to be encrypted</param>
/// <param name="hasAuthenticationTag">Does the algorithm require authentication tag.</param>
/// <returns>Returns the ciphertext corresponding to the plaintext.</returns>
protected byte[] EncryptData(byte[] plainText, bool hasAuthenticationTag) {
// Empty values get encrypted and decrypted properly for both Deterministic and Randomized encryptions.
Debug.Assert(plainText != null);
byte[] iv = new byte[_BlockSizeInBytes];
// Prepare IV
// Should be 1 single block (16 bytes)
if (_isDeterministic) {
SqlSecurityUtility.GetHMACWithSHA256(plainText, _columnEncryptionKey.IVKey, iv);
}
else {
SqlSecurityUtility.GenerateRandomBytes(iv);
}
int numBlocks = plainText.Length / _BlockSizeInBytes + 1;
// Final blob we return = version + HMAC + iv + cipherText
const int hmacStartIndex = 1;
int authenticationTagLen = hasAuthenticationTag ? _KeySizeInBytes : 0;
int ivStartIndex = hmacStartIndex + authenticationTagLen;
int cipherStartIndex = ivStartIndex + _BlockSizeInBytes; // this is where hmac starts.
// Output buffer size = size of VersionByte + Authentication Tag + IV + cipher Text blocks.
int outputBufSize = sizeof(byte) + authenticationTagLen + iv.Length + (numBlocks*_BlockSizeInBytes);
byte[] outBuffer = new byte[outputBufSize];
// Store the version and IV rightaway
outBuffer[0] = _algorithmVersion;
Buffer.BlockCopy(iv, 0, outBuffer, ivStartIndex, iv.Length);
AesCryptoServiceProvider aesAlg;
// Try to get a provider from the pool.
// If no provider is available, create a new one.
if (!_cryptoProviderPool.TryDequeue(out aesAlg)) {
aesAlg = new AesCryptoServiceProvider();
try {
// Set various algorithm properties
aesAlg.Key = _columnEncryptionKey.EncryptionKey;
aesAlg.Mode = _cipherMode;
aesAlg.Padding = _paddingMode;
}
catch (Exception) {
if (aesAlg != null) {
aesAlg.Dispose();
}
throw;
}
}
try {
// Always set the IV since it changes from cell to cell.
aesAlg.IV = iv;
// Compute CipherText and authentication tag in a single pass
using (ICryptoTransform encryptor = aesAlg.CreateEncryptor()) {
Debug.Assert(encryptor.CanTransformMultipleBlocks, "AES Encryptor can transform multiple blocks");
int count = 0;
int cipherIndex = cipherStartIndex; // this is where cipherText starts
if (numBlocks > 1) {
count = (numBlocks - 1) * _BlockSizeInBytes;
cipherIndex += encryptor.TransformBlock(plainText, 0, count, outBuffer, cipherIndex);
}
byte[] buffTmp = encryptor.TransformFinalBlock(plainText, count, plainText.Length - count); // done encrypting
Buffer.BlockCopy(buffTmp, 0, outBuffer, cipherIndex, buffTmp.Length);
cipherIndex += buffTmp.Length;
}
if (hasAuthenticationTag) {
using (HMACSHA256 hmac = new HMACSHA256(_columnEncryptionKey.MACKey)) {
Debug.Assert(hmac.CanTransformMultipleBlocks, "HMAC can't transform multiple blocks");
hmac.TransformBlock(_version, 0, _version.Length, _version, 0);
hmac.TransformBlock(iv, 0, iv.Length, iv, 0);
// Compute HMAC on final block
hmac.TransformBlock(outBuffer, cipherStartIndex, numBlocks * _BlockSizeInBytes, outBuffer, cipherStartIndex);
hmac.TransformFinalBlock(_versionSize, 0, _versionSize.Length);
byte[] hash = hmac.Hash;
Debug.Assert(hash.Length >= authenticationTagLen, "Unexpected hash size");
Buffer.BlockCopy(hash, 0, outBuffer, hmacStartIndex, authenticationTagLen);
}
}
}
finally {
// Return the provider to the pool.
_cryptoProviderPool.Enqueue(aesAlg);
//.........这里部分代码省略.........