summary refs log tree commit diff
path: root/crypto/src/asn1/x509/X509NameTokenizer.cs
blob: 7821f423a37c68aef2e25d76b563aebd07900c28 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
using System;

namespace Org.BouncyCastle.Asn1.X509
{
    /**
     * class for breaking up an X500 Name into it's component tokens, ala
     * java.util.StringTokenizer. We need this class as some of the
     * lightweight Java environment don't support classes like
     * StringTokenizer.
     */
    public class X509NameTokenizer
    {
        private readonly string m_value;
        private readonly char m_separator;

        private int m_index;

        public X509NameTokenizer(string oid)
            : this(oid, ',')
        {
        }

		public X509NameTokenizer(string	oid, char separator)
        {
            if (oid == null)
                throw new ArgumentNullException(nameof(oid));

            if (separator == '"' || separator == '\\')
                throw new ArgumentException("reserved separator character", nameof(separator));

            m_value = oid;
            m_separator = separator;
            m_index = oid.Length < 1 ? 0 : -1;
        }

        public bool HasMoreTokens() => m_index < m_value.Length;

		public string NextToken()
        {
            if (m_index >= m_value.Length)
                return null;

            bool quoted = false;
            bool escaped = false;

            int beginIndex = m_index + 1;
            while (++m_index < m_value.Length)
            {
                char c = m_value[m_index];

                if (escaped)
                {
                    escaped = false;
                }
                else if (c == '"')
                {
                    quoted = !quoted;
                }
                else if (quoted)
                {
                }
                else if (c == '\\')
                {
                    escaped = true;
                }
                else if (c == m_separator)
                {
                    // TODO[api] The Trim() is for backward compatibility; remove on transition to X500NameTokenizer
                    return m_value.Substring(beginIndex, m_index - beginIndex).Trim();
                }
            }

            if (escaped || quoted)
                throw new ArgumentException("badly formatted directory string");

            // TODO[api] The Trim() is for backward compatibility; remove on transition to X500NameTokenizer
            return m_value.Substring(beginIndex, m_index - beginIndex).Trim();
        }
    }
}