using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using IcgSoftware.Threema.CoreMsgApi.Exceptions; namespace IcgSoftware.Threema.CoreMsgApi { /// /// Encapsulates an asymmetric key, either public or private. /// public class Key { public static readonly char separator = ':'; public static class KeyType { public const string PRIVATE = "private"; public const string PUBLIC = "public"; } public byte[] key; public string type; public Key(string type, byte[] key) { this.key = key; this.type = type; } /// /// Decodes and validates an encoded key. /// Encoded key format: type:hex_key /// /// an encoded key /// public static Key DecodeKey(string encodedKey) { // Split key and check length string[] keyArray = encodedKey.Split(Key.separator); if (keyArray.Length != 2) { throw new InvalidKeyException("Does not contain a valid key format"); } // Unpack key string keyType = keyArray[0]; string keyContent = keyArray[1]; // Is this a valid hex key? if (!Regex.IsMatch(keyContent, "[0-9a-fA-F]{64}")) { throw new InvalidKeyException("Does not contain a valid key"); } return new Key(keyType, DataUtils.HexStringToByteArray(keyContent)); } /// /// Decodes and validates an encoded key. /// Encoded key format: type:hex_key /// /// an encoded key /// the expected type of the key /// public static Key DecodeKey(String encodedKey, String expectedKeyType) { Key key = DecodeKey(encodedKey); // Check key type if (!key.type.Equals(expectedKeyType)) { throw new InvalidKeyException("Expected key type: " + expectedKeyType + ", got: " + key.type); } return key; } /// /// Encodes a key. /// /// an encoded key public String Encode() { return this.type + Key.separator + DataUtils.ByteArrayToHexString(this.key); } } }