示例#1
0
        public static string EncodeCheck(VersionByte versionByte, byte[] data)
        {
            var bytes = new List <byte>
            {
                (byte)versionByte
            };

            bytes.AddRange(data);
            var checksum = CalculateChecksum(bytes.ToArray());

            bytes.AddRange(checksum);
            return(Base32Encoding.ToString(bytes.ToArray(), options => options.OmitPadding = true));
        }
示例#2
0
        private static byte[] CheckedBase32Decode(string encoded)
        {
            if (encoded.Length == 0)
            {
                throw new ArgumentException("Encoded string is empty");
            }

            foreach (var t in encoded)
            {
                if (t > 127)
                {
                    throw new ArgumentException("Illegal characters in encoded string.");
                }
            }

            return(Base32Encoding.ToBytes(encoded));
        }
示例#3
0
        public static byte[] DecodeCheck(VersionByte versionByte, string encoded)
        {
            for (var i = 0; i < encoded.Length; i++)
            {
                if (encoded[i] > 127)
                {
                    throw new ArgumentException("Illegal characters in encoded char array.");
                }
            }

            var decoded            = Base32Encoding.ToBytes(encoded);
            var decodedVersionByte = decoded[0];

            var payload = new byte[decoded.Length - 2];

            Array.Copy(decoded, 0, payload, 0, payload.Length);

            var data = new byte[payload.Length - 1];

            Array.Copy(payload, 1, data, 0, data.Length);

            var checksum = new byte[2];

            Array.Copy(decoded, decoded.Length - 2, checksum, 0, checksum.Length);

            if (decodedVersionByte != (byte)versionByte)
            {
                throw new FormatException("Version byte is invalid");
            }

            var expectedChecksum = CalculateChecksum(payload);

            if (!expectedChecksum.SequenceEqual(checksum))
            {
                throw new FormatException("Checksum invalid");
            }

            return(data);
        }