-
Notifications
You must be signed in to change notification settings - Fork 110
/
RijndaelEncryptionService.cs
63 lines (57 loc) · 1.79 KB
/
RijndaelEncryptionService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using System;
using System.IO;
using System.Security.Cryptography;
using Rhino.ServiceBus.DataStructures;
using Rhino.ServiceBus.Internal;
namespace Rhino.ServiceBus.Impl
{
public class RijndaelEncryptionService : IEncryptionService
{
public byte[] Key { get; set;}
public RijndaelEncryptionService(byte[] key)
{
Key = key;
}
public EncryptedValue Encrypt(string value)
{
using (var rijndael = new RijndaelManaged())
{
rijndael.Key = Key;
rijndael.Mode = CipherMode.CBC;
rijndael.GenerateIV();
using (var encryptor = rijndael.CreateEncryptor())
using (var memoryStream = new MemoryStream())
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
using (var writer = new StreamWriter(cryptoStream))
{
writer.Write(value);
writer.Flush();
cryptoStream.Flush();
cryptoStream.FlushFinalBlock();
return new EncryptedValue
{
EncryptedBase64Value = Convert.ToBase64String(memoryStream.ToArray()),
Base64Iv = Convert.ToBase64String(rijndael.IV)
};
}
}
}
public string Decrypt(EncryptedValue encryptedValue)
{
var encrypted = Convert.FromBase64String(encryptedValue.EncryptedBase64Value);
using (var rijndael = new RijndaelManaged())
{
rijndael.Key = Key;
rijndael.IV = Convert.FromBase64String(encryptedValue.Base64Iv);
rijndael.Mode = CipherMode.CBC;
using (var decryptor = rijndael.CreateDecryptor())
using (var memoryStream = new MemoryStream(encrypted))
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
using (var reader = new StreamReader(cryptoStream))
{
return reader.ReadToEnd();
}
}
}
}
}