-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTripleDESCryptor.cs
61 lines (52 loc) · 2.03 KB
/
TripleDESCryptor.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
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace CryptStr
{
public class TripleDESCryptor : ICryptor
{
private readonly string Key;
private readonly string IV;
public TripleDESCryptor(string key, string iv)
{
Key = key;
IV = iv;
}
public string Encrypt(string value)
{
var provider = new TripleDESCryptoServiceProvider();
var encryptor = provider.CreateEncryptor(Convert.FromBase64String(Key), Convert.FromBase64String(IV));
using (var memoryStream = new MemoryStream())
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
var bytes = Encoding.UTF8.GetBytes(value);
cryptoStream.Write(bytes, 0, bytes.Length);
cryptoStream.FlushFinalBlock();
return Convert.ToBase64String(memoryStream.ToArray());
}
}
public string Decrypt(string value)
{
var provider = new TripleDESCryptoServiceProvider();
var decryptor = provider.CreateDecryptor(Convert.FromBase64String(Key), Convert.FromBase64String(IV));
var bytes = Convert.FromBase64String(value);
using (var memoryStream = new MemoryStream(bytes))
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
using (var streamReader = new StreamReader(cryptoStream))
{
return streamReader.ReadLine();
}
}
public static (string Key, string IV) Generate()
{
var provider = new TripleDESCryptoServiceProvider();
provider.GenerateKey();
provider.GenerateIV();
return (
Key: Convert.ToBase64String(provider.Key),
IV: Convert.ToBase64String(provider.IV)
);
}
}
}