Renamed target AssignProjectConfigurations to AssignProjectConfiguration (without...
[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 extern alias MonoSecurity;
34
35 using System.Text;
36
37 using MonoSecurity::Mono.Security;
38 using MonoSecurity::Mono.Security.Cryptography;
39
40 namespace System.Security.Cryptography.X509Certificates {
41
42         public sealed class X509SubjectKeyIdentifierExtension : X509Extension {
43
44                 internal const string oid = "2.5.29.14";
45                 internal const string friendlyName = "Subject Key Identifier";
46
47                 private byte[] _subjectKeyIdentifier;
48                 private string _ski;
49                 private AsnDecodeStatus _status;
50
51                 // constructors
52
53                 public X509SubjectKeyIdentifierExtension ()
54                 {
55                         _oid = new Oid (oid, friendlyName);
56                 }
57
58                 public X509SubjectKeyIdentifierExtension (AsnEncodedData encodedSubjectKeyIdentifier, bool critical)
59                 {
60                         // ignore the Oid provided by encodedKeyUsage (our rules!)
61                         _oid = new Oid (oid, friendlyName);
62                         _raw = encodedSubjectKeyIdentifier.RawData;
63                         base.Critical = critical;
64                         _status = Decode (this.RawData);
65                 }
66
67                 public X509SubjectKeyIdentifierExtension (byte[] subjectKeyIdentifier, bool critical)
68                 {
69                         if (subjectKeyIdentifier == null)
70                                 throw new ArgumentNullException ("subjectKeyIdentifier");
71                         if (subjectKeyIdentifier.Length == 0)
72                                 throw new ArgumentException ("subjectKeyIdentifier");
73
74                         _oid = new Oid (oid, friendlyName);
75                         base.Critical = critical;
76                         _subjectKeyIdentifier = (byte[])subjectKeyIdentifier.Clone ();
77                         RawData = Encode ();
78                 }
79
80                 public X509SubjectKeyIdentifierExtension (string subjectKeyIdentifier, bool critical)
81                 {
82                         if (subjectKeyIdentifier == null)
83                                 throw new ArgumentNullException ("subjectKeyIdentifier");
84                         if (subjectKeyIdentifier.Length < 2)
85                                 throw new ArgumentException ("subjectKeyIdentifier");
86
87                         _oid = new Oid (oid, friendlyName);
88                         base.Critical = critical;
89                         _subjectKeyIdentifier = FromHex (subjectKeyIdentifier);
90                         RawData = Encode ();
91                 }
92
93                 public X509SubjectKeyIdentifierExtension (PublicKey key, bool critical)
94                         : this (key, X509SubjectKeyIdentifierHashAlgorithm.Sha1, critical)
95                 {
96                 }
97
98                 public X509SubjectKeyIdentifierExtension (PublicKey key, X509SubjectKeyIdentifierHashAlgorithm algorithm, bool critical)
99                 {
100                         if (key == null)
101                                 throw new ArgumentNullException ("key");
102
103                         byte[] pkraw = key.EncodedKeyValue.RawData;
104                         // compute SKI
105                         switch (algorithm) {
106                         // hash of the public key, excluding Tag, Length and unused bits values
107                         case X509SubjectKeyIdentifierHashAlgorithm.Sha1:
108                                 _subjectKeyIdentifier = SHA1.Create ().ComputeHash (pkraw);
109                                 break;
110                         // 0100 bit pattern followed by the 60 last bit of the hash
111                         case X509SubjectKeyIdentifierHashAlgorithm.ShortSha1:
112                                 byte[] hash = SHA1.Create ().ComputeHash (pkraw);
113                                 _subjectKeyIdentifier = new byte [8];
114                                 Buffer.BlockCopy (hash, 12, _subjectKeyIdentifier, 0, 8);
115                                 _subjectKeyIdentifier [0] = (byte) (0x40 | (_subjectKeyIdentifier [0] & 0x0F));
116                                 break;
117                         // hash of the public key, including Tag, Length and unused bits values
118                         case X509SubjectKeyIdentifierHashAlgorithm.CapiSha1:
119                                 // CryptoAPI does that hash on the complete subjectPublicKeyInfo (unlike PKIX)
120                                 // http://groups.google.ca/groups?selm=e7RqM%24plCHA.1488%40tkmsftngp02&oe=UTF-8&output=gplain
121                                 ASN1 subjectPublicKeyInfo = new ASN1 (0x30);
122                                 ASN1 algo = subjectPublicKeyInfo.Add (new ASN1 (0x30));
123                                 algo.Add (new ASN1 (CryptoConfig.EncodeOID (key.Oid.Value)));
124                                 algo.Add (new ASN1 (key.EncodedParameters.RawData)); 
125                                 // add an extra byte for the unused bits (none)
126                                 byte[] full = new byte [pkraw.Length + 1];
127                                 Buffer.BlockCopy (pkraw, 0, full, 1, pkraw.Length);
128                                 subjectPublicKeyInfo.Add (new ASN1 (0x03, full));
129                                 _subjectKeyIdentifier = SHA1.Create ().ComputeHash (subjectPublicKeyInfo.GetBytes ());
130                                 break;
131                         default:
132                                 throw new ArgumentException ("algorithm");
133                         }
134
135                         _oid = new Oid (oid, friendlyName);
136                         base.Critical = critical;
137                         RawData = Encode ();
138                 }
139
140                 // properties
141
142                 public string SubjectKeyIdentifier {
143                         get {
144                                 switch (_status) {
145                                 case AsnDecodeStatus.Ok:
146                                 case AsnDecodeStatus.InformationNotAvailable:
147                                         if (_subjectKeyIdentifier != null)
148                                                 _ski = CryptoConvert.ToHex (_subjectKeyIdentifier);
149                                         return _ski;
150                                 default:
151                                         throw new CryptographicException ("Badly encoded extension.");
152                                 }
153                         }
154                 }
155
156                 // methods
157
158                 public override void CopyFrom (AsnEncodedData encodedData)
159                 {
160                         if (encodedData == null)
161                                 throw new ArgumentNullException ("encodedData");
162
163                         X509Extension ex = (encodedData as X509Extension);
164                         if (ex == null)
165                                 throw new ArgumentException (Locale.GetText ("Wrong type."), "encodedData");
166
167                         if (ex._oid == null)
168                                 _oid = new Oid (oid, friendlyName);
169                         else 
170                                 _oid = new Oid (ex._oid);
171
172                         RawData = ex.RawData;
173                         base.Critical = ex.Critical;
174                         // and we deal with the rest later
175                         _status = Decode (this.RawData);
176                 }
177
178                 // internal
179
180                 static internal byte FromHexChar (char c) 
181                 {
182                         if ((c >= 'a') && (c <= 'f'))
183                                 return (byte) (c - 'a' + 10);
184                         if ((c >= 'A') && (c <= 'F'))
185                                 return (byte) (c - 'A' + 10);
186                         if ((c >= '0') && (c <= '9'))
187                                 return (byte) (c - '0');
188                         return 255;     // F
189                 }
190
191                 static internal byte FromHexChars (char c1, char c2)
192                 {
193                         byte result = FromHexChar (c1);
194                         if (result < 255)
195                                 result = (byte) ((result << 4) | FromHexChar (c2));
196                         return result;
197                 }
198
199                 static internal byte[] FromHex (string hex)
200                 {
201                         // here we can't use CryptoConvert.FromHex because we
202                         // must convert any *illegal* (non hex) 2 characters 
203                         // to 'FF' and ignore last char on odd length
204                         if (hex == null)
205                                 return null;
206
207                         int length = hex.Length >> 1;
208
209                         byte[] result = new byte [length]; // + (odd ? 1 : 0)];
210                         int n = 0;
211                         int i = 0;
212                         while (n < length) {
213                                 result [n++] = FromHexChars (hex [i++], hex [i++]);
214                         }
215                         return result;
216                 }
217
218                 internal AsnDecodeStatus Decode (byte[] extension)
219                 {
220                         if ((extension == null) || (extension.Length == 0))
221                                 return AsnDecodeStatus.BadAsn;
222                         _ski = String.Empty;
223                         if (extension [0] != 0x04)
224                                 return AsnDecodeStatus.BadTag;
225                         if (extension.Length == 2)
226                                 return AsnDecodeStatus.InformationNotAvailable;
227                         if (extension.Length < 3)
228                                 return AsnDecodeStatus.BadLength;
229
230                         try {
231                                 ASN1 ex = new ASN1 (extension);
232                                 _subjectKeyIdentifier = ex.Value;
233                         }
234                         catch {
235                                 return AsnDecodeStatus.BadAsn;
236                         }
237
238                         return AsnDecodeStatus.Ok;
239                 }
240
241                 internal byte[] Encode ()
242                 {
243                         ASN1 ex = new ASN1 (0x04, _subjectKeyIdentifier);
244                         return ex.GetBytes ();
245                 }
246
247                 internal override string ToString (bool multiLine)
248                 {
249                         switch (_status) {
250                         case AsnDecodeStatus.BadAsn:
251                                 return String.Empty;
252                         case AsnDecodeStatus.BadTag:
253                         case AsnDecodeStatus.BadLength:
254                                 return FormatUnkownData (_raw);
255                         case AsnDecodeStatus.InformationNotAvailable:
256                                 return "Information Not Available";
257                         }
258
259                         if (_oid.Value != oid)
260                                 return String.Format ("Unknown Key Usage ({0})", _oid.Value);
261
262                         StringBuilder sb = new StringBuilder ();
263
264                         for (int i=0; i < _subjectKeyIdentifier.Length; i++) {
265                                 sb.Append (_subjectKeyIdentifier [i].ToString ("x2"));
266                                 if (i != _subjectKeyIdentifier.Length - 1)
267                                         sb.Append (" ");
268                         }
269
270                         if (multiLine)
271                                 sb.Append (Environment.NewLine);
272
273                         return sb.ToString ();
274                 }
275         }
276 }
277
278 #endif