本文整理汇总了C#中System.Security.Cryptography.CryptoStream.WriteAsync方法的典型用法代码示例。如果您正苦于以下问题:C# CryptoStream.WriteAsync方法的具体用法?C# CryptoStream.WriteAsync怎么用?C# CryptoStream.WriteAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Security.Cryptography.CryptoStream
的用法示例。
在下文中一共展示了CryptoStream.WriteAsync方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: EncryptAsync
public async static Task<string> EncryptAsync(string plainText, string passPhrase)
{
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
using (var password = new Rfc2898DeriveBytes(passPhrase, InitVectorBytes))
{
var keyBytes = password.GetBytes(Keysize / 8);
using (var symmetricKey = new RijndaelManaged())
{
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.PKCS7;
using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, InitVectorBytes))
{
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
await cryptoStream.WriteAsync(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
var cipherTextBytes = memoryStream.ToArray();
return Convert.ToBase64String(cipherTextBytes);
}
}
}
}
}
}
示例2: PerformCryptography
private async Task<byte[]> PerformCryptography(ICryptoTransform cryptoTransform, byte[] data)
{
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write))
{
await cryptoStream.WriteAsync(data, 0, data.Length);
cryptoStream.FlushFinalBlock();
return memoryStream.ToArray();
}
}
}
示例3: EncryptStringAsync
public static async Task<string> EncryptStringAsync(string plainData, byte[] key, byte[] iv, CancellationToken cancellationToken = default(CancellationToken))
{
byte[] cipherMessageBytes;
using (var rijndael = Rijndael.Create())
using (var memoryStream = new MemoryStream())
using (var cryptoStream = new CryptoStream(memoryStream, rijndael.CreateEncryptor(key, iv), CryptoStreamMode.Write))
{
var plainDataInBytes = Encoding.UTF8.GetBytes(plainData);
await cryptoStream.WriteAsync(plainDataInBytes, 0, plainDataInBytes.Length, cancellationToken).ConfigureAwait(false);
cryptoStream.FlushFinalBlock();
cipherMessageBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
rijndael.Clear();
}
return Convert.ToBase64String(cipherMessageBytes);
}
示例4: AliceSendsDataAsync
private async Task<byte[]> AliceSendsDataAsync(string message)
{
WriteLine($"Alice sends message: {message}");
byte[] rawData = Encoding.UTF8.GetBytes(message);
byte[] encryptedData = null;
using (var aliceAlgorithm = new ECDiffieHellmanCng(_aliceKey))
using (CngKey bobPubKey = CngKey.Import(_bobPubKeyBlob,
CngKeyBlobFormat.EccPublicBlob))
{
byte[] symmKey = aliceAlgorithm.DeriveKeyMaterial(bobPubKey);
WriteLine("Alice creates this symmetric key with " +
$"Bobs public key information: { Convert.ToBase64String(symmKey)}");
using (var aes = new AesCryptoServiceProvider())
{
aes.Key = symmKey;
aes.GenerateIV();
using (ICryptoTransform encryptor = aes.CreateEncryptor())
using (var ms = new MemoryStream())
{
// create CryptoStream and encrypt data to send
using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
// write initialization vector not encrypted
await ms.WriteAsync(aes.IV, 0, aes.IV.Length);
await cs.WriteAsync(rawData, 0, rawData.Length);
}
encryptedData = ms.ToArray();
}
aes.Clear();
}
}
WriteLine($"Alice: message is encrypted: {Convert.ToBase64String(encryptedData)}"); ;
WriteLine();
return encryptedData;
}
示例5: File
private async static Task File(string inFile, string outFile, RSACryptoServiceProvider key)
{
RSACryptoServiceProvider rsaPrivateKey = key;
// Create instance of AesManaged for
// symetric decryption of the data.
using (AesManaged aesManaged = new AesManaged())
{
aesManaged.KeySize = 256;
aesManaged.BlockSize = 128;
aesManaged.Mode = CipherMode.CBC;
// Create byte arrays to get the length of
// the encrypted key and IV.
// These values were stored as 4 bytes each
// at the beginning of the encrypted package.
byte[] LenK = new byte[4];
byte[] LenIV = new byte[4];
// Consruct the file name for the decrypted file.
// Use FileStream objects to read the encrypted
// file (inFs) and save the decrypted file (outFs).
using (FileStream inFs = new FileStream(inFile, FileMode.Open))
{
inFs.Seek(0, SeekOrigin.Begin);
inFs.Seek(0, SeekOrigin.Begin);
await inFs.ReadAsync(LenK, 0, 3);
inFs.Seek(4, SeekOrigin.Begin);
await inFs.ReadAsync(LenIV, 0, 3);
// Convert the lengths to integer values.
int lenK = BitConverter.ToInt32(LenK, 0);
int lenIV = BitConverter.ToInt32(LenIV, 0);
// Determine the start postition of
// the ciphter text (startC)
// and its length(lenC).
int startC = lenK + lenIV + 8;
int lenC = (int)inFs.Length - startC;
// Create the byte arrays for
// the encrypted AesManaged key,
// the IV, and the cipher text.
byte[] KeyEncrypted = new byte[lenK];
byte[] IV = new byte[lenIV];
// Extract the key and IV
// starting from index 8
// after the length values.
inFs.Seek(8, SeekOrigin.Begin);
await inFs.ReadAsync(KeyEncrypted, 0, lenK);
inFs.Seek(8 + lenK, SeekOrigin.Begin);
await inFs.ReadAsync(IV, 0, lenIV);
// Use RSACryptoServiceProvider
// to decrypt the AesManaged key.
byte[] KeyDecrypted = rsaPrivateKey.Decrypt(KeyEncrypted, false);
// Decrypt the key.
using (ICryptoTransform transform = aesManaged.CreateDecryptor(KeyDecrypted, IV))
{
// Decrypt the cipher text from
// from the FileSteam of the encrypted
// file (inFs) into the FileStream
// for the decrypted file (outFs).
using (FileStream outFs = new FileStream(outFile, FileMode.Create))
{
int count = 0;
int offset = 0;
int blockSizeBytes = aesManaged.BlockSize / 8;
byte[] data = new byte[blockSizeBytes];
// By decrypting a chunk a time,
// you can save memory and
// accommodate large files.
// Start at the beginning
// of the cipher text.
inFs.Seek(startC, SeekOrigin.Begin);
using (CryptoStream outStreamDecrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write))
{
do
{
count = await inFs.ReadAsync(data, 0, blockSizeBytes);
offset += count;
await outStreamDecrypted.WriteAsync(data, 0, count);
}
while (count > 0);
}
}
}
}
}
}
示例6: EncryptFile
private async static Task EncryptFile(string inputFilename, string outputFilename, string password)
{
var buffer = new byte[1024 * 1024 * 1];
var sha256 = SHA256.Create();
var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(password));
using (FileStream input = new FileStream(inputFilename, FileMode.Open, FileAccess.Read, FileShare.None))
{
using (FileStream outputRaw = new FileStream(outputFilename, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
var aes = Aes.Create();
var iv = aes.IV;
var encryptor = aes.CreateEncryptor(hash, iv);
BinaryWriter bw = new BinaryWriter(outputRaw);
bw.Write(iv.Length);
bw.Write(iv);
bw.Flush();
int bytesRead;
using (var output = new CryptoStream(outputRaw, encryptor, CryptoStreamMode.Write))
{
do
{
bytesRead = await input.ReadAsync(buffer, 0, buffer.Length);
if (bytesRead > 0)
{
await output.WriteAsync(buffer, 0, bytesRead);
}
}
while (bytesRead > 0);
}
}
}
}
示例7: BobReceivesDataAsync
private async Task BobReceivesDataAsync(byte[] encryptedData)
{
WriteLine("Bob receives encrypted data");
byte[] rawData = null;
var aes = new AesCryptoServiceProvider();
int nBytes = aes.BlockSize >> 3;
byte[] iv = new byte[nBytes];
for (int i = 0; i < iv.Length; i++)
iv[i] = encryptedData[i];
using (var bobAlgorithm = new ECDiffieHellmanCng(_bobKey))
using (CngKey alicePubKey = CngKey.Import(_alicePubKeyBlob,
CngKeyBlobFormat.EccPublicBlob))
{
byte[] symmKey = bobAlgorithm.DeriveKeyMaterial(alicePubKey);
WriteLine("Bob creates this symmetric key with " +
$"Alices public key information: {Convert.ToBase64String(symmKey)}");
aes.Key = symmKey;
aes.IV = iv;
using (ICryptoTransform decryptor = aes.CreateDecryptor())
using (MemoryStream ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write))
{
await cs.WriteAsync(encryptedData, nBytes, encryptedData.Length - nBytes);
}
rawData = ms.ToArray();
WriteLine($"Bob decrypts message to: {Encoding.UTF8.GetString(rawData)}");
}
aes.Clear();
}
}
示例8: File
private async static Task File(string inFile, string outFile, RSACryptoServiceProvider key)
{
using (AesManaged aesManaged = new AesManaged())
{
// Create instance of AesManaged for
// symetric encryption of the data.
aesManaged.KeySize = 256;
aesManaged.BlockSize = 128;
aesManaged.Mode = CipherMode.CBC;
using (ICryptoTransform transform = aesManaged.CreateEncryptor())
{
RSAPKCS1KeyExchangeFormatter keyFormatter = new RSAPKCS1KeyExchangeFormatter(key);
byte[] keyEncrypted = keyFormatter.CreateKeyExchange(aesManaged.Key, aesManaged.GetType());
// Create byte arrays to contain
// the length values of the key and IV.
byte[] LenK = new byte[4];
byte[] LenIV = new byte[4];
int lKey = keyEncrypted.Length;
LenK = BitConverter.GetBytes(lKey);
int lIV = aesManaged.IV.Length;
LenIV = BitConverter.GetBytes(lIV);
// Write the following to the FileStream
// for the encrypted file (outFs):
// - length of the key
// - length of the IV
// - ecrypted key
// - the IV
// - the encrypted cipher content
using (FileStream outFs = new FileStream(outFile, FileMode.Create))
{
await outFs.WriteAsync(LenK, 0, 4);
await outFs.WriteAsync(LenIV, 0, 4);
await outFs.WriteAsync(keyEncrypted, 0, lKey);
await outFs.WriteAsync(aesManaged.IV, 0, lIV);
// Now write the cipher text using
// a CryptoStream for encrypting.
using (CryptoStream outStreamEncrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write))
{
// By encrypting a chunk at
// a time, you can save memory
// and accommodate large files.
int count = 0;
int offset = 0;
// blockSizeBytes can be any arbitrary size.
int blockSizeBytes = aesManaged.BlockSize / 8;
byte[] data = new byte[blockSizeBytes];
int bytesRead = 0;
using (FileStream inFs = new FileStream(inFile, FileMode.Open))
{
do
{
count = await inFs.ReadAsync(data, 0, blockSizeBytes);
offset += count;
await outStreamEncrypted.WriteAsync(data, 0, count);
bytesRead += blockSizeBytes;
}
while (count > 0);
}
}
}
}
}
}
示例9: Main
public static void Main(string[] args)
{
System.Console.WriteLine(
typeof(object).AssemblyQualifiedName
);
// http://www.drdobbs.com/windows/programming-public-key-cryptostreams-par/184416907
// X:\jsc.svn\examples\java\hybrid\JVMCLRRSACryptoServiceProviderExport\JVMCLRRSACryptoServiceProviderExport\Program.cs
//var dwKeySize = (0x100 + 0x100) * 8;
var dwKeySize = 128 * 8;
var MaxData = (dwKeySize - 384) / 8 + 7;
var RSA = new RSACryptoServiceProvider(
dwKeySize: dwKeySize,
parameters: new CspParameters { }
);
RSAParameters p = RSA.ExportParameters(includePrivateParameters: false);
var value = RSA.Encrypt(
Encoding.UTF8.GetBytes("hello from server"), fOAEP: true
//Encoding.UTF8.GetBytes("hello from server"), fOAEP: false
);
var data = new MemoryStream();
var goo = new CryptoStream(data, new RSAEnCryptoTransform(RSA), CryptoStreamMode.Write);
var text = Encoding.UTF8.GetBytes("hello".PadRight(8000) + "world");
goo.WriteAsync(text, 0, text.Length).Wait();
goo.FlushFinalBlock();
goo.FlushAsync().Wait();
var foo = new CryptoStream(data, new RSADeCryptoTransform(RSA), CryptoStreamMode.Read);
//var buffer = new byte[100];
//var buffer = new byte[MaxData];
var buffer = new byte[0x1000];
var result = foo.Read(buffer, 0, buffer.Length);
//var result = foo.ReadAsync(buffer, 0, buffer.Length).Result;
CLRProgram.CLRMain();
}