コード例 #1
0
        public static async Task Decrypt(string filePath, string certName, string password)
        {
            //Read the file in memory so we can overwrite the source with it's original file.
            //We also need it in memory so we can extract the key.
            var file         = (await File.ReadAllBytesAsync(filePath)).ToList();
            var encryptedKey = new Collection <byte>();
            //Checking the length so we know how much bytes we need to take from the file.
            //Different certificates can create different size of keys.
            var encryptLength = Encrypter.EncryptKey(Encoding.UTF8.GetBytes("string"), certName, password).Length;

            //Extract the key.
            for (var i = 0; i < encryptLength; i++)
            {
                encryptedKey.Add(file[i]);
            }
            file.RemoveRange(0, encryptLength);

            var decryptedKey = DecryptKey(encryptedKey.ToArray(), certName, password);

            using (var managed = new AesManaged())
            {
                //We're using AES encryption, but this time we do not generate the key but pass our decrypted key.
                Aes aesKey = Aes.Create();
                aesKey.Key = decryptedKey;
                byte[] ivKey = new byte[aesKey.IV.Length];
                Array.Copy(aesKey.Key, ivKey, aesKey.IV.Length);
                aesKey.IV = ivKey;
                var decryptor = aesKey.CreateDecryptor();

                //We're using truncate mode, so the file opens up and is empty.
                using (var fileStream = new FileStream(filePath, FileMode.Truncate))
                    using (var decryptStream = new CryptoStream(fileStream, decryptor, CryptoStreamMode.Write))
                        using (var encryptedFileStream = new MemoryStream(file.ToArray()))
                            await encryptedFileStream.CopyToAsync(decryptStream);
            }
        }
コード例 #2
0
 static void Main(string[] args)
 {
     Encrypter.Encrypt(File, CertPath, CertPassword).Wait();
     Console.ReadKey();
     Decrypter.Decrypt(File, CertPath, CertPassword).Wait();
 }