From 8d2a2cd5de40e2b94ef5007c32832ed9a063dc40 Mon Sep 17 00:00:00 2001 From: chai <215380520@qq.com> Date: Thu, 12 Oct 2023 22:09:49 +0800 Subject: +hazel-networking --- Tools/Hazel-Networking/Hazel.UnitTests/Utils.cs | 99 +++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 Tools/Hazel-Networking/Hazel.UnitTests/Utils.cs (limited to 'Tools/Hazel-Networking/Hazel.UnitTests/Utils.cs') diff --git a/Tools/Hazel-Networking/Hazel.UnitTests/Utils.cs b/Tools/Hazel-Networking/Hazel.UnitTests/Utils.cs new file mode 100644 index 0000000..df62b80 --- /dev/null +++ b/Tools/Hazel-Networking/Hazel.UnitTests/Utils.cs @@ -0,0 +1,99 @@ +using Org.BouncyCastle.Crypto; +using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.OpenSsl; +using Org.BouncyCastle.Security; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.IO; +using System.Security.Cryptography; + +namespace Hazel.UnitTests +{ + static class Utils + { + /// + /// Hex encode a byte array (lower case) + /// + public static string BytesToHex(byte[] data) + { + string chars = "0123456789abcdef"; + + StringBuilder sb = new StringBuilder(data.Length * 2); + for (int ii = 0, nn = data.Length; ii != nn; ++ii) + { + sb.Append(chars[data[ii] >> 4]); + sb.Append(chars[data[ii] & 0xF]); + } + + return sb.ToString().ToLower(); + } + + /// + /// Decode a hex string to a byte array (lowercase) + /// + public static byte[] HexToBytes(string hex) + { + hex = hex.ToLower(); + hex = hex = string.Concat(hex.Where(c => !char.IsWhiteSpace(c))); + + byte[] output = new byte[hex.Length / 2]; + + for (int ii = 0; ii != hex.Length; ++ii) + { + byte nibble; + + char c = hex[ii]; + if (c >= 'a') + { + nibble = (byte)(0x0A + c - 'a'); + } + else + { + nibble = (byte)(c - '0'); + } + + if ((ii & 1) == 0) + { + output[ii / 2] = (byte)(nibble << 4); + } + else + { + output[ii / 2] |= nibble; + } + } + + return output; + } + + public static byte[] DecodePEM(string pemData) + { + List result = new List(); + + pemData = pemData.Replace("\r", ""); + string[] lines = pemData.Split('\n'); + foreach (string line in lines) + { + if (line.StartsWith("-----")) + { + continue; + } + + byte[] lineData = Convert.FromBase64String(line); + result.AddRange(lineData); + } + + return result.ToArray(); + } + + public static RSA DecodeRSAKeyFromPEM(string pemData) + { + var pemReader = new PemReader(new StringReader(pemData)); + var parameters = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)pemReader.ReadObject()); + var rsa = RSA.Create(); + rsa.ImportParameters(parameters); + return rsa; + } + } +} -- cgit v1.1-26-g67d0