82 lines
2.5 KiB
C#
82 lines
2.5 KiB
C#
using Sarand.Net.Standard.Base.Core;
|
|
using Sarand.Net.Standard.Base.Utils;
|
|
using System;
|
|
using System.Text;
|
|
|
|
namespace Sarand.Net.Standard.Base.Helpers
|
|
{
|
|
public static class SacsEncryptionHelper
|
|
{
|
|
// --- Definitions ---
|
|
|
|
/// <summary>Number of byes in key. [32 bytes = 256 bits]</summary>
|
|
public static int KeyLength { get; } = 32;
|
|
/// <summary>Default encoding: UTF8.</summary>
|
|
public static Encoding DefaultEncoding { get; } = Encoding.UTF8;
|
|
|
|
// --- Key Management ---
|
|
|
|
// Symmetric Encryption in .NET Core
|
|
// System.Security.Cryptography implements and provides the APIs for encryption in .NET Core.
|
|
// Ref. https://damienbod.com/2020/08/19/symmetric-and-asymmetric-encryption-in-net-core/
|
|
public static bool IsBase64(String value, int expectedLength = 0)
|
|
{
|
|
try
|
|
{
|
|
Byte[] decoded = Convert.FromBase64String(value);
|
|
if (expectedLength > 0 && decoded.Length != expectedLength)
|
|
return false;
|
|
}
|
|
catch (Exception) { return false; }
|
|
return true;
|
|
}
|
|
public static String EncodePlainKey(String plainKey, int keyLength = 32, Encoding encoding = null)
|
|
{
|
|
if (String.IsNullOrWhiteSpace(plainKey))
|
|
throw new NotSupportedException("Plain key must not be null/blank");
|
|
// Ensure key if 32 bytes long.
|
|
while (StringUtil.GetLength(plainKey) < keyLength)
|
|
plainKey += plainKey;
|
|
plainKey = StringUtil.Left(plainKey, keyLength);
|
|
|
|
// Encode to base-64.
|
|
encoding = encoding ?? DefaultEncoding;
|
|
return Convert.ToBase64String(encoding.GetBytes(plainKey));
|
|
}
|
|
|
|
// Generate random key.
|
|
// NB Can use own key if suitable - 32 character value in base-64 format.
|
|
public static String InitSymmetricEncryptionKey()
|
|
{
|
|
var key = GetEncodedRandomString(KeyLength); // 256 bits.
|
|
return key;
|
|
}
|
|
public static string GetEncodedRandomString(int length)
|
|
{
|
|
var base64 = Convert.ToBase64String(GenerateRandomBytes(length));
|
|
return base64;
|
|
}
|
|
|
|
private static byte[] GenerateRandomBytes(int length)
|
|
{
|
|
var byteArray = new byte[length];
|
|
SacsRandomHelper.Fill(byteArray);
|
|
return byteArray;
|
|
}
|
|
|
|
// --- Authenticated Encryption ---
|
|
|
|
public static String EncryptAuthenticated(String text, String key, String purpose)
|
|
{
|
|
return SacsAuthenticatedEncryption.Encrypt(text, Convert.FromBase64String(key), purpose);
|
|
}
|
|
|
|
public static String DecryptAuthenticated(String encryptedText, String key, String purpose)
|
|
{
|
|
return SacsAuthenticatedEncryption.Decrypt(encryptedText, Convert.FromBase64String(key), purpose);
|
|
}
|
|
|
|
// --- The End ---
|
|
}
|
|
}
|