summary refs log tree commit diff
path: root/crypto/src/asn1/pkcs/PrivateKeyInfo.cs
blob: 9535dbcaeba986c96d1122535ca65c721cbfc71a (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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
using System;

using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Utilities.Collections;

namespace Org.BouncyCastle.Asn1.Pkcs
{
    /**
     *  RFC 5958
     *
     *  <pre>
     *  [IMPLICIT TAGS]
     *
     *  OneAsymmetricKey ::= SEQUENCE {
     *      version                   Version,
     *      privateKeyAlgorithm       PrivateKeyAlgorithmIdentifier,
     *      privateKey                PrivateKey,
     *      attributes            [0] Attributes OPTIONAL,
     *      ...,
     *      [[2: publicKey        [1] PublicKey OPTIONAL ]],
     *      ...
     *  }
     *
     *  PrivateKeyInfo ::= OneAsymmetricKey
     *
     *  Version ::= INTEGER { v1(0), v2(1) } (v1, ..., v2)
     *
     *  PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
     *                                     { PUBLIC-KEY,
     *                                       { PrivateKeyAlgorithms } }
     *
     *  PrivateKey ::= OCTET STRING
     *                     -- Content varies based on type of key.  The
     *                     -- algorithm identifier dictates the format of
     *                     -- the key.
     *
     *  PublicKey ::= BIT STRING
     *                     -- Content varies based on type of key.  The
     *                     -- algorithm identifier dictates the format of
     *                     -- the key.
     *
     *  Attributes ::= SET OF Attribute { { OneAsymmetricKeyAttributes } }
     *  </pre>
     */
    public class PrivateKeyInfo
        : Asn1Encodable
    {
        private readonly DerInteger version;
        private readonly AlgorithmIdentifier privateKeyAlgorithm;
        private readonly Asn1OctetString privateKey;
        private readonly Asn1Set attributes;
        private readonly DerBitString publicKey;

        public static PrivateKeyInfo GetInstance(Asn1TaggedObject obj, bool explicitly)
        {
            return GetInstance(Asn1Sequence.GetInstance(obj, explicitly));
        }

        public static PrivateKeyInfo GetInstance(
            object obj)
        {
            if (obj == null)
                return null;
            if (obj is PrivateKeyInfo)
                return (PrivateKeyInfo)obj;
            return new PrivateKeyInfo(Asn1Sequence.GetInstance(obj));
        }

        private static int GetVersionValue(DerInteger version)
        {
            BigInteger bigValue = version.Value;
            if (bigValue.CompareTo(BigInteger.Zero) < 0 || bigValue.CompareTo(BigInteger.One) > 0)
                throw new ArgumentException("invalid version for private key info", "version");

            return bigValue.IntValue;
        }

        public PrivateKeyInfo(
            AlgorithmIdentifier privateKeyAlgorithm,
            Asn1Encodable privateKey)
            : this(privateKeyAlgorithm, privateKey, null, null)
        {
        }

        public PrivateKeyInfo(
            AlgorithmIdentifier privateKeyAlgorithm,
            Asn1Encodable privateKey,
            Asn1Set attributes)
            : this(privateKeyAlgorithm, privateKey, attributes, null)
        {
        }

        public PrivateKeyInfo(
            AlgorithmIdentifier privateKeyAlgorithm,
            Asn1Encodable privateKey,
            Asn1Set attributes,
            byte[] publicKey)
        {
            this.version = new DerInteger(publicKey != null ? BigInteger.One : BigInteger.Zero);
            this.privateKeyAlgorithm = privateKeyAlgorithm;
            this.privateKey = new DerOctetString(privateKey);
            this.attributes = attributes;
            this.publicKey = publicKey == null ? null : new DerBitString(publicKey);
        }

        private PrivateKeyInfo(Asn1Sequence seq)
        {
            var e = seq.GetEnumerator();

            this.version = DerInteger.GetInstance(CollectionUtilities.RequireNext(e));

            int versionValue = GetVersionValue(version);

            this.privateKeyAlgorithm = AlgorithmIdentifier.GetInstance(CollectionUtilities.RequireNext(e));
            this.privateKey = Asn1OctetString.GetInstance(CollectionUtilities.RequireNext(e));

            int lastTag = -1;
            while (e.MoveNext())
            {
                Asn1TaggedObject tagged = (Asn1TaggedObject)e.Current;

                int tag = tagged.TagNo;
                if (tag <= lastTag)
                    throw new ArgumentException("invalid optional field in private key info", "seq");

                lastTag = tag;

                switch (tag)
                {
                case 0:
                {
                    this.attributes = Asn1Set.GetInstance(tagged, false);
                    break;
                }
                case 1:
                {
                    if (versionValue < 1)
                        throw new ArgumentException("'publicKey' requires version v2(1) or later", "seq");

                    this.publicKey = DerBitString.GetInstance(tagged, false);
                    break;
                }
                default:
                {
                    throw new ArgumentException("unknown optional field in private key info", "seq");
                }
                }
            }
        }

        public virtual DerInteger Version
        {
            get { return version; }
        }

        public virtual Asn1Set Attributes
        {
            get { return attributes; }
        }

        /// <summary>Return true if a public key is present, false otherwise.</summary>
        public virtual bool HasPublicKey
        {
            get { return publicKey != null; }
        }

        public virtual AlgorithmIdentifier PrivateKeyAlgorithm
        {
            get { return privateKeyAlgorithm; }
        }

        public virtual Asn1OctetString PrivateKey => privateKey;

        [Obsolete("Use 'PrivateKey' instead")]
        public virtual Asn1OctetString PrivateKeyData
        {
            get { return privateKey; }
        }

        public virtual int PrivateKeyLength => privateKey.GetOctetsLength();

        public virtual Asn1Object ParsePrivateKey()
        {
            return Asn1Object.FromByteArray(privateKey.GetOctets());
        }

        /// <summary>For when the public key is an ASN.1 encoding.</summary>
        public virtual Asn1Object ParsePublicKey()
        {
            return publicKey == null ? null : Asn1Object.FromByteArray(publicKey.GetOctets());
        }

        public virtual DerBitString PublicKey => publicKey;

        /// <summary>Return the public key as a raw bit string.</summary>
        [Obsolete("Use 'PublicKey' instead")]
        public virtual DerBitString PublicKeyData
        {
            get { return publicKey; }
        }

        public override Asn1Object ToAsn1Object()
        {
            Asn1EncodableVector v = new Asn1EncodableVector(version, privateKeyAlgorithm, privateKey);
            v.AddOptionalTagged(false, 0, attributes);
            v.AddOptionalTagged(false, 1, publicKey);
            return new DerSequence(v);
        }
    }
}