diff options
Diffstat (limited to 'crypto/src/util')
-rw-r--r-- | crypto/src/util/encoders/Hex.cs | 24 | ||||
-rw-r--r-- | crypto/src/util/encoders/HexEncoder.cs | 26 |
2 files changed, 49 insertions, 1 deletions
diff --git a/crypto/src/util/encoders/Hex.cs b/crypto/src/util/encoders/Hex.cs index 3540a9d1e..dc4871352 100644 --- a/crypto/src/util/encoders/Hex.cs +++ b/crypto/src/util/encoders/Hex.cs @@ -9,7 +9,7 @@ namespace Org.BouncyCastle.Utilities.Encoders /// </summary> public sealed class Hex { - private static readonly IEncoder encoder = new HexEncoder(); + private static readonly HexEncoder encoder = new HexEncoder(); private Hex() { @@ -126,5 +126,27 @@ namespace Org.BouncyCastle.Utilities.Encoders { return encoder.DecodeString(data, outStream); } + + /** + * Decode the hexadecimal-encoded string strictly i.e. any non-hexadecimal characters will be + * considered an error. + * + * @return a byte array representing the decoded data. + */ + public static byte[] DecodeStrict(string str) + { + return encoder.DecodeStrict(str, 0, str.Length); + } + + /** + * Decode the hexadecimal-encoded string strictly i.e. any non-hexadecimal characters will be + * considered an error. + * + * @return a byte array representing the decoded data. + */ + public static byte[] DecodeStrict(string str, int off, int len) + { + return encoder.DecodeStrict(str, off, len); + } } } diff --git a/crypto/src/util/encoders/HexEncoder.cs b/crypto/src/util/encoders/HexEncoder.cs index af526e0da..950bc8477 100644 --- a/crypto/src/util/encoders/HexEncoder.cs +++ b/crypto/src/util/encoders/HexEncoder.cs @@ -172,5 +172,31 @@ namespace Org.BouncyCastle.Utilities.Encoders return length; } + + internal byte[] DecodeStrict(string str, int off, int len) + { + if (null == str) + throw new ArgumentNullException("str"); + if (off < 0 || len < 0 || off > (str.Length - len)) + throw new IndexOutOfRangeException("invalid offset and/or length specified"); + if (0 != (len & 1)) + throw new ArgumentException("a hexadecimal encoding must have an even number of characters", "len"); + + int resultLen = len >> 1; + byte[] result = new byte[resultLen]; + + int strPos = off; + for (int i = 0; i < resultLen; ++i) + { + byte b1 = decodingTable[str[strPos++]]; + byte b2 = decodingTable[str[strPos++]]; + + if ((b1 | b2) >= 0x80) + throw new IOException("invalid characters encountered in Hex data"); + + result[i] = (byte)((b1 << 4) | b2); + } + return result; + } } } |