Ejemplo n.º 1
0
        /// <summary>
        /// Decrypts the cookie.
        /// </summary>
        /// <param name="cookie">The cookie to decrypt.</param>
        /// <returns>A new HttpCookie instance with the Value decrypted.</returns>
        public static HttpCookie Decrypt(HttpCookie cookie)
        {
            if (cookie == null)
            {
                throw new ArgumentNullException("cookie");
            }

            //nothing to do!
            if (cookie.Value.Length == 0)
            {
                return(cookie);
            }

            try
            {
                byte[] encrypted = MachineKeyWrapper.HexStringToByteArray(cookie.Value);
                if (encrypted == null)
                {
                    return(null);                                       // i wonder if this is the most intuitive situation here... the above method will return null if it cant "DeHex" the string...
                }
                byte[] decrypted = MachineKeyWrapper.EncryptOrDecryptData(false, encrypted, null, 0, encrypted.Length);

                //i wonder if I should guarantee getting a cookie at this point [no exceptions, etc]
                HttpCookie decryptedCookie = CloneCookie(cookie);

                decryptedCookie.Value = System.Text.Encoding.Unicode.GetString(decrypted);

                return(decryptedCookie);
            }
            catch (Exception ex)
            {
                //repackage the exception
                throw new HttpException("Unable to Decrypt the cookie.", ex);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Returns an encrypted cookie without updating the Response.
        /// </summary>
        /// <param name="source">The cookie to encrypt</param>
        /// <returns>An encrypted instance, cloned from the source.</returns>
        public static HttpCookie Encrypt(HttpCookie source)
        {
            try
            {
                byte[] data    = System.Text.Encoding.Unicode.GetBytes(source.Value);
                byte[] encData = MachineKeyWrapper.EncryptOrDecryptData(true, data, null, 0, data.Length);

                HttpCookie encrypted = CloneCookie(source);
                encrypted.Value = MachineKeyWrapper.ByteArrayToHexString(encData, encData.Length);

                return(encrypted);
            }
            catch (Exception ex)
            {
                //repackage
                throw new HttpException("Unable to encrypt the cookie.", ex);
            }
        }