Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Gracefully handling exceptions

Status
Not open for further replies.
Jun 9, 2006
159
US
I have a cookie class that calls this decode method. Occasionaly its throwing a weird exception. In the case of this excpetion being thrown I'd like it to remove the cookie and perform some other actions, instead of halting the application and displaying this exception to the user.

what are my options?


Code:
        /// <summary>
        /// Decodes a string
        /// </summary>
        /// <param name="text">String to decode</param>
        /// <param name="cookieProtection">The method in which the string is protected</param>
        /// <returns>The decoded string or throws InvalidCypherTextException if tampered with</returns>
        public static string Decode(string text, CookieProtection cookieProtection) {
            if (string.IsNullOrEmpty(text)) {
                return text;
            }
            byte[] buf;
            try {
                buf = CookieProtectionHelperWrapper.Decode(cookieProtection, text);
            }
            catch(Exception ex) {
                throw new InvalidCypherTextException("Unable to decode the text", ex.InnerException);
            }
            if (buf == null || buf.Length == 0) {
                throw new InvalidCypherTextException("Unable to decode the text");
            }
            return Encoding.UTF8.GetString(buf, 0, buf.Length);
        }
    }

Shawn Molloy
Seattle, WA
 
As a general rule, you shouldn't use exceptions to control application flow, but considering your post you probably already know that.

I would try to get to the bottom of what the "weird exception" is. Otherwise, it seems like you would be doing what I said not to do above ;-)

Could you post the error message?
 
LoL you are going to be sorry you asked.

I am in agreement; I would like to fix this problem at the root. Lets give it a shot.

This a secure HTTPCookie solution I built.

Code:
    private void CheckCookie() 
    {
        HttpCookie cookie = Request.Cookies["userId"];
        HttpCookie decodedCookie = HttpSecureCookie.Decode(cookie);
        if (decodedCookie.Value != "-1")
        {
            Session["UserId"] = decodedCookie.Value;
            Response.Redirect("settings/");
        }
    }


Here is my HttpSecureCookie Class:

Code:
/// <summary>
    /// Provides cookie cyphering services.
    /// </summary>
    public static class HttpSecureCookie {

        /// <summary>
        /// Encodes a cookie with all protection levels
        /// </summary>
        /// <param name="cookie">The cookie to encode</param>
        /// <returns>A clone of the cookie in encoded format</returns>
        public static HttpCookie Encode(HttpCookie cookie) {
            return Encode(cookie, CookieProtection.All);
        }

        /// <summary>
        /// Encodes a cookie
        /// </summary>
        /// <param name="cookie">The cookie to encode</param>
        /// <param name="cookieProtection">The cookie protection to set</param>
        /// <returns>A clone of the cookie in encoded format</returns>
        public static HttpCookie Encode(HttpCookie cookie, CookieProtection cookieProtection) {
            HttpCookie encodedCookie = CloneCookie(cookie);
            encodedCookie.Value = MachineKeyCryptography.Encode(cookie.Value, cookieProtection);
            return encodedCookie;
        }

        /// <summary>
        /// Decodes a cookie that has all levels of cookie protection. Throws InvalidCypherTextException if unable to decode.
        /// </summary>
        /// <param name="cookie">The cookie to decode</param>
        /// <returns>A clone of the cookie in decoded format</returns>
        public static HttpCookie Decode(HttpCookie cookie) {
            return Decode(cookie, CookieProtection.All);
        }

        /// <summary>
        /// Decodes a cookie. Throws InvalidCypherTextException if unable to decode.
        /// </summary>
        /// <param name="cookie">The cookie to decode</param>
        /// <param name="cookieProtection">The protection level to use when decoding</param>
        /// <returns>A clone of the cookie in decoded format</returns>
        public static HttpCookie Decode(HttpCookie cookie, CookieProtection cookieProtection) {
            HttpCookie decodedCookie = CloneCookie(cookie);
            decodedCookie.Value = MachineKeyCryptography.Decode(cookie.Value, cookieProtection);
            return decodedCookie;
        }

        /// <summary>
        /// Creates a clone of the given cookie
        /// </summary>
        /// <param name="cookie">A cookie to clone</param>
        /// <returns>The cloned cookie</returns>
        public static HttpCookie CloneCookie(HttpCookie cookie) {
            HttpCookie clonedCookie = new HttpCookie(cookie.Name, cookie.Value);
            clonedCookie.Domain = cookie.Domain;
            clonedCookie.Expires = cookie.Expires;
            clonedCookie.HttpOnly = cookie.HttpOnly;
            clonedCookie.Path = cookie.Path;
            clonedCookie.Secure = cookie.Secure;

            return clonedCookie;
        }
    
    }

The error happens in the Decode() fucntion. Through debugging I can see that the two parameters are String Text = "JXwx8dL1K9kf-4hPJZotwZ_4B0_eWu2fdpIp6PCCmxE1" and CookieProtection = All.


The exception says: {"Unable to decode the text"} and is of the type InvalidCypherTextException.

The specific Error that is being presented is "The Padding Legnth is Invalid" or something.

This error only happens occasionally. Usually when there is a cookie present, but after some time has elapsed since the user has visited the page. If there is no cookie it works fine, or if its in the same few days it seems to be ok... ???

Thanks for you help!

Shawn Molloy
Seattle, WA
 
Hmm, I've never done this before, so maybe there is someone else here who can help you better than me.

I was reading, and did you explicitly set your machine key?

This msdn article states ( :
even if your application runs on a single Web server, if the keys need to remain stable over time, you should explicitly set the values for both validation and decryption
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top