online_security_project/lib/Utils.cs

65 lines
1.6 KiB
C#
Raw Permalink Normal View History

2024-12-14 15:17:58 +00:00
using System.Linq;
2024-12-20 10:13:39 +00:00
using System.Text;
2024-12-14 15:17:58 +00:00
namespace lib;
2024-12-20 10:13:39 +00:00
public static class Utils
{
public static byte[] NumberToBytes(string Number)
{
if (Number.Any(c => !char.IsDigit(c)) || Number.Length > 16)
{
2024-12-14 15:17:58 +00:00
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 + '-';
2024-12-20 10:13:39 +00:00
for (int i = 0; i < Number.Length - 1; i += 2)
{
2024-12-14 15:17:58 +00:00
char c1 = Number[i];
char c2 = Number[i + 1];
res[i / 2] = (byte)((DigitToByte(c1) << 4) | DigitToByte(c2));
}
return res;
}
2024-12-20 10:13:39 +00:00
public static string BytesToNumber(byte[] Bytes)
{
2024-12-14 15:17:58 +00:00
string s = "";
2024-12-20 10:13:39 +00:00
foreach (byte b in Bytes)
{
2024-12-14 15:17:58 +00:00
byte b1 = (byte)((b >> 4) & 0b1111);
byte b2 = (byte)(b & 0b1111);
s = s + ByteToDigit(b1) + ByteToDigit(b2);
}
2024-12-20 10:13:39 +00:00
return new string(s.Where(char.IsDigit).ToArray());
2024-12-14 15:17:58 +00:00
}
2024-12-20 10:13:39 +00:00
public static byte DigitToByte(char c)
{
if (int.TryParse(c.ToString(), out int d))
{
2024-12-14 15:17:58 +00:00
return (byte)d;
}
2024-12-20 10:13:39 +00:00
else
{
2024-12-14 15:17:58 +00:00
return 0b1111; // empty, turned into '-' later to be discarded
}
}
2024-12-20 10:13:39 +00:00
public static char ByteToDigit(byte b)
{
2024-12-14 15:17:58 +00:00
byte offset = Encoding.ASCII.GetBytes("0")[0];
2024-12-20 10:13:39 +00:00
if (b == 0b1111)
{
2024-12-14 15:17:58 +00:00
return '-';
}
2024-12-20 10:13:39 +00:00
else
{
2024-12-14 15:17:58 +00:00
return Encoding.ASCII.GetChars([(byte)(b + offset)])[0];
}
}
}