64 lines
No EOL
2.1 KiB
C#
64 lines
No EOL
2.1 KiB
C#
using System;
|
|
using System.IO;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
|
|
namespace Cryptura;
|
|
|
|
public static class EncryptionLibrary
|
|
{
|
|
private const int SaltSize = 16;
|
|
private const int KeySize = 32;
|
|
private const int Iterations = 10000;
|
|
|
|
public static string Encrypt(string masterPassword, string plainPassword)
|
|
{
|
|
byte[] salt = new byte[SaltSize];
|
|
using (var rng = new RNGCryptoServiceProvider())
|
|
{
|
|
rng.GetBytes(salt);
|
|
}
|
|
|
|
using (var aesAlg = Aes.Create())
|
|
{
|
|
var key = new Rfc2898DeriveBytes(masterPassword, salt, Iterations);
|
|
aesAlg.Key = key.GetBytes(KeySize);
|
|
aesAlg.IV = new byte[16];
|
|
|
|
using (var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV))
|
|
using (var ms = new MemoryStream())
|
|
{
|
|
ms.Write(salt, 0, salt.Length);
|
|
|
|
using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
|
|
using (var writer = new StreamWriter(cs))
|
|
{
|
|
writer.Write(plainPassword);
|
|
}
|
|
|
|
return Convert.ToBase64String(ms.ToArray());
|
|
}
|
|
}
|
|
}
|
|
public static string Decrypt(string masterPassword, string encryptedPassword)
|
|
{
|
|
byte[] cipherBytes = Convert.FromBase64String(encryptedPassword);
|
|
byte[] salt = new byte[SaltSize];
|
|
Array.Copy(cipherBytes, 0, salt, 0, SaltSize); // Extract the salt
|
|
|
|
using (var aesAlg = Aes.Create())
|
|
{
|
|
var key = new Rfc2898DeriveBytes(masterPassword, salt, Iterations);
|
|
aesAlg.Key = key.GetBytes(KeySize);
|
|
aesAlg.IV = new byte[16];
|
|
|
|
using (var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV))
|
|
using (var ms = new MemoryStream(cipherBytes, SaltSize, cipherBytes.Length - SaltSize))
|
|
using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
|
|
using (var reader = new StreamReader(cs))
|
|
{
|
|
return reader.ReadToEnd();
|
|
}
|
|
}
|
|
}
|
|
} |