sharp-chat/SharpChat/Extensions.cs

35 lines
1.1 KiB
C#
Raw Normal View History

2023-02-07 15:01:56 +00:00
using System.IO;
2022-08-30 15:00:58 +00:00
using System.Security.Cryptography;
using System.Text;
namespace SharpChat {
public static class Extensions {
2023-02-07 15:01:56 +00:00
public static string GetSignedHash(this string str, string key = null) {
return Encoding.UTF8.GetBytes(str).GetSignedHash(key);
}
2022-08-30 15:00:58 +00:00
public static string GetSignedHash(this byte[] bytes, string key = null) {
2023-02-07 15:01:56 +00:00
key ??= File.Exists(@"login_key.txt") ? File.ReadAllText(@"login_key.txt") : @"woomy";
2022-08-30 15:00:58 +00:00
2023-02-07 15:01:56 +00:00
StringBuilder sb = new();
2022-08-30 15:00:58 +00:00
2023-02-07 15:01:56 +00:00
using(HMACSHA256 algo = new(Encoding.UTF8.GetBytes(key))) {
2022-08-30 15:00:58 +00:00
byte[] hash = algo.ComputeHash(bytes);
2023-02-07 15:01:56 +00:00
foreach(byte b in hash)
2022-08-30 15:00:58 +00:00
sb.AppendFormat(@"{0:x2}", b);
}
return sb.ToString();
}
public static string GetIdString(this byte[] buffer) {
const string id_chars = @"abcdefghijklmnopqrstuvwxyz0123456789-_ABCDEFGHIJKLMNOPQRSTUVWXYZ";
2023-02-07 15:01:56 +00:00
StringBuilder sb = new();
2022-08-30 15:00:58 +00:00
foreach(byte b in buffer)
sb.Append(id_chars[b % id_chars.Length]);
return sb.ToString();
}
}
}