/// <summary> /// Encrypts a file at <see cref="path"/> using the cert at <see cref="certCerPath"/> /// </summary> /// <param name="path"></param> /// <param name="certCerPath"></param> /// <returns></returns> public static void EncryptFile(string path, string certCerPath) { //test inputs TestEnDeCryptInputs(path, certCerPath, String.Empty); var encFile = Path.Combine(Path.GetDirectoryName(path) ?? Environment.CurrentDirectory, Path.GetFileName(path) + NF_CRYPTO_EXT); //import the cert var cert = new X509Certificate2(certCerPath); var pubKey = cert.PublicKey.Key; using (var aes = new AesManaged()) { aes.KeySize = 256; aes.BlockSize = 128; aes.Mode = CipherMode.CBC; using (var trns = aes.CreateEncryptor()) { var keyFm = new RSAPKCS1KeyExchangeFormatter(pubKey); var enKey = keyFm.CreateKeyExchange(aes.Key, aes.GetType()); var lenK = BitConverter.GetBytes(enKey.Length); var lIv = BitConverter.GetBytes(aes.IV.Length); using (var outFs = new FileStream(encFile, FileMode.Create)) { outFs.Write(lenK, 0, 4); outFs.Write(lIv, 0, 4); outFs.Write(enKey, 0, enKey.Length); outFs.Write(aes.IV, 0, aes.IV.Length); using (var cryptStream = new CryptoStream(outFs, trns, CryptoStreamMode.Write)) { var blockSz = aes.BlockSize / 8; var data = new byte[blockSz]; using (var inFs = new FileStream(path, FileMode.Open)) { var count = 0; do { count = inFs.Read(data, 0, blockSz); cryptStream.Write(data, 0, count); } while (count > 0); inFs.Close(); } cryptStream.FlushFinalBlock(); cryptStream.Close(); } outFs.Close(); } } } }
public byte[] EncryptWithX509(byte[] bytesToEncrypt) { // TODO: Exercise 1: Task 3a: Get the public key from the X509 certificate. //throw new NotImplementedException(); var provider = (RSACryptoServiceProvider)this._certificate.PublicKey.Key; // TODO: Exercise 1: Task 3b: Create an instance of the AesManaged algorithm. using (var algorithm = new AesManaged()) { // TODO: Exercise 1: Task 3c: Create an underlying stream for the unencrypted data. using (var outStream = new MemoryStream()) { // TODO: Exercise 1: Task 3d: Create an AES encryptor based on the key and IV. using (var encryptor = algorithm.CreateEncryptor()) { var keyFormatter = new RSAPKCS1KeyExchangeFormatter(provider); var encryptedKey = keyFormatter.CreateKeyExchange(algorithm.Key, algorithm.GetType()); // TODO: Exercise 1: Task 3e: Create byte arrays to get the length of the encryption key and IV. var keyLength = BitConverter.GetBytes(encryptedKey.Length); var ivLength = BitConverter.GetBytes(algorithm.IV.Length); // TODO: Exercise 1: Task 3f: Write the following to the out stream: // 1) the length of the encryption key. outStream.Write(keyLength, 0, keyLength.Length); // 2) the length of the IV. outStream.Write(ivLength, 0, ivLength.Length); // 3) the encryption key. outStream.Write(encryptedKey, 0, encryptedKey.Length); // 4) the IV. outStream.Write(algorithm.IV, 0, algorithm.IV.Length); // TODO: Exercise 1: Task 3g: Create a CryptoStream that will write the encypted data to the underlying buffer. using (var encrypt = new CryptoStream(outStream, encryptor, CryptoStreamMode.Write)) { // TODO: Exercise 1: Task 3h: Write all the data to the stream. encrypt.Write(bytesToEncrypt, 0, bytesToEncrypt.Length); encrypt.FlushFinalBlock(); // TODO: Exercise 1: Task 3i: Return the encrypted buffered data as a byte[]. return(outStream.ToArray()); } } } } }
byte[] EncryptWithX509(byte[] bytesToEncypt) { // Get the public key from the X509 certificate. This key will be used to encrypt the AesManaged encryption key. var provider = (RSACryptoServiceProvider)this._certificate.PublicKey.Key; // Create an instance of the AesManaged algorithm which we will use to encrypt the data with. using (var algorithm = new AesManaged()) { // Create an underlying stream which the decrypted data will be buffered too. using (var outStream = new MemoryStream()) { // Create an AES encryptor based on the key and IV. using (var encryptor = algorithm.CreateEncryptor()) { var keyFormatter = new RSAPKCS1KeyExchangeFormatter(provider); var encryptedKey = keyFormatter.CreateKeyExchange(algorithm.Key, algorithm.GetType()); // Create byte arrays to get the length of the encryption key and IV. var keyLength = BitConverter.GetBytes(encryptedKey.Length); var ivLength = BitConverter.GetBytes(algorithm.IV.Length); // Write the following to the out stream: // 1) the length of the encryption key. // 2) the length of the IV. // 3) the encryption key. // 4) the IV. // 5) the encrypted data. outStream.Write(keyLength, 0, 4); outStream.Write(ivLength, 0, 4); outStream.Write(encryptedKey, 0, encryptedKey.Length); outStream.Write(algorithm.IV, 0, algorithm.IV.Length); // Create a CryptoStream that will write the encypted data to the underlying buffer. using (var encrypt = new CryptoStream(outStream, encryptor, CryptoStreamMode.Write)) { // Write all the data to the stream. encrypt.Write(bytesToEncypt, 0, bytesToEncypt.Length); encrypt.FlushFinalBlock(); // Return the encrypted buffered data as a byte[]. return(outStream.ToArray()); } } } } }
// Encrypt a file using a public key. private static void EncryptFile(string inFile, RSACryptoServiceProvider rsaPublicKey) { 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(rsaPublicKey); 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 int startFileName = inFile.LastIndexOf("\\") + 1; // Change the file's extension to ".enc" string outFile = encrFolder + inFile.Substring(startFileName, inFile.LastIndexOf(".") - startFileName) + ".enc"; Directory.CreateDirectory(encrFolder); using (FileStream outFs = new FileStream(outFile, FileMode.Create)) { outFs.Write(LenK, 0, 4); outFs.Write(LenIV, 0, 4); outFs.Write(keyEncrypted, 0, lKey); outFs.Write(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 = inFs.Read(data, 0, blockSizeBytes); offset += count; outStreamEncrypted.Write(data, 0, count); bytesRead += blockSizeBytes; }while (count > 0); inFs.Close(); } outStreamEncrypted.FlushFinalBlock(); outStreamEncrypted.Close(); } outFs.Close(); } } } }
// Encrypt a file using a public key. private static MemoryStream EncryptFile(byte[] unencryptedData, RSACryptoServiceProvider rsaPublicKey) { MemoryStream stream = null; 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(rsaPublicKey); 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 stream = new MemoryStream(); try { stream.Write(LenK, 0, 4); stream.Write(LenIV, 0, 4); stream.Write(keyEncrypted, 0, lKey); stream.Write(aesManaged.IV, 0, lIV); // Now write the cipher text using // a CryptoStream for encrypting. CryptoStream outStreamEncrypted = new CryptoStream(stream, transform, CryptoStreamMode.Write); try { // 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; do { if (offset + blockSizeBytes <= unencryptedData.Length) { count = blockSizeBytes; } else { count = unencryptedData.Length - offset; } outStreamEncrypted.Write(unencryptedData, offset, count); offset += count; }while (offset < unencryptedData.Length); outStreamEncrypted.FlushFinalBlock(); } catch (Exception ex) { Console.WriteLine("Error : {0}", ex.Message); } } catch (Exception ex) { Console.WriteLine("Error : {0}", ex.Message); } stream.Position = 0; } } return(stream); }
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); } } } } } }
private static void EncryptData(Stream output, Stream input, AsymmetricAlgorithm rsaPublicKey) { using (AesManaged aesManaged = new AesManaged()) { aesManaged.KeySize = 256; aesManaged.BlockSize = 128; aesManaged.Mode = CipherMode.CBC; using (ICryptoTransform transform = aesManaged.CreateEncryptor()) { RSAPKCS1KeyExchangeFormatter keyFormatter = new RSAPKCS1KeyExchangeFormatter(rsaPublicKey); byte[] keyEncrypted = keyFormatter.CreateKeyExchange(aesManaged.Key, aesManaged.GetType()); 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); output.Write(LenK, 0, 4); output.Write(LenIV, 0, 4); output.Write(keyEncrypted, 0, lKey); output.Write(aesManaged.IV, 0, lIV); using (CryptoStream streamEncrypted = new CryptoStream(output, transform, CryptoStreamMode.Write)) { int count = 0; int offset = 0; int blockSizeBytes = aesManaged.BlockSize / 8; byte[] buffer = new byte[blockSizeBytes]; int bytesRead = 0; do { count = input.Read(buffer, 0, blockSizeBytes); offset += count; streamEncrypted.Write(buffer, 0, count); bytesRead += blockSizeBytes; }while (count > 0); input.Close(); streamEncrypted.FlushFinalBlock(); streamEncrypted.Close(); } } } }
public void Encrypt(Stream inStream, Stream outStream, AsymmetricAlgorithm rsaPublicKey) { 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(rsaPublicKey); 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 outStream.Write(LenK, 0, 4); outStream.Write(LenIV, 0, 4); outStream.Write(keyEncrypted, 0, lKey); outStream.Write(aesManaged.IV, 0, lIV); // Now write the cipher text using a CryptoStream for encrypting. using (CryptoStream outStreamEncrypted = new CryptoStream(outStream, transform, CryptoStreamMode.Write)) { { int bytesRead = 0; int blockSizeBytes = aesManaged.BlockSize / 8; byte[] data = new byte[blockSizeBytes]; while ((bytesRead = inStream.Read(data, 0, blockSizeBytes)) > 0) { outStreamEncrypted.Write(data, 0, bytesRead); } } outStreamEncrypted.FlushFinalBlock(); outStreamEncrypted.Close(); } } } }
public byte[] Encrypt(byte[] bytesToEncrypt, string certName) { var cert = GetCert(certName); var provider = cert.PublicKey.Key; using (var algorithm = new AesManaged()) using (var outStream = new MemoryStream()) using (var encryptor = algorithm.CreateEncryptor()) { var keyFormatter = new RSAPKCS1KeyExchangeFormatter(provider); var encyptedKey = keyFormatter.CreateKeyExchange(algorithm.Key, algorithm.GetType()); var keyLength = BitConverter.GetBytes(encyptedKey.Length); var ivLength = BitConverter.GetBytes(algorithm.IV.Length); outStream.Write(keyLength, 0, 4); outStream.Write(ivLength, 0, 4); outStream.Write(encyptedKey, 0, encyptedKey.Length); outStream.Write(algorithm.IV, 0, algorithm.IV.Length); using (var encrypt = new CryptoStream(outStream, encryptor, CryptoStreamMode.Write)) { encrypt.Write(bytesToEncrypt, 0, bytesToEncrypt.Length); encrypt.FlushFinalBlock(); return(outStream.ToArray()); } } }
public byte[] Encrypt(byte[] content, RSACng rsaPublicKey) { using (var aesManaged = new AesManaged()) { aesManaged.KeySize = 256; aesManaged.BlockSize = 128; aesManaged.Mode = CipherMode.CBC; using (var transform = aesManaged.CreateEncryptor()) { var keyFormatter = new RSAPKCS1KeyExchangeFormatter(rsaPublicKey); var keyEncrypted = keyFormatter.CreateKeyExchange(aesManaged.Key, aesManaged.GetType()); var LenK = new byte[4]; var LenIV = new byte[4]; var lKey = keyEncrypted.Length; LenK = BitConverter.GetBytes(lKey); var lIV = aesManaged.IV.Length; LenIV = BitConverter.GetBytes(lIV); using (var outFs = new MemoryStream()) { outFs.Write(LenK, 0, 4); outFs.Write(LenIV, 0, 4); outFs.Write(keyEncrypted, 0, lKey); outFs.Write(aesManaged.IV, 0, lIV); using (var outStreamEncrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write)) { // By encrypting a chunk at // a time, you can save memory // and accommodate large files. var count = 0; var offset = 0; // blockSizeBytes can be any arbitrary size. var blockSizeBytes = aesManaged.BlockSize / 8; var data = new byte[blockSizeBytes]; var bytesRead = 0; using (var inFs = new MemoryStream(content)) { do { count = inFs.Read(data, 0, blockSizeBytes); offset += count; outStreamEncrypted.Write(data, 0, count); bytesRead += blockSizeBytes; }while (count > 0); inFs.Close(); } outStreamEncrypted.FlushFinalBlock(); outStreamEncrypted.Close(); } outFs.Close(); return(outFs.ToArray()); } } } }