private byte[] DecodePk11String(string attributeName, string pk11String, char[] allowedChars, bool decodePctEncodedChars)
{
if (string.IsNullOrEmpty(pk11String))
return null;
using (MemoryStream memoryStream = new MemoryStream())
{
int i = 0;
while (i < pk11String.Length)
{
if (decodePctEncodedChars)
{
if (pk11String[i] == '%')
{
if ((i + 2) > pk11String.Length)
{
if (attributeName != null)
throw new Pkcs11UriException("Value of " + attributeName + " attribute contains invalid application of percent-encoding");
else
throw new Pkcs11UriException("URI contains invalid application of percent-encoding");
}
if (!IsHexDigit(pk11String[i + 1]) || !IsHexDigit(pk11String[i + 2]))
{
if (attributeName != null)
throw new Pkcs11UriException("Value of " + attributeName + " attribute contains invalid application of percent-encoding");
else
throw new Pkcs11UriException("URI contains invalid application of percent-encoding");
}
memoryStream.WriteByte(Convert.ToByte(pk11String.Substring(i + 1, 2), 16));
i = i + 3;
continue;
}
}
bool allowedChar = false;
for (int j = 0; j < allowedChars.Length; j++)
{
if (pk11String[i] == allowedChars[j])
{
allowedChar = true;
break;
}
}
if (allowedChar)
{
memoryStream.WriteByte(Convert.ToByte(pk11String[i]));
i++;
continue;
}
if (attributeName != null)
throw new Pkcs11UriException("Value of " + attributeName + " attribute contains invalid character");
else
throw new Pkcs11UriException("URI contains invalid character");
}
return memoryStream.ToArray();
}
}