Skip to content

Instantly share code, notes, and snippets.

@pitermarx
Last active August 6, 2021 09:35
Show Gist options
  • Save pitermarx/c370e6747e8473c16658474e00738996 to your computer and use it in GitHub Desktop.
Save pitermarx/c370e6747e8473c16658474e00738996 to your computer and use it in GitHub Desktop.
.net utils
// .Net Symetric encryption
public class Encryptor<T>
where T : SymmetricAlgorithm, new()
{
private const int KeySize = 256;
private readonly byte[] vectorBytes;
private readonly byte[] keyBytes;
public Encryptor(
string password,
string salt = "my random salt 1", // Random - Salt
string vector = "1234567890123456") // Random - 16 lenght
{
vectorBytes = Encoding.ASCII.GetBytes(vector);
var passwordBytes = new Rfc2898DeriveBytes(
password,
Encoding.ASCII.GetBytes(salt),
hashAlgorithm: HashAlgorithmName.SHA1,
iterations: 2);
keyBytes = passwordBytes.GetBytes(KeySize / 8);
}
public string EncryptString(string value)
{
var valueBytes = Encoding.UTF8.GetBytes(value);
byte[] encrypted;
using (var cipher = new T())
{
cipher.Mode = CipherMode.CBC;
using (var encryptor = cipher.CreateEncryptor(keyBytes, vectorBytes))
using (var to = new MemoryStream())
using (var writer = new CryptoStream(to, encryptor, CryptoStreamMode.Write))
{
writer.Write(valueBytes, 0, valueBytes.Length);
writer.FlushFinalBlock();
encrypted = to.ToArray();
}
cipher.Clear();
}
return Convert.ToBase64String(encrypted);
}
public string DecryptString(string value)
{
byte[] valueBytes = Convert.FromBase64String(value);
byte[] decrypted;
int decryptedByteCount = 0;
using (var cipher = new T())
{
cipher.Mode = CipherMode.CBC;
using (var decryptor = cipher.CreateDecryptor(keyBytes, vectorBytes))
using (var from = new MemoryStream(valueBytes))
using (var reader = new CryptoStream(from, decryptor, CryptoStreamMode.Read))
{
decrypted = new byte[valueBytes.Length];
decryptedByteCount = reader.Read(decrypted, 0, decrypted.Length);
}
cipher.Clear();
}
return Encoding.UTF8.GetString(decrypted, 0, decryptedByteCount);
}
}
public static class FastActivator
{
private static readonly Type ObjectType = typeof(object);
private static readonly Type ConstructorType = typeof(Func<object>);
private static readonly ConcurrentDictionary<Type, Func<object>> ConstructorsCache = new ConcurrentDictionary<Type, Func<object>>();
public static object New<T>()
{
return (T)New(typeof(T));
}
public static object New(Type type)
{
try
{
return ConstructorsCache.GetOrAdd(type, CreateConstructor)();
}
catch (Exception exc)
{
throw new Exception(string.Format("FastActivator couldn't create instance for type '{0}' from assemebly '{1}'",
type.FullName, type.AssemblyQualifiedName), exc);
}
}
private static Func<object> CreateConstructor(Type type)
{
if (type.IsClass)
{
// classes
var dynMethod = new DynamicMethod("_", type, null);
var ilGen = dynMethod.GetILGenerator();
ilGen.Emit(OpCodes.Newobj, type.GetConstructor(Type.EmptyTypes));
ilGen.Emit(OpCodes.Ret);
return (Func<object>)dynMethod.CreateDelegate(ConstructorType);
}
else
{
// structs
var dynMethod = new DynamicMethod("_", ObjectType, null);
var ilGen = dynMethod.GetILGenerator();
var lv = ilGen.DeclareLocal(type);
ilGen.Emit(OpCodes.Ldloca_S, lv);
ilGen.Emit(OpCodes.Initobj, type);
ilGen.Emit(OpCodes.Ldloc_0);
ilGen.Emit(OpCodes.Box, type);
ilGen.Emit(OpCodes.Ret);
return (Func<object>)dynMethod.CreateDelegate(ConstructorType);
}
}
}
/// <summary> Like Guid, but shorter and url safe </summary>
public struct ShortGuid
{
/// <summary> A read-only instance of the ShortGuid class whose value is guaranteed to be all zeroes. </summary>
public static readonly ShortGuid Empty = new ShortGuid(Guid.Empty);
public readonly Guid Guid;
public readonly string Value;
/// <summary> Creates a ShortGuid from a Guid </summary>
public ShortGuid(Guid guid)
{
Value = Encode(guid);
Guid = guid;
}
/// <summary> Encodes the given Guid as a base64 string that is 22 characters long. </summary>
private static string Encode(Guid guid)
{
string encoded = Convert.ToBase64String(guid.ToByteArray());
return encoded.Replace("/", "_").Replace("+", "-").Substring(0, 22);
}
/// <summary> Decodes the given base64 string </summary>
private static Guid Decode(string value)
{
value = value.Replace("_", "/").Replace("-", "+") + "==";
return new Guid(Convert.FromBase64String(value));
}
/// <summary> Determines if both ShortGuids have the same underlying Guid value. </summary>
public static bool operator ==(ShortGuid x, ShortGuid y) => x.Guid.Equals(y.Guid);
/// <summary> Determines if both ShortGuids do not have the same underlying Guid value. </summary>
public static bool operator !=(ShortGuid x, ShortGuid y) => !(x == y);
/// <summary> Implicitly converts the ShortGuid to it's string equivilent </summary>
public static implicit operator string(ShortGuid shortGuid) => shortGuid.Value;
/// <summary> Implicitly converts the ShortGuid to it's Guid equivilent </summary>
public static implicit operator Guid(ShortGuid shortGuid) => shortGuid.Guid;
/// <summary> Implicitly converts the Guid to a ShortGuid </summary>
public static implicit operator ShortGuid(Guid guid) => new ShortGuid(guid);
/// <summary> Implicitly converts the string to a ShortGuid </summary>
public static implicit operator ShortGuid(string @string) => new ShortGuid(Decode(@string));
/// <summary> Initialises a new instance of the ShortGuid class </summary>
public static ShortGuid NewGuid() => new ShortGuid(Guid.NewGuid());
/// <summary> Returns the base64 encoded guid as a string </summary>
public override string ToString() => Value;
/// <summary>
/// Returns a value indicating whether this instance and a
/// specified Object represent the same type and value.
/// </summary>
/// <param name="obj">The object to compare</param>
/// <returns></returns>
public override bool Equals(object obj)
{
switch (obj)
{
case ShortGuid guid:
return Guid.Equals(guid.Guid);
case Guid _:
return Guid.Equals(obj);
case string _:
return Value.Equals(obj);
default:
return false;
}
}
/// <summary> Returns the HashCode for underlying Guid. </summary>
public override int GetHashCode() => Guid.GetHashCode();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment