Merge pull request #649 from DavidS/feature/implement-additional-reference-path
[mono.git] / mcs / class / System / System.Security.Cryptography.X509Certificates / X509SubjectKeyIdentifierExtension.cs
1 //
2 // System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension
3 //
4 // Authors:
5 //      Tim Coleman (tim@timcoleman.com)
6 //      Sebastien Pouliot  <sebastien@ximian.com>
7 //
8 // Copyright (C) Tim Coleman, 2004
9 // Copyright (C) 2004-2005 Novell Inc. (http://www.novell.com)
10 //
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 //
30
31 #if SECURITY_DEP
32
33 #if MONOTOUCH
34 using Mono.Security;
35 using Mono.Security.Cryptography;
36 #else
37 extern alias MonoSecurity;
38 using MonoSecurity::Mono.Security;
39 using MonoSecurity::Mono.Security.Cryptography;
40 #endif
41
42 using System.Text;
43
44 namespace System.Security.Cryptography.X509Certificates {
45
46         public sealed class X509SubjectKeyIdentifierExtension : X509Extension {
47
48                 internal const string oid = "2.5.29.14";
49                 internal const string friendlyName = "Subject Key Identifier";
50
51                 private byte[] _subjectKeyIdentifier;
52                 private string _ski;
53                 private AsnDecodeStatus _status;
54
55                 // constructors
56
57                 public X509SubjectKeyIdentifierExtension ()
58                 {
59                         _oid = new Oid (oid, friendlyName);
60                 }
61
62                 public X509SubjectKeyIdentifierExtension (AsnEncodedData encodedSubjectKeyIdentifier, bool critical)
63                 {
64                         // ignore the Oid provided by encodedKeyUsage (our rules!)
65                         _oid = new Oid (oid, friendlyName);
66                         _raw = encodedSubjectKeyIdentifier.RawData;
67                         base.Critical = critical;
68                         _status = Decode (this.RawData);
69                 }
70
71                 public X509SubjectKeyIdentifierExtension (byte[] subjectKeyIdentifier, bool critical)
72                 {
73                         if (subjectKeyIdentifier == null)
74                                 throw new ArgumentNullException ("subjectKeyIdentifier");
75                         if (subjectKeyIdentifier.Length == 0)
76                                 throw new ArgumentException ("subjectKeyIdentifier");
77
78                         _oid = new Oid (oid, friendlyName);
79                         base.Critical = critical;
80                         _subjectKeyIdentifier = (byte[])subjectKeyIdentifier.Clone ();
81                         RawData = Encode ();
82                 }
83
84                 public X509SubjectKeyIdentifierExtension (string subjectKeyIdentifier, bool critical)
85                 {
86                         if (subjectKeyIdentifier == null)
87                                 throw new ArgumentNullException ("subjectKeyIdentifier");
88                         if (subjectKeyIdentifier.Length < 2)
89                                 throw new ArgumentException ("subjectKeyIdentifier");
90
91                         _oid = new Oid (oid, friendlyName);
92                         base.Critical = critical;
93                         _subjectKeyIdentifier = FromHex (subjectKeyIdentifier);
94                         RawData = Encode ();
95                 }
96
97                 public X509SubjectKeyIdentifierExtension (PublicKey key, bool critical)
98                         : this (key, X509SubjectKeyIdentifierHashAlgorithm.Sha1, critical)
99                 {
100                 }
101
102                 public X509SubjectKeyIdentifierExtension (PublicKey key, X509SubjectKeyIdentifierHashAlgorithm algorithm, bool critical)
103                 {
104                         if (key == null)
105                                 throw new ArgumentNullException ("key");
106
107                         byte[] pkraw = key.EncodedKeyValue.RawData;
108                         // compute SKI
109                         switch (algorithm) {
110                         // hash of the public key, excluding Tag, Length and unused bits values
111                         case X509SubjectKeyIdentifierHashAlgorithm.Sha1:
112                                 _subjectKeyIdentifier = SHA1.Create ().ComputeHash (pkraw);
113                                 break;
114                         // 0100 bit pattern followed by the 60 last bit of the hash
115                         case X509SubjectKeyIdentifierHashAlgorithm.ShortSha1:
116                                 byte[] hash = SHA1.Create ().ComputeHash (pkraw);
117                                 _subjectKeyIdentifier = new byte [8];
118                                 Buffer.BlockCopy (hash, 12, _subjectKeyIdentifier, 0, 8);
119                                 _subjectKeyIdentifier [0] = (byte) (0x40 | (_subjectKeyIdentifier [0] & 0x0F));
120                                 break;
121                         // hash of the public key, including Tag, Length and unused bits values
122                         case X509SubjectKeyIdentifierHashAlgorithm.CapiSha1:
123                                 // CryptoAPI does that hash on the complete subjectPublicKeyInfo (unlike PKIX)
124                                 // http://groups.google.ca/groups?selm=e7RqM%24plCHA.1488%40tkmsftngp02&oe=UTF-8&output=gplain
125                                 ASN1 subjectPublicKeyInfo = new ASN1 (0x30);
126                                 ASN1 algo = subjectPublicKeyInfo.Add (new ASN1 (0x30));
127                                 algo.Add (new ASN1 (CryptoConfig.EncodeOID (key.Oid.Value)));
128                                 algo.Add (new ASN1 (key.EncodedParameters.RawData)); 
129                                 // add an extra byte for the unused bits (none)
130                                 byte[] full = new byte [pkraw.Length + 1];
131                                 Buffer.BlockCopy (pkraw, 0, full, 1, pkraw.Length);
132                                 subjectPublicKeyInfo.Add (new ASN1 (0x03, full));
133                                 _subjectKeyIdentifier = SHA1.Create ().ComputeHash (subjectPublicKeyInfo.GetBytes ());
134                                 break;
135                         default:
136                                 throw new ArgumentException ("algorithm");
137                         }
138
139                         _oid = new Oid (oid, friendlyName);
140                         base.Critical = critical;
141                         RawData = Encode ();
142                 }
143
144                 // properties
145
146                 public string SubjectKeyIdentifier {
147                         get {
148                                 switch (_status) {
149                                 case AsnDecodeStatus.Ok:
150                                 case AsnDecodeStatus.InformationNotAvailable:
151                                         if (_subjectKeyIdentifier != null)
152                                                 _ski = CryptoConvert.ToHex (_subjectKeyIdentifier);
153                                         return _ski;
154                                 default:
155                                         throw new CryptographicException ("Badly encoded extension.");
156                                 }
157                         }
158                 }
159
160                 // methods
161
162                 public override void CopyFrom (AsnEncodedData encodedData)
163                 {
164                         if (encodedData == null)
165                                 throw new ArgumentNullException ("encodedData");
166
167                         X509Extension ex = (encodedData as X509Extension);
168                         if (ex == null)
169                                 throw new ArgumentException (Locale.GetText ("Wrong type."), "encodedData");
170
171                         if (ex._oid == null)
172                                 _oid = new Oid (oid, friendlyName);
173                         else 
174                                 _oid = new Oid (ex._oid);
175
176                         RawData = ex.RawData;
177                         base.Critical = ex.Critical;
178                         // and we deal with the rest later
179                         _status = Decode (this.RawData);
180                 }
181
182                 // internal
183
184                 static internal byte FromHexChar (char c) 
185                 {
186                         if ((c >= 'a') && (c <= 'f'))
187                                 return (byte) (c - 'a' + 10);
188                         if ((c >= 'A') && (c <= 'F'))
189                                 return (byte) (c - 'A' + 10);
190                         if ((c >= '0') && (c <= '9'))
191                                 return (byte) (c - '0');
192                         return 255;     // F
193                 }
194
195                 static internal byte FromHexChars (char c1, char c2)
196                 {
197                         byte result = FromHexChar (c1);
198                         if (result < 255)
199                                 result = (byte) ((result << 4) | FromHexChar (c2));
200                         return result;
201                 }
202
203                 static internal byte[] FromHex (string hex)
204                 {
205                         // here we can't use CryptoConvert.FromHex because we
206                         // must convert any *illegal* (non hex) 2 characters 
207                         // to 'FF' and ignore last char on odd length
208                         if (hex == null)
209                                 return null;
210
211                         int length = hex.Length >> 1;
212
213                         byte[] result = new byte [length]; // + (odd ? 1 : 0)];
214                         int n = 0;
215                         int i = 0;
216                         while (n < length) {
217                                 result [n++] = FromHexChars (hex [i++], hex [i++]);
218                         }
219                         return result;
220                 }
221
222                 internal AsnDecodeStatus Decode (byte[] extension)
223                 {
224                         if ((extension == null) || (extension.Length == 0))
225                                 return AsnDecodeStatus.BadAsn;
226                         _ski = String.Empty;
227                         if (extension [0] != 0x04)
228                                 return AsnDecodeStatus.BadTag;
229                         if (extension.Length == 2)
230                                 return AsnDecodeStatus.InformationNotAvailable;
231                         if (extension.Length < 3)
232                                 return AsnDecodeStatus.BadLength;
233
234                         try {
235                                 ASN1 ex = new ASN1 (extension);
236                                 _subjectKeyIdentifier = ex.Value;
237                         }
238                         catch {
239                                 return AsnDecodeStatus.BadAsn;
240                         }
241
242                         return AsnDecodeStatus.Ok;
243                 }
244
245                 internal byte[] Encode ()
246                 {
247                         ASN1 ex = new ASN1 (0x04, _subjectKeyIdentifier);
248                         return ex.GetBytes ();
249                 }
250
251                 internal override string ToString (bool multiLine)
252                 {
253                         switch (_status) {
254                         case AsnDecodeStatus.BadAsn:
255                                 return String.Empty;
256                         case AsnDecodeStatus.BadTag:
257                         case AsnDecodeStatus.BadLength:
258                                 return FormatUnkownData (_raw);
259                         case AsnDecodeStatus.InformationNotAvailable:
260                                 return "Information Not Available";
261                         }
262
263                         if (_oid.Value != oid)
264                                 return String.Format ("Unknown Key Usage ({0})", _oid.Value);
265
266                         StringBuilder sb = new StringBuilder ();
267
268                         for (int i=0; i < _subjectKeyIdentifier.Length; i++) {
269                                 sb.Append (_subjectKeyIdentifier [i].ToString ("x2"));
270                                 if (i != _subjectKeyIdentifier.Length - 1)
271                                         sb.Append (" ");
272                         }
273
274                         if (multiLine)
275                                 sb.Append (Environment.NewLine);
276
277                         return sb.ToString ();
278                 }
279         }
280 }
281
282 #endif