This commit is contained in:
Alexander
2023-01-20 16:22:37 +03:00
parent d3171a1164
commit c89a6b2a71
5 changed files with 112 additions and 3 deletions

View File

@@ -0,0 +1,48 @@
using System.Text;
using anbs_cp.Interfaces;
namespace anbs_cp.Classes.Encrypt;
/// <summary>
/// Ключ шифровки / расшифровки
/// </summary>
public class EncryptKey: IEncryptKey
{
/// <summary>
/// Конструктор по умолчанию
/// </summary>
/// <param name="key">Ключ в формате массива <see cref="byte"/></param>
public EncryptKey (byte[] key) => Key = key;
/// <summary>
/// Конструктор, принимающий строку и преобразующий в нужный формат
/// </summary>
/// <param name="key">Ключ в формате <see cref="string"/></param>
public EncryptKey (string key) => Key = Encoding.ASCII.GetBytes(key);
/// <summary>
/// Ключ
/// </summary>
public byte[] Key { get; set; }
/// <summary>
/// Получение ключа по умолчанию
/// </summary>
/// <returns><see cref="EncryptKey"/></returns>
public static EncryptKey GetDefault () => new(Enumerable.Range(0, 32).Select(static x => (byte)x).ToArray());
/// <summary>
/// Получение класса ключа
/// </summary>
/// <param name="key">Ключ в формате массива <see cref="byte"/></param>
/// <returns><see cref="EncryptKey"/></returns>
public static EncryptKey GetKey (byte[]? key) => key != null ? new(key) : GetDefault();
/// <summary>
/// Получение класса ключа
/// </summary>
/// <param name="key">Ключ в формате массива <see cref="byte"/></param>
/// <returns><see cref="EncryptKey"/></returns>
public static EncryptKey GetKey (string key) => !string.IsNullOrWhiteSpace(key) ? new(key) : GetDefault();
}

View File

@@ -0,0 +1,48 @@
using System.Security.Cryptography;
using System.Text;
namespace anbs_cp.Classes.Encrypt;
/// <summary>
/// Класс для шифровки строк
/// </summary>
public static class StringEncrypt
{
/// <summary>
/// Метод для шифрования строки <paramref name="text"/> с помощью ключа <paramref name="key"/>
/// </summary>
/// <param name="text">Строка, которая должна быть зашифрована</param>
/// <param name="key">Ключ шифрования (в случае <value>null</value>)</param>
/// <returns>Этот статический метод возвращает зашифрованную строку <paramref name="text"/> с помощью ключа шифрования <paramref name="key"/></returns>
public static string Encrypt (string text, EncryptKey? key = null)
{
using Aes aes = Aes.Create();
aes.Key = key?.Key ?? EncryptKey.GetDefault().Key;
using MemoryStream ms = new();
ms.Write(aes.IV);
using (CryptoStream cs = new(ms, aes.CreateEncryptor(), CryptoStreamMode.Write, true))
cs.Write(Encoding.UTF8.GetBytes(text));
return Convert.ToBase64String(ms.ToArray());
}
/// <summary>
/// Метод для дешифрования строки <paramref name="text"/> с помощью ключа <paramref name="key"/>
/// </summary>
/// <param name="text">Строка, которая должна быть дешифрована</param>
/// <param name="key">Ключ шифрования (в случае <value>null</value>)</param>
/// <returns>Этот статический метод возвращает дешифрованную строку <paramref name="text"/> с помощью ключа шифрования <paramref name="key"/></returns>
public static string Decrypt (string text, EncryptKey? key = null)
{
using MemoryStream ms = new(Convert.FromBase64String(text));
byte[] iv = new byte[16];
int _ = ms.Read(iv);
using Aes aes = Aes.Create();
aes.Key = key?.Key ?? EncryptKey.GetDefault().Key;
aes.IV = iv;
using CryptoStream cs = new(ms, aes.CreateDecryptor(), CryptoStreamMode.Read, true);
using MemoryStream output = new();
cs.CopyTo(output);
return Encoding.UTF8.GetString(output.ToArray());
}
}