2 // System.Web.Configuration.MachineKeyConfigHandler
5 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 // (C) 2002 Ximian, Inc (http://www.ximian.com)
11 using System.Collections;
12 using System.Configuration;
13 using System.Security.Cryptography;
16 namespace System.Web.Configuration
18 class MachineKeyConfigHandler : IConfigurationSectionHandler
20 static byte [] autogenerated;
21 static MachineKeyConfigHandler ()
23 autogenerated = new byte [64];
24 RNGCryptoServiceProvider cp = new RNGCryptoServiceProvider ();
25 cp.GetBytes (autogenerated);
28 static byte ToHexValue (char c, bool high)
31 if (c >= '0' && c <= '9')
33 else if (c >= 'a' && c <= 'f')
34 v = (byte) (c - 'a' + 10);
35 else if (c >= 'A' && c <= 'F')
36 v = (byte) (c - 'A' + 10);
38 throw new ArgumentException ("Invalid hex character");
46 internal static byte [] GetBytes (string key, int len)
48 byte [] result = new byte [len / 2];
49 for (int i = 0; i < len; i += 2)
50 result [i / 2] = (byte) (ToHexValue (key [i], true) + ToHexValue (key [i + 1], false));
55 static byte [] MakeKey (string key)
57 if (key == null || key == "AutoGenerated")
61 if (len < 40 || len > 128 || (len % 2) == 1)
62 throw new ArgumentException ("Invalid key length");
64 return GetBytes (key, len);
67 public object Create (object parent, object context, XmlNode section)
69 if (section.HasChildNodes)
70 ThrowException ("Child nodes not allowed here", section.FirstChild);
72 MachineKeyConfig config = new MachineKeyConfig (parent);
74 string validationKey = AttValue ("validationKey", section);
76 config.ValidationKey = MakeKey (validationKey);
77 } catch (ArgumentException e) {
78 ThrowException (e.Message, section);
81 string decryptionKey = AttValue ("decryptionKey", section);
83 config.DecryptionKey = MakeKey (decryptionKey);
84 } catch (ArgumentException e) {
85 ThrowException (e.Message, section);
88 string validation = AttValue ("validation", section);
89 if (validation != "SHA1" && validation != "MD5" && validation != "3DES")
90 ThrowException ("Invalid 'validation' value", section);
92 config.ValidationType = validation;
94 if (section.Attributes != null && section.Attributes.Count != 0)
95 ThrowException ("Unrecognized attribute", section);
97 MachineKeyConfig.MachineKey = config;
101 // A few methods to save some typing
102 static string AttValue (string name, XmlNode node)
104 return HandlersUtil.ExtractAttributeValue (name, node, true);
107 static void ThrowException (string message, XmlNode node)
109 HandlersUtil.ThrowException (message, node);