diff --git a/anbs_cp/Classes/Encrypt/StringEncrypt.cs b/anbs_cp/Classes/Encrypt/StringEncrypt.cs
index 71f11f2..46a90cd 100644
--- a/anbs_cp/Classes/Encrypt/StringEncrypt.cs
+++ b/anbs_cp/Classes/Encrypt/StringEncrypt.cs
@@ -1,6 +1,5 @@
-using System.Text;
-
-using gfoidl.Base64;
+using System.Security.Cryptography;
+using System.Text;
namespace anbs_cp.Classes.Encrypt;
@@ -10,42 +9,112 @@ namespace anbs_cp.Classes.Encrypt;
public static class StringEncrypt
{
///
- /// Метод для шифрования строки
+ /// Получение ключа из строки
///
- /// Строка, которая должна быть зашифрована
- /// Этот статический метод возвращает зашифрованную строку
- public static string Encrypt (string text)
+ /// Ключ-строка
+ /// Хэш-ключ
+ /// Ключ
+ private static byte[] KeyFromString (string s, byte[] salt)
{
- byte[] byteText = Encoding.UTF8.GetBytes(text);
- return Base64.Url.Encode(byteText);
+ // Создаю хэшер
+ using Rfc2898DeriveBytes hasher = new(s, salt, 1000, HashAlgorithmName.SHA256);
+
+ // Получаю ключ
+ return hasher.GetBytes(32);
}
///
- /// Метод для шифрования массива строк
+ /// Метод для шифрования строки
///
- /// Массив строк
- /// Этот статический метод возвращает зашифрованную строку из массива
- public static string EncryptBytes (byte[] bytes) => Base64.Url.Encode(bytes);
+ /// Строка, которая должна быть зашифрована
+ /// Ключ
+ /// Этот статический метод возвращает зашифрованную строку
+ public static string Encrypt (string text, string key)
+ {
+ // Создаю криптограф
+ using Aes aes = Aes.Create();
+
+ // Получаю ключ
+ aes.Key = KeyFromString(key, aes.IV);
+
+ // Открываю поток
+ 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());
+ }
///
/// Метод для дешифрования строки
///
/// Строка, которая должна быть дешифрована
+ /// Ключ
/// Этот статический метод возвращает дешифрованную строку
- public static string Decrypt (string text)
+ public static string Decrypt (string text, string key)
{
- string guidBase64Url = text.Replace('+', '-').Replace('/', '_').TrimEnd('=');
- return Encoding.UTF8.GetString(Base64.Url.Decode(guidBase64Url));
+ // Открываю поток в памяти
+ using MemoryStream ms = new(Convert.FromBase64String(text));
+
+ // Задаю ключ
+ byte[] iv = new byte[16];
+
+ // Читаю его
+ _ = ms.Read(iv);
+
+ // Создаю криптограф
+ using Aes aes = Aes.Create();
+
+ // Получаю ключ
+ aes.Key = KeyFromString(key, iv);
+
+ // присваиваю ключ
+ 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());
}
///
- /// Метод для дешифрования в массив byte
+ /// Декодирует зашифрованную строку в HTML-пригодный формат
///
- /// Строка, которая должна быть дешифрована
- /// Этот статический метод возвращает дешифрованный массива byte[]
- public static byte[] DecryptBytes (string text)
+ /// Зашифрованная строка
+ /// Этот статический метод возвращает дешифрованную строку
+ public static string Base64UrlEncode(string text) => text.TrimEnd('=').Replace('+', '-').Replace('/', '_');
+
+ ///
+ /// Раскодирует из декодированной строки в HTML-пригодный формат
+ ///
+ /// Декодированная строка
+ /// Этот статический метод возвращает шифрованную строку
+ public static string Base64UrlDecode(string text)
{
- string guidBase64Url = text.Replace('+', '-').Replace('/', '_').TrimEnd('=');
- return Base64.Url.Decode(guidBase64Url);
+ string result = text.Replace('_', '/').Replace('-', '+');
+ switch (result.Length % 4)
+ {
+ case 2:
+ result += "==";
+ break;
+ case 3:
+ result += "=";
+ break;
+ }
+ return result;
}
}
\ No newline at end of file
diff --git a/anbs_cp/Interfaces/IEncryptKey.cs b/anbs_cp/Interfaces/IEncryptKey.cs
deleted file mode 100644
index fedd43a..0000000
--- a/anbs_cp/Interfaces/IEncryptKey.cs
+++ /dev/null
@@ -1,12 +0,0 @@
-namespace anbs_cp.Interfaces;
-
-///
-/// Интерфейс ключа
-///
-public interface IEncryptKey
-{
- ///
- /// Ключ
- ///
- public byte[] Key { get; set; }
-}
\ No newline at end of file
diff --git a/anbs_cp/anbs_cp.csproj b/anbs_cp/anbs_cp.csproj
index 2fb692f..95cc409 100644
--- a/anbs_cp/anbs_cp.csproj
+++ b/anbs_cp/anbs_cp.csproj
@@ -2,7 +2,7 @@
net7.0
- 2023.827.0
+ 2023.902.0
Александр Бабаев
Набор компонентов ANB Software
Библиотека полезных методов языка C#
diff --git a/anbsoftware.componentspack.sln.DotSettings b/anbsoftware.componentspack.sln.DotSettings
index 977eb0e..25bcf0b 100644
--- a/anbsoftware.componentspack.sln.DotSettings
+++ b/anbsoftware.componentspack.sln.DotSettings
@@ -17,10 +17,13 @@
True
True
True
+ True
True
+ True
True
True
True
True
True
- True
\ No newline at end of file
+ True
+ True
\ No newline at end of file