|
| 1 | +// Copyright 2024 Yubico AB |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"). |
| 4 | +// You may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +using System; |
| 16 | +using System.IO; |
| 17 | +using System.Linq; |
| 18 | + |
| 19 | +namespace Yubico.Core.Tlv |
| 20 | +{ |
| 21 | + /// <summary> |
| 22 | + /// Tag, length, Value structure that helps to parse APDU response data. |
| 23 | + /// This class handles BER-TLV encoded data with determinate length. |
| 24 | + /// </summary> |
| 25 | + public class TlvObject |
| 26 | + { |
| 27 | + /// <summary> |
| 28 | + /// Returns the tag. |
| 29 | + /// </summary> |
| 30 | + public int Tag { get; } |
| 31 | + |
| 32 | + /// <summary> |
| 33 | + /// Returns the value. |
| 34 | + /// </summary> |
| 35 | + public Memory<byte> Value => _bytes.Skip(_offset).Take(Length).ToArray(); |
| 36 | + |
| 37 | + /// <summary> |
| 38 | + /// Returns the length of the value. |
| 39 | + /// </summary> |
| 40 | + public int Length { get; } |
| 41 | + |
| 42 | + private readonly byte[] _bytes; |
| 43 | + private readonly int _offset; |
| 44 | + |
| 45 | + /// <summary> |
| 46 | + /// Creates a new TLV (Tag-Length-Value) object with the specified tag and value. |
| 47 | + /// </summary> |
| 48 | + /// <param name="tag">The tag value, must be between 0x00 and 0xFFFF.</param> |
| 49 | + /// <param name="value">The value data as a read-only span of bytes.</param> |
| 50 | + /// <exception cref="TlvException">Thrown when the tag value is outside the supported range (0x00-0xFFFF).</exception> |
| 51 | + /// <remarks> |
| 52 | + /// This constructor creates a BER-TLV encoded structure where: |
| 53 | + /// - The tag is encoded in the minimum number of bytes needed |
| 54 | + /// - The length is encoded according to BER-TLV rules |
| 55 | + /// - The value is stored as provided |
| 56 | + /// </remarks> |
| 57 | + public TlvObject(int tag, ReadOnlySpan<byte> value) |
| 58 | + { |
| 59 | + // Validate that the tag is within the supported range (0x00-0xFFFF) |
| 60 | + if (tag < 0 || tag > 0xFFFF) |
| 61 | + { |
| 62 | + throw new TlvException(ExceptionMessages.TlvUnsupportedTag); |
| 63 | + } |
| 64 | + |
| 65 | + Tag = tag; |
| 66 | + // Create a copy of the input value |
| 67 | + byte[] valueBuffer = value.ToArray(); |
| 68 | + using var ms = new MemoryStream(); |
| 69 | + |
| 70 | + // Convert tag to bytes and remove leading zeros, maintaining BER-TLV format |
| 71 | + byte[] tagBytes = BitConverter.GetBytes(tag).Reverse().SkipWhile(b => b == 0).ToArray(); |
| 72 | + ms.Write(tagBytes, 0, tagBytes.Length); |
| 73 | + |
| 74 | + Length = valueBuffer.Length; |
| 75 | + // For lengths < 128 (0x80), use single byte encoding |
| 76 | + if (Length < 0x80) |
| 77 | + { |
| 78 | + ms.WriteByte((byte)Length); |
| 79 | + } |
| 80 | + // For lengths >= 128, use multi-byte encoding with length indicator |
| 81 | + else |
| 82 | + { |
| 83 | + // Convert length to bytes and remove leading zeros |
| 84 | + byte[] lnBytes = BitConverter.GetBytes(Length).Reverse().SkipWhile(b => b == 0).ToArray(); |
| 85 | + // Write number of length bytes with high bit set (0x80 | number of bytes) |
| 86 | + ms.WriteByte((byte)(0x80 | lnBytes.Length)); |
| 87 | + // Write the actual length bytes |
| 88 | + ms.Write(lnBytes, 0, lnBytes.Length); |
| 89 | + } |
| 90 | + |
| 91 | + // Store the position where the value begins |
| 92 | + _offset = (int)ms.Position; |
| 93 | + |
| 94 | + // Write the value bytes |
| 95 | + ms.Write(valueBuffer, 0, Length); |
| 96 | + |
| 97 | + // Store the complete TLV encoding |
| 98 | + _bytes = ms.ToArray(); |
| 99 | + } |
| 100 | + |
| 101 | + /// <summary> |
| 102 | + /// Returns a copy of the Tlv as a BER-TLV encoded byte array. |
| 103 | + /// </summary> |
| 104 | + public Memory<byte> GetBytes() => _bytes.ToArray(); |
| 105 | + |
| 106 | + /// <summary> |
| 107 | + /// Parse a Tlv from a BER-TLV encoded byte array. |
| 108 | + /// </summary> |
| 109 | + /// <param name="data">A byte array containing the TLV encoded data (and nothing more).</param> |
| 110 | + /// <returns>The parsed Tlv</returns> |
| 111 | + public static TlvObject Parse(ReadOnlySpan<byte> data) |
| 112 | + { |
| 113 | + ReadOnlySpan<byte> buffer = data; |
| 114 | + return ParseFrom(ref buffer); |
| 115 | + } |
| 116 | + |
| 117 | + /// <summary> |
| 118 | + /// Parses a TLV from a BER-TLV encoded byte array. |
| 119 | + /// </summary> |
| 120 | + /// <param name="buffer">A byte array containing the TLV encoded data.</param> |
| 121 | + /// <returns>The parsed <see cref="TlvObject"/></returns> |
| 122 | + /// <remarks> |
| 123 | + /// This method will parse a TLV from the given buffer and return the parsed Tlv. |
| 124 | + /// The method will consume the buffer as much as necessary to parse the TLV. |
| 125 | + /// </remarks> |
| 126 | + /// <exception cref="ArgumentException">Thrown if the buffer does not contain a valid TLV.</exception> |
| 127 | + internal static TlvObject ParseFrom(ref ReadOnlySpan<byte> buffer) |
| 128 | + { |
| 129 | + // The first byte of the TLV is the tag. |
| 130 | + int tag = buffer[0]; |
| 131 | + |
| 132 | + // Determine if the tag is in long form. |
| 133 | + // Long form tags have more than one byte, starting with 0x1F. |
| 134 | + if ((buffer[0] & 0x1F) == 0x1F) |
| 135 | + { |
| 136 | + // Ensure there is enough data for a long form tag. |
| 137 | + if (buffer.Length < 2) |
| 138 | + { |
| 139 | + throw new ArgumentException("Insufficient data for long form tag"); |
| 140 | + } |
| 141 | + // Combine the first two bytes to form the tag. |
| 142 | + tag = (buffer[0] << 8) | buffer[1]; |
| 143 | + buffer = buffer[2..]; // Skip the tag bytes |
| 144 | + } |
| 145 | + else |
| 146 | + { |
| 147 | + buffer = buffer[1..]; // Skip the tag byte |
| 148 | + } |
| 149 | + |
| 150 | + if (buffer.Length < 1) |
| 151 | + { |
| 152 | + throw new ArgumentException("Insufficient data for length"); |
| 153 | + } |
| 154 | + |
| 155 | + // Read the length of the TLV value. |
| 156 | + int length = buffer[0]; |
| 157 | + buffer = buffer[1..]; |
| 158 | + |
| 159 | + // If the length is more than one byte, process remaining bytes. |
| 160 | + if (length > 0x80) |
| 161 | + { |
| 162 | + int lengthLn = length - 0x80; |
| 163 | + length = 0; |
| 164 | + for (int i = 0; i < lengthLn; i++) |
| 165 | + { |
| 166 | + length = (length << 8) | buffer[0]; |
| 167 | + buffer = buffer[1..]; |
| 168 | + } |
| 169 | + } |
| 170 | + |
| 171 | + ReadOnlySpan<byte> value = buffer[..length]; |
| 172 | + buffer = buffer[length..]; // Advance the buffer to the end of the value |
| 173 | + |
| 174 | + return new TlvObject(tag, value); |
| 175 | + } |
| 176 | + |
| 177 | + /// <summary> |
| 178 | + /// Returns a string that represents the current object. |
| 179 | + /// </summary> |
| 180 | + /// <returns>A string that represents the current object.</returns> |
| 181 | + /// <remarks> |
| 182 | + /// The string is of the form <c>Tlv(0xTAG, LENGTH, VALUE)</c>. |
| 183 | + /// <para> |
| 184 | + /// The tag is written out in hexadecimal, prefixed by 0x. |
| 185 | + /// The length is written out in decimal. |
| 186 | + /// The value is written out in hexadecimal. |
| 187 | + /// </para> |
| 188 | + /// </remarks> |
| 189 | + public override string ToString() |
| 190 | + { |
| 191 | +#if NETSTANDARD2_1_OR_GREATER |
| 192 | + return $"Tlv(0x{Tag:X}, {Length}, {BitConverter.ToString(Value.ToArray()).Replace("-", "", StringComparison.Ordinal)})"; |
| 193 | +#else |
| 194 | + return $"Tlv(0x{Tag:X}, {Length}, {BitConverter.ToString(Value.ToArray()).Replace("-", "")})"; |
| 195 | +#endif |
| 196 | + } |
| 197 | + } |
| 198 | +} |
0 commit comments