online_security_project/lib/Utils.cs

53 lines
1.6 KiB
C#
Raw Normal View History

2024-12-14 15:17:58 +00:00
using System.Text;
using System.Linq;
namespace lib;
public static class Utils {
public static byte[] NumberToBytes(string Number) {
if(Number.Any(c => !char.IsDigit(c)) || Number.Length > 16) {
throw new Exception("Invalid arguments!");
}
byte[] res = Enumerable.Repeat((byte)0b1111_1111, 8).ToArray();
// Pad Number if needed to be of even length (because each 2 digits are turned into 1 byte)
Number = Number.Length % 2 == 0 ? Number : Number + '-';
for(int i = 0; i < Number.Length - 1; i += 2) {
char c1 = Number[i];
char c2 = Number[i + 1];
res[i / 2] = (byte)((DigitToByte(c1) << 4) | DigitToByte(c2));
}
return res;
}
public static string BytesToNumber(byte[] Bytes) {
string s = "";
foreach(byte b in Bytes) {
byte b1 = (byte)((b >> 4) & 0b1111);
byte b2 = (byte)(b & 0b1111);
s = s + ByteToDigit(b1) + ByteToDigit(b2);
}
return new string(s.Where(c => char.IsDigit(c)).ToArray());
}
public static byte DigitToByte(char c) {
if (int.TryParse(c.ToString(), out int d)) {
return (byte)d;
}
else {
return 0b1111; // empty, turned into '-' later to be discarded
}
}
public static char ByteToDigit(byte b) {
byte offset = Encoding.ASCII.GetBytes("0")[0];
if(b == 0b1111) {
return '-';
}
else {
return Encoding.ASCII.GetChars([(byte)(b + offset)])[0];
}
}
}