System.Web.Security.MachineKey.Decode C# (CSharp) Method

Decode() public static method

public static Decode ( string encodedData, MachineKeyProtection protectionOption ) : byte[]
encodedData string
protectionOption MachineKeyProtection
return byte[]
		public static byte[] Decode (string encodedData, MachineKeyProtection protectionOption)
		{
			if (encodedData == null)
				throw new ArgumentNullException ("encodedData");

			int dlen = encodedData.Length;
			if (dlen == 0 || dlen % 2 == 1)
				throw new ArgumentException ("encodedData");

			byte[] data = MachineKeySectionUtils.GetBytes (encodedData, dlen);
			if (data == null || data.Length == 0)
				throw new ArgumentException ("encodedData");
			
			var config = WebConfigurationManager.GetWebApplicationSection ("system.web/machineKey") as MachineKeySection;
			byte[] result = null;
			Exception ex = null;
			try {
				switch (protectionOption) {
					case MachineKeyProtection.All:
						result = MachineKeySectionUtils.VerifyDecrypt (config, data);
						break;

					case MachineKeyProtection.Encryption:
						result = MachineKeySectionUtils.Decrypt (config, data);
						break;

					case MachineKeyProtection.Validation:
						result = MachineKeySectionUtils.Verify (config, data);
						break;

					default:
						return MachineKeySectionUtils.GetBytes (encodedData, dlen);
				}
			} catch (Exception e) {
				ex = e;
			}
			
			if (result == null || ex != null)
				throw new HttpException ("Unable to verify passed data.", ex);
			
			return result;
		}

Usage Example

Example #1
0
        /// <summary>
        /// Uses .NET 4.0/4.5 API.
        /// With MachineKeyProtection.Encryption option.
        /// </summary>
        /// <param name="input">String to be decrypted.</param>
        /// <returns>Decrypted string.</returns>
        internal static string Unprotect(string input)
        {
#if NET40
            byte[] unprotectedBytes = MachineKey.Decode(input, MachineKeyProtection.Encryption);
            return(System.Text.Encoding.Unicode.GetString(unprotectedBytes));
#else
            byte[] protectedBytes   = Convert.FromBase64String(input);
            byte[] unprotectedBytes = MachineKey.Unprotect(protectedBytes);
            return(System.Text.Encoding.Unicode.GetString(unprotectedBytes));
#endif
        }