Common
A library of common classes.
Cryptography.cs
1using System.IO;
2using System.Runtime.Serialization;
3using System.Security.Cryptography;
4
6{
10 public static class Cryptography
11 {
17 public static string DecryptTextFile(string path, byte[] key)
18 {
19 using (var stream = File.OpenRead(path))
20 using (var algorithm = Aes.Create())
21 {
22 var iv = new byte[algorithm.IV.Length];
23 stream.Read(iv, 0, iv.Length);
24
25 using (var encryptor = algorithm.CreateDecryptor(key, iv))
26 using (var crypto = new CryptoStream(stream, encryptor, CryptoStreamMode.Read))
27 using (var reader = new StreamReader(crypto))
28 {
29 return reader.ReadToEnd();
30 }
31 }
32 }
33
41 public static void EncryptToStream<T>(Stream stream, XmlObjectSerializer serializer, T graph, byte[] key)
42 {
43 using (var algorithm = Aes.Create())
44 using (var encryptor = algorithm.CreateEncryptor(key, algorithm.IV))
45 using (var crypto = new CryptoStream(stream, encryptor, CryptoStreamMode.Write))
46 {
47 stream.Write(algorithm.IV, 0, algorithm.IV.Length);
48 serializer.WriteObject(crypto, graph);
49 }
50 }
51
58 public static T DecryptFromStream<T>(Stream stream, XmlObjectSerializer serializer, byte[] key)
59 {
60 using (var algorithm = Aes.Create())
61 {
62 var iv = new byte[algorithm.IV.Length];
63 stream.Read(iv, 0, iv.Length);
64
65 using (var decryptor = algorithm.CreateDecryptor(key, iv))
66 using (var crypto = new CryptoStream(stream, decryptor, CryptoStreamMode.Read))
67 {
68 return (T)serializer.ReadObject(crypto);
69 }
70 }
71 }
72 }
73}
Contains methods related to encryption and decryption.
Definition: Cryptography.cs:11
static void EncryptToStream< T >(Stream stream, XmlObjectSerializer serializer, T graph, byte[] key)
Encrypts the object to the stream.
Definition: Cryptography.cs:41
static T DecryptFromStream< T >(Stream stream, XmlObjectSerializer serializer, byte[] key)
Decrypts the object from the stream.
Definition: Cryptography.cs:58
static string DecryptTextFile(string path, byte[] key)
Returns the decrypted text for the file at the specified path.
Definition: Cryptography.cs:17