/// <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 <see cref="CookieSecureException"/> if tampered with /// </returns> public static string Decode(string text, CookieProtection cookieProtection) { if (string.IsNullOrEmpty(text)) { return text; } byte[] buf; var machineKeyProtection = Map(cookieProtection); try { buf = MachineKey.Decode(text, machineKeyProtection); } catch (Exception ex) { throw new CookieSecureException(Resources.CookieError1, ex.InnerException); } if (buf == null || buf.Length == 0) { throw new CookieSecureException(Resources.CookieError1); } return Encoding.UTF8.GetString(buf, 0, buf.Length); }
/// <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); }
internal static string Encode(CookieProtection cookieProtection, byte[] buf, int count) { if ((cookieProtection == CookieProtection.All) || (cookieProtection == CookieProtection.Validation)) { byte[] src = MachineKeySection.HashData(buf, null, 0, count); if (src == null) { return(null); } if (buf.Length >= (count + src.Length)) { Buffer.BlockCopy(src, 0, buf, count, src.Length); } else { byte[] buffer2 = buf; buf = new byte[count + src.Length]; Buffer.BlockCopy(buffer2, 0, buf, 0, count); Buffer.BlockCopy(src, 0, buf, count, src.Length); } count += src.Length; } if ((cookieProtection == CookieProtection.All) || (cookieProtection == CookieProtection.Encryption)) { buf = MachineKeySection.EncryptOrDecryptData(true, buf, null, 0, count); count = buf.Length; } if (count < buf.Length) { byte[] buffer3 = buf; buf = new byte[count]; Buffer.BlockCopy(buffer3, 0, buf, 0, count); } return(HttpServerUtility.UrlTokenEncode(buf)); }
/// <summary> /// 解密 /// </summary> /// <param name="text"></param> /// <param name="cookieProtection"></param> /// <returns></returns> public static string Decode(string text, CookieProtection cookieProtection = CookieProtection.All) { if (string.IsNullOrEmpty(text)) { return(text); } byte[] buf; string resStr = string.Empty; try { buf = CookieProtectionHelperWrapper.Decode(cookieProtection, text); if (buf == null || buf.Length == 0) { //throw new InvalidCypherTextException( // "Unable to decode the text"); } resStr = Encoding.UTF8.GetString(buf, 0, buf.Length); } catch (Exception ex) { //throw new InvalidCypherTextException( // "Unable to decode the text", ex.InnerException); } return(resStr); }
internal static string Encode(CookieProtection cookieProtection, byte[] buf, int count) { if ((cookieProtection == CookieProtection.All) || (cookieProtection == CookieProtection.Validation)) { byte[] src = MachineKeySection.HashData(buf, null, 0, count); if (src == null) { return null; } if (buf.Length >= (count + src.Length)) { Buffer.BlockCopy(src, 0, buf, count, src.Length); } else { byte[] buffer2 = buf; buf = new byte[count + src.Length]; Buffer.BlockCopy(buffer2, 0, buf, 0, count); Buffer.BlockCopy(src, 0, buf, count, src.Length); } count += src.Length; } if ((cookieProtection == CookieProtection.All) || (cookieProtection == CookieProtection.Encryption)) { buf = MachineKeySection.EncryptOrDecryptData(true, buf, null, 0, count); count = buf.Length; } if (count < buf.Length) { byte[] buffer3 = buf; buf = new byte[count]; Buffer.BlockCopy(buffer3, 0, buf, 0, count); } return HttpServerUtility.UrlTokenEncode(buf); }
public static string Encode(CookieProtection cookieProtection, byte[] buf, int count) { if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Validation) { byte[] array = HashData(buf, null, 0, count); if (array == null || array.Length != 20) { return(null); } if (buf.Length >= count + 20) { Buffer.BlockCopy(array, 0, buf, count, 20); } else { byte[] src = buf; buf = new byte[count + 20]; Buffer.BlockCopy(src, 0, buf, 0, count); Buffer.BlockCopy(array, 0, buf, count, 20); } count += 20; } if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Encryption) { buf = EncryptOrDecryptData(true, buf, null, 0, count); count = buf.Length; } if (count < buf.Length) { byte[] src2 = buf; buf = new byte[count]; Buffer.BlockCopy(src2, 0, buf, 0, count); } return(HttpServerUtility.UrlTokenEncode(buf)); }
internal static byte[] Decode (CookieProtection cookieProtection, string data, Purpose purpose) { byte[] buf = HttpServerUtility.UrlTokenDecode(data); if (AspNetCryptoServiceProvider.Instance.IsDefaultProvider) { // If we're configured to go through the new crypto routines, do so. ICryptoService cryptoService = AspNetCryptoServiceProvider.Instance.GetCryptoService(purpose); return cryptoService.Unprotect(buf); } #pragma warning disable 618 // calling obsolete methods // Otherwise fall back to using MachineKeySection. if (buf == null || cookieProtection == CookieProtection.None) return buf; if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Encryption) { buf = MachineKeySection.EncryptOrDecryptData (false, buf, null, 0, buf.Length); if (buf == null) return null; } if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Validation) return MachineKeySection.GetUnHashedData(buf); return buf; #pragma warning restore 618 // calling obsolete methods }
/// <summary> /// Decode the specified cookie. /// </summary> /// <param name="cookie">The cookie.</param> /// <param name="cookieProtection">The cookie protection.</param> /// <returns>the Decode</returns> public static HttpCookie Decode(HttpCookie cookie, CookieProtection cookieProtection) { HttpCookie decodedCookie = CloneCookie(cookie); decodedCookie.Value = Unprotect(cookie.Value, cookieProtection.ToString()); return(decodedCookie); }
/// <summary> /// Encodes a string /// </summary> /// <param name="text">String to encode</param> /// <param name="cookieProtection">The method in which the string is protected</param> /// <returns></returns> public static string Encode(string text, CookieProtection cookieProtection) { if (string.IsNullOrEmpty(text) || cookieProtection == CookieProtection.None) { return text; } byte[] buf = Encoding.UTF8.GetBytes(text); return CookieProtectionHelperWrapper.Encode(cookieProtection, buf, buf.Length); }
internal static byte[] Decode(CookieProtection cookieProtection, string data, Purpose purpose) { byte[] buf = HttpServerUtility.UrlTokenDecode(data); if (AspNetCryptoServiceProvider.Instance.IsDefaultProvider) { // If we're configured to go through the new crypto routines, do so. ICryptoService cryptoService = AspNetCryptoServiceProvider.Instance.GetCryptoService(purpose); return(cryptoService.Unprotect(buf)); } #pragma warning disable 618 // calling obsolete methods // Otherwise fall back to using MachineKeySection. if (buf == null || cookieProtection == CookieProtection.None) { return(buf); } if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Encryption) { buf = MachineKeySection.EncryptOrDecryptData(false, buf, null, 0, buf.Length); if (buf == null) { return(null); } } if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Validation) { return(MachineKeySection.GetUnHashedData(buf)); } return(buf); #pragma warning restore 618 // calling obsolete methods }
/// <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 <see cref="CookieSecureException"/> if tampered with /// </returns> public static string Decode(string text, CookieProtection cookieProtection) { if (string.IsNullOrEmpty(text)) { return(text); } byte[] buf; var machineKeyProtection = Map(cookieProtection); try { buf = MachineKey.Decode(text, machineKeyProtection); } catch (Exception ex) { throw new CookieSecureException(Resources.CookieError1, ex.InnerException); } if (buf == null || buf.Length == 0) { throw new CookieSecureException(Resources.CookieError1); } return(Encoding.UTF8.GetString(buf, 0, buf.Length)); }
private static void Initialize() { if (!s_Initialized) { lock (s_InitLock) { if (!s_Initialized) { AnonymousIdentificationSection anonymousIdentification = RuntimeConfig.GetAppConfig().AnonymousIdentification; s_Enabled = anonymousIdentification.Enabled; s_CookieName = anonymousIdentification.CookieName; s_CookiePath = anonymousIdentification.CookiePath; s_CookieTimeout = (int)anonymousIdentification.CookieTimeout.TotalMinutes; s_RequireSSL = anonymousIdentification.CookieRequireSSL; s_SlidingExpiration = anonymousIdentification.CookieSlidingExpiration; s_Protection = anonymousIdentification.CookieProtection; s_CookieMode = anonymousIdentification.Cookieless; s_Domain = anonymousIdentification.Domain; s_Modifier = Encoding.UTF8.GetBytes("AnonymousIdentification"); if (s_CookieTimeout < 1) { s_CookieTimeout = 1; } if (s_CookieTimeout > 0x100a40) { s_CookieTimeout = 0x100a40; } s_Initialized = true; } } } }
public static HttpCookie Encode(HttpCookie cookie, CookieProtection cookieProtection) { HttpCookie encodedCookie = CloneCookie(cookie); encodedCookie.Value = MachineKeyCryptography.Encode(cookie.Value, cookieProtection); return encodedCookie; }
/// <summary> /// Encode the specified cookie. /// </summary> /// <param name="cookie">The cookie.</param> /// <param name="cookieProtection">The cookie protection.</param> /// <returns>the Encode</returns> public static HttpCookie Encode(HttpCookie cookie, CookieProtection cookieProtection) { HttpCookie encodedCookie = CloneCookie(cookie); encodedCookie.Value = Protect(cookie.Value, cookieProtection.ToString()); return(encodedCookie); }
/// <summary> /// Encodes a string /// </summary> /// <param name="text">String to encode</param> /// <param name="cookieProtection">The method in which the string is protected</param> /// <returns></returns> public static string Encode(string text, CookieProtection cookieProtection) { if (string.IsNullOrEmpty(text) || cookieProtection == CookieProtection.None) { return(text); } byte[] buf = Encoding.UTF8.GetBytes(text); return(CookieProtectionHelperWrapper.Encode(cookieProtection, buf, buf.Length)); }
/// <summary> /// Encodes a string /// </summary> /// <param name="text"> /// String to encode /// </param> /// <param name="cookieProtection"> /// The method in which the string is protected /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> public static string Encode(string text, CookieProtection cookieProtection) { if (string.IsNullOrEmpty(text) || cookieProtection == CookieProtection.None) { return(text); } var buf = Encoding.UTF8.GetBytes(text); var map = Map(cookieProtection); return(MachineKey.Encode(buf, map)); }
internal static string Encode(CookieProtection cookieProtection, byte [] buf, Purpose purpose) { if (AspNetCryptoServiceProvider.Instance.IsDefaultProvider) { // If we're configured to go through the new crypto routines, do so. ICryptoService cryptoService = AspNetCryptoServiceProvider.Instance.GetCryptoService(purpose); return(HttpServerUtility.UrlTokenEncode(cryptoService.Protect(buf))); } #pragma warning disable 618 // calling obsolete methods // Otherwise fall back to using MachineKeySection. int count = buf.Length; if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Validation) { byte[] bMac = MachineKeySection.HashData(buf, null, 0, count); if (bMac == null) { return(null); } if (buf.Length >= count + bMac.Length) { Buffer.BlockCopy(bMac, 0, buf, count, bMac.Length); } else { byte[] bTemp = buf; buf = new byte[count + bMac.Length]; Buffer.BlockCopy(bTemp, 0, buf, 0, count); Buffer.BlockCopy(bMac, 0, buf, count, bMac.Length); } count += bMac.Length; } if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Encryption) { buf = MachineKeySection.EncryptOrDecryptData(true, buf, null, 0, count); count = buf.Length; } if (count < buf.Length) { byte[] bTemp = buf; buf = new byte[count]; Buffer.BlockCopy(bTemp, 0, buf, 0, count); } #pragma warning restore 618 // calling obsolete methods return(HttpServerUtility.UrlTokenEncode(buf)); }
/// <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); }
internal static string Encode (CookieProtection cookieProtection, byte [] buf, Purpose purpose) { if (AspNetCryptoServiceProvider.Instance.IsDefaultProvider) { // If we're configured to go through the new crypto routines, do so. ICryptoService cryptoService = AspNetCryptoServiceProvider.Instance.GetCryptoService(purpose); return HttpServerUtility.UrlTokenEncode(cryptoService.Protect(buf)); } #pragma warning disable 618 // calling obsolete methods // Otherwise fall back to using MachineKeySection. int count = buf.Length; if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Validation) { byte[] bMac = MachineKeySection.HashData (buf, null, 0, count); if (bMac == null) return null; if (buf.Length >= count + bMac.Length) { Buffer.BlockCopy (bMac, 0, buf, count, bMac.Length); } else { byte[] bTemp = buf; buf = new byte[count + bMac.Length]; Buffer.BlockCopy (bTemp, 0, buf, 0, count); Buffer.BlockCopy (bMac, 0, buf, count, bMac.Length); } count += bMac.Length; } if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Encryption) { buf = MachineKeySection.EncryptOrDecryptData (true, buf, null, 0, count); count = buf.Length; } if (count < buf.Length) { byte[] bTemp = buf; buf = new byte[count]; Buffer.BlockCopy (bTemp, 0, buf, 0, count); } #pragma warning restore 618 // calling obsolete methods return HttpServerUtility.UrlTokenEncode(buf); }
public string ToEncryptedTicket() { string roles = string.Join(",", GetRoles()); string cookiePath = RoleManagerConfig.CookiePath; int approxTicketLen = roles.Length + cookiePath.Length + 64; if (_cachedArray.Length > Roles.MaxCachedResults) { return(null); } MemoryStream ticket = new MemoryStream(approxTicketLen); BinaryWriter writer = new BinaryWriter(ticket); // version writer.Write(Version); // issue datetime DateTime issueDate = DateTime.Now; writer.Write(issueDate.Ticks); // expiration datetime writer.Write(_expireDate.Ticks); writer.Write(cookiePath); writer.Write(roles); CookieProtection cookieProtection = RoleManagerConfig.CookieProtection; byte[] ticket_data = ticket.GetBuffer(); if (cookieProtection == CookieProtection.All) { ticket_data = MachineKeySectionUtils.EncryptSign(MachineConfig, ticket_data); } else if (cookieProtection == CookieProtection.Encryption) { ticket_data = MachineKeySectionUtils.Encrypt(MachineConfig, ticket_data); } else if (cookieProtection == CookieProtection.Validation) { ticket_data = MachineKeySectionUtils.Sign(MachineConfig, ticket_data); } return(GetBase64FromBytes(ticket_data, 0, ticket_data.Length)); }
/// <summary> /// Invokes the logic of the middleware. /// </summary> /// <param name="context">The <see cref="HttpContext"/>.</param> /// <returns>A <see cref="Task"/> that completes when the middleware has completed processing.</returns> public async Task Invoke(HttpContext context) { var isNewSessionKey = false; Func <bool> tryEstablishSession = ReturnTrue; var cookieValue = context.Request.Headers[_options.Cookie.Name]; var sessionKey = CookieProtection.Unprotect(_dataProtector, cookieValue, _logger); if (string.IsNullOrWhiteSpace(sessionKey) || sessionKey.Length != SessionKeyLength) { // No valid cookie, new session. var guidBytes = new byte[16]; CryptoRandom.GetBytes(guidBytes); sessionKey = new Guid(guidBytes).ToString(); cookieValue = CookieProtection.Protect(_dataProtector, sessionKey); var establisher = new SessionEstablisher(context, cookieValue, _options); tryEstablishSession = establisher.TryEstablishSession; isNewSessionKey = true; } var feature = new SessionFeature(); feature.Session = _sessionStore.Create(sessionKey, TimeSpan.FromMinutes(120.0), TimeSpan.FromMinutes(3.0), tryEstablishSession, isNewSessionKey); context.Features.Set <ISessionFeature>(feature); try { await _next(context); } finally { context.Features.Set <ISessionFeature>(null); if (feature.Session != null) { try { await feature.Session.CommitAsync(context.RequestAborted); } catch (OperationCanceledException ex) { _logger.LogError(ex.Message); } } } }
/// <summary> /// Encodes a cookie with definable protection levels. /// </summary> /// <param name="cookie"> /// An object of type <see cref="System.Web.HttpCookie"/> to encode. /// </param> /// <param name="cookieProtection"> /// An enumeration of type <see cref="System.Web.Security.CookieProtection"/> defining the level of protection required. /// </param> /// <returns> /// An object of type <see cref="System.Web.HttpCookie"/> encoded and tamper proof. /// </returns> /// <exception cref="CookieSecureException"> /// Thrown if /// <paramref name="cookie"/> /// is invalid or tamper is detected. /// </exception> /// <example> /// The following C# example demonstrates how to Encode a cookie. /// <code> /// //Create a value to store /// string myValueToStoreInCookie = "My details"; /// /// //Create a "standard" (unencrypted) HttpCookie /// HttpCookie myCookie = new HttpCookie("MyCookieName",myValueToStoreInCookie); /// /// //encrypt the "standard" cookie /// HttpCookie myEncodedCookie = CookieSecure.Encode(myCookie, System.Web.Security.CookieProtection.Encryption); /// /// //Add the encoded cookie to the response stream. /// Page.Response.AppendCookie(myEncodedCookie); /// </code> /// </example> public static HttpCookie Encode(HttpCookie cookie, CookieProtection cookieProtection) { try { if (cookie != null) { var encodedCookie = CloneCookie(cookie); encodedCookie.Value = MachineKeyCryptography.Encode(cookie.Value, cookieProtection); return(encodedCookie); } return(null); } catch (Exception ex) { throw new CookieSecureException(Resources.CookieError2, ex.InnerException); } }
internal static byte[] Decode(CookieProtection cookieProtection, string data) { byte[] buf = HttpServerUtility.UrlTokenDecode(data); if ((buf == null) || (cookieProtection == CookieProtection.None)) { return(buf); } if ((cookieProtection == CookieProtection.All) || (cookieProtection == CookieProtection.Encryption)) { buf = MachineKeySection.EncryptOrDecryptData(false, buf, null, 0, buf.Length); if (buf == null) { return(null); } } if ((cookieProtection != CookieProtection.All) && (cookieProtection != CookieProtection.Validation)) { return(buf); } return(MachineKeySection.GetUnHashedData(buf)); }
/// <summary> /// The map. /// </summary> /// <param name="cookieProtection"> /// The cookie protection. /// </param> /// <returns> /// The <see cref="MachineKeyProtection"/>. /// </returns> private static MachineKeyProtection Map(CookieProtection cookieProtection) { MachineKeyProtection rtn; switch (cookieProtection) { case CookieProtection.Encryption: rtn = MachineKeyProtection.Encryption; break; case CookieProtection.Validation: rtn = MachineKeyProtection.Validation; break; default: rtn = MachineKeyProtection.All; break; } return(rtn); }
internal static byte[] Decode(CookieProtection cookieProtection, string data) { byte[] buf = HttpServerUtility.UrlTokenDecode(data); if ((buf == null) || (cookieProtection == CookieProtection.None)) { return buf; } if ((cookieProtection == CookieProtection.All) || (cookieProtection == CookieProtection.Encryption)) { buf = MachineKeySection.EncryptOrDecryptData(false, buf, null, 0, buf.Length); if (buf == null) { return null; } } if ((cookieProtection != CookieProtection.All) && (cookieProtection != CookieProtection.Validation)) { return buf; } return MachineKeySection.GetUnHashedData(buf); }
public static byte[] Decode(CookieProtection cookieProtection, string data) { byte[] array = HttpServerUtility.UrlTokenDecode(data); if (array == null || cookieProtection == CookieProtection.None) { return(array); } if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Encryption) { array = EncryptOrDecryptData(false, array, null, 0, array.Length); if (array == null) { return(null); } } if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Validation) { if (array.Length <= 20) { return(null); } byte[] array2 = new byte[array.Length - 20]; Buffer.BlockCopy(array, 0, array2, 0, array2.Length); byte[] array3 = HashData(array2, null, 0, array2.Length); if (array3 == null || array3.Length != 20) { return(null); } for (int i = 0; i < 20; i++) { if (array3[i] != array[array2.Length + i]) { return(null); } } array = array2; } return(array); }
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 System.Security.Cryptography.CryptographicException( "Unable to decode the text", ex.InnerException); } if (buf == null || buf.Length == 0) { throw new System.Security.Cryptography.CryptographicException( "Unable to decode the text"); } return(Encoding.UTF8.GetString(buf, 0, buf.Length)); }
///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // Static functions private static void Initialize() { if (s_Initialized) { return; } lock (s_InitLock) { if (s_Initialized) { return; } AnonymousIdentificationSection settings = RuntimeConfig.GetAppConfig().AnonymousIdentification; s_Enabled = settings.Enabled; s_CookieName = settings.CookieName; s_CookiePath = settings.CookiePath; s_CookieTimeout = (int)settings.CookieTimeout.TotalMinutes; s_RequireSSL = settings.CookieRequireSSL; s_SlidingExpiration = settings.CookieSlidingExpiration; s_Protection = settings.CookieProtection; s_CookieMode = settings.Cookieless; s_Domain = settings.Domain; s_Modifier = Encoding.UTF8.GetBytes("AnonymousIdentification"); if (s_CookieTimeout < 1) { s_CookieTimeout = 1; } if (s_CookieTimeout > 60 * 24 * 365 * 2) { s_CookieTimeout = 60 * 24 * 365 * 2; // 2 years } s_Initialized = true; } }
/// <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(this HttpCookie cookie, CookieProtection cookieProtection) { HttpCookie decodedCookie = CloneCookie(cookie); decodedCookie.Value = MachineKeyCryptography.Decode(cookie.Value, cookieProtection); return decodedCookie; }
/// <summary> /// Encodes a string /// </summary> /// <param name="text"> /// String to encode /// </param> /// <param name="cookieProtection"> /// The method in which the string is protected /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> public static string Encode(string text, CookieProtection cookieProtection) { if (string.IsNullOrEmpty(text) || cookieProtection == CookieProtection.None) { return text; } var buf = Encoding.UTF8.GetBytes(text); var map = Map(cookieProtection); return MachineKey.Encode(buf, map); }
/// <summary> /// The map. /// </summary> /// <param name="cookieProtection"> /// The cookie protection. /// </param> /// <returns> /// The <see cref="MachineKeyProtection"/>. /// </returns> private static MachineKeyProtection Map(CookieProtection cookieProtection) { MachineKeyProtection rtn; switch (cookieProtection) { case CookieProtection.Encryption: rtn = MachineKeyProtection.Encryption; break; case CookieProtection.Validation: rtn = MachineKeyProtection.Validation; break; default: rtn = MachineKeyProtection.All; break; } return rtn; }
/// <summary> /// Wrapper arround CookieProtectionHelper.Decode /// </summary> /// <param name="cookieProtection">Protection Type</param> /// <param name="data">String to decode</param> /// <returns>Decoded bytes</returns> public static byte[] Decode(CookieProtection cookieProtection, string data) { return (byte[])_decode.Invoke(null, new object[] { cookieProtection, data }); }
/// <summary> /// Wrapper arround CookieProtectionHelper.Encode /// </summary> /// <param name="cookieProtection">Protection Type</param> /// <param name="buf">Bytes buffer to encode</param> /// <param name="count">The number of bytes in the buffer</param> /// <returns>Encoded text</returns> public static string Encode(CookieProtection cookieProtection, byte[] buf, int count) { return (string)_encode.Invoke(null, new object[] { cookieProtection, buf, count }); }
private static void Initialize() { if (!s_Initialized) { lock (s_InitLock) { if (!s_Initialized) { AnonymousIdentificationSection anonymousIdentification = RuntimeConfig.GetAppConfig().AnonymousIdentification; s_Enabled = anonymousIdentification.Enabled; s_CookieName = anonymousIdentification.CookieName; s_CookiePath = anonymousIdentification.CookiePath; s_CookieTimeout = (int) anonymousIdentification.CookieTimeout.TotalMinutes; s_RequireSSL = anonymousIdentification.CookieRequireSSL; s_SlidingExpiration = anonymousIdentification.CookieSlidingExpiration; s_Protection = anonymousIdentification.CookieProtection; s_CookieMode = anonymousIdentification.Cookieless; s_Domain = anonymousIdentification.Domain; s_Modifier = Encoding.UTF8.GetBytes("AnonymousIdentification"); if (s_CookieTimeout < 1) { s_CookieTimeout = 1; } if (s_CookieTimeout > 0x100a40) { s_CookieTimeout = 0x100a40; } s_Initialized = true; } } } }
private static void Initialize() { if (s_Initialized) { if (s_InitializeException != null) { throw s_InitializeException; } if (s_InitializedDefaultProvider) { return; } } lock (s_lock) { if (s_Initialized) { if (s_InitializeException != null) { throw s_InitializeException; } if (s_InitializedDefaultProvider) { return; } } try { if (HostingEnvironment.IsHosted) { HttpRuntime.CheckAspNetHostingPermission(AspNetHostingPermissionLevel.Low, "Feature_not_supported_at_this_level"); } RoleManagerSection roleManager = RuntimeConfig.GetAppConfig().RoleManager; if (!s_EnabledSet) { s_Enabled = roleManager.Enabled; } s_CookieName = roleManager.CookieName; s_CacheRolesInCookie = roleManager.CacheRolesInCookie; s_CookieTimeout = (int) roleManager.CookieTimeout.TotalMinutes; s_CookiePath = roleManager.CookiePath; s_CookieRequireSSL = roleManager.CookieRequireSSL; s_CookieSlidingExpiration = roleManager.CookieSlidingExpiration; s_CookieProtection = roleManager.CookieProtection; s_Domain = roleManager.Domain; s_CreatePersistentCookie = roleManager.CreatePersistentCookie; s_MaxCachedResults = roleManager.MaxCachedResults; if (s_Enabled) { if (s_MaxCachedResults < 0) { throw new ProviderException(System.Web.SR.GetString("Value_must_be_non_negative_integer", new object[] { "maxCachedResults" })); } InitializeSettings(roleManager); InitializeDefaultProvider(roleManager); } } catch (Exception exception) { s_InitializeException = exception; } s_Initialized = true; } if (s_InitializeException != null) { throw s_InitializeException; } }
/// <summary> /// Wrapper arround CookieProtectionHelper.Encode /// </summary> /// <param name="cookieProtection">Protection Type</param> /// <param name="buf">Bytes buffer to encode</param> /// <param name="count">The number of bytes in the buffer</param> /// <returns>Encoded text</returns> public static string Encode(CookieProtection cookieProtection, byte[] buf, int count) { return((string)_encode.Invoke(null, new object[] { cookieProtection, buf, count })); }
private static void Initialize() { if (s_Initialized) { if (s_InitializeException != null) { throw s_InitializeException; } if (s_InitializedDefaultProvider) { return; } } lock (s_lock) { if (s_Initialized) { if (s_InitializeException != null) { throw s_InitializeException; } if (s_InitializedDefaultProvider) { return; } } try { if (HostingEnvironment.IsHosted) { HttpRuntime.CheckAspNetHostingPermission(AspNetHostingPermissionLevel.Low, "Feature_not_supported_at_this_level"); } RoleManagerSection roleManager = RuntimeConfig.GetAppConfig().RoleManager; if (!s_EnabledSet) { s_Enabled = roleManager.Enabled; } s_CookieName = roleManager.CookieName; s_CacheRolesInCookie = roleManager.CacheRolesInCookie; s_CookieTimeout = (int)roleManager.CookieTimeout.TotalMinutes; s_CookiePath = roleManager.CookiePath; s_CookieRequireSSL = roleManager.CookieRequireSSL; s_CookieSlidingExpiration = roleManager.CookieSlidingExpiration; s_CookieProtection = roleManager.CookieProtection; s_Domain = roleManager.Domain; s_CreatePersistentCookie = roleManager.CreatePersistentCookie; s_MaxCachedResults = roleManager.MaxCachedResults; if (s_Enabled) { if (s_MaxCachedResults < 0) { throw new ProviderException(System.Web.SR.GetString("Value_must_be_non_negative_integer", new object[] { "maxCachedResults" })); } InitializeSettings(roleManager); InitializeDefaultProvider(roleManager); } } catch (Exception exception) { s_InitializeException = exception; } s_Initialized = true; } if (s_InitializeException != null) { throw s_InitializeException; } }
void DecryptTicket(string encryptedTicket) { if (encryptedTicket == null || encryptedTicket == String.Empty) { throw new ArgumentException("Invalid encrypted ticket", "encryptedTicket"); } byte [] ticketBytes = GetBytesFromBase64(encryptedTicket); byte [] decryptedTicketBytes = null; CookieProtection cookieProtection = RoleManagerConfig.CookieProtection; if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Encryption) { ICryptoTransform decryptor; decryptor = TripleDES.Create().CreateDecryptor( MachineKeySectionUtils.DecryptionKey192Bits(MachineConfig), InitVector); decryptedTicketBytes = decryptor.TransformFinalBlock(ticketBytes, 0, ticketBytes.Length); } else { decryptedTicketBytes = ticketBytes; } if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Validation) { byte [] validationBytes = MachineKeySectionUtils.ValidationKeyBytes(MachineConfig); byte [] rolesWithValidationBytes = null; byte [] tmpValidation = null; int hashSize = (MachineConfig.Validation == MachineKeyValidation.MD5) ? 16 : 20; //md5 is 16 bytes, sha1 is 20 bytes rolesWithValidationBytes = new byte [decryptedTicketBytes.Length - hashSize + validationBytes.Length]; Buffer.BlockCopy(decryptedTicketBytes, 0, rolesWithValidationBytes, 0, decryptedTicketBytes.Length - hashSize); Buffer.BlockCopy(validationBytes, 0, rolesWithValidationBytes, decryptedTicketBytes.Length - hashSize, validationBytes.Length); switch (MachineConfig.Validation) { case MachineKeyValidation.MD5: tmpValidation = MD5.Create().ComputeHash(rolesWithValidationBytes); break; case MachineKeyValidation.TripleDES: case MachineKeyValidation.SHA1: tmpValidation = SHA1.Create().ComputeHash(rolesWithValidationBytes); break; } for (int i = 0; i < tmpValidation.Length; i++) { if (i >= decryptedTicketBytes.Length || tmpValidation [i] != decryptedTicketBytes [i + decryptedTicketBytes.Length - hashSize]) { throw new HttpException("ticket validation failed"); } } } MemoryStream ticket = new MemoryStream(decryptedTicketBytes); BinaryReader reader = new BinaryReader(ticket); // version _version = reader.ReadInt32(); // issued date _issueDate = new DateTime(reader.ReadInt64()); // expire date _expireDate = new DateTime(reader.ReadInt64()); // cookie path _cookiePath = reader.ReadString(); // roles string roles = reader.ReadString(); if (!Expired) { InitializeRoles(roles); //update ticket if less than half of CookieTimeout remaining. if (Roles.CookieSlidingExpiration) { if (_expireDate - DateTime.Now < TimeSpan.FromTicks(RoleManagerConfig.CookieTimeout.Ticks / 2)) { _issueDate = DateTime.Now; _expireDate = DateTime.Now.Add(RoleManagerConfig.CookieTimeout); SetDirty(); } } } else { // issue a new ticket _issueDate = DateTime.Now; _expireDate = _issueDate.Add(RoleManagerConfig.CookieTimeout); } }
///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // Static functions private static void Initialize() { if (s_Initialized) return; lock(s_InitLock) { if (s_Initialized) return; AnonymousIdentificationSection settings = RuntimeConfig.GetAppConfig().AnonymousIdentification; s_Enabled = settings.Enabled; s_CookieName = settings.CookieName; s_CookiePath = settings.CookiePath; s_CookieTimeout = (int) settings.CookieTimeout.TotalMinutes; s_RequireSSL = settings.CookieRequireSSL; s_SlidingExpiration = settings.CookieSlidingExpiration; s_Protection = settings.CookieProtection; s_CookieMode = settings.Cookieless; s_Domain = settings.Domain; s_Modifier = Encoding.UTF8.GetBytes("AnonymousIdentification"); if (s_CookieTimeout < 1) s_CookieTimeout = 1; if (s_CookieTimeout > 60 * 24 * 365 * 2) s_CookieTimeout = 60 * 24 * 365 * 2; // 2 years s_Initialized = true; } }
/// <summary> /// Wrapper arround CookieProtectionHelper.Decode /// </summary> /// <param name="cookieProtection">Protection Type</param> /// <param name="data">String to decode</param> /// <returns>Decoded bytes</returns> public static byte[] Decode(CookieProtection cookieProtection, string data) { return((byte[])_decode.Invoke(null, new object[] { cookieProtection, data })); }
/// <summary> /// Encodes a cookie with definable protection levels. /// </summary> /// <param name="cookie"> /// An object of type <see cref="System.Web.HttpCookie"/> to encode. /// </param> /// <param name="cookieProtection"> /// An enumeration of type <see cref="System.Web.Security.CookieProtection"/> defining the level of protection required. /// </param> /// <returns> /// An object of type <see cref="System.Web.HttpCookie"/> encoded and tamper proof. /// </returns> /// <exception cref="CookieSecureException"> /// Thrown if /// <paramref name="cookie"/> /// is invalid or tamper is detected. /// </exception> /// <example> /// The following C# example demonstrates how to Encode a cookie. /// <code> /// //Create a value to store /// string myValueToStoreInCookie = "My details"; /// /// //Create a "standard" (unencrypted) HttpCookie /// HttpCookie myCookie = new HttpCookie("MyCookieName",myValueToStoreInCookie); /// /// //encrypt the "standard" cookie /// HttpCookie myEncodedCookie = CookieSecure.Encode(myCookie, System.Web.Security.CookieProtection.Encryption); /// /// //Add the encoded cookie to the response stream. /// Page.Response.AppendCookie(myEncodedCookie); /// </code> /// </example> public static HttpCookie Encode(HttpCookie cookie, CookieProtection cookieProtection) { try { if (cookie != null) { var encodedCookie = CloneCookie(cookie); encodedCookie.Value = MachineKeyCryptography.Encode(cookie.Value, cookieProtection); return encodedCookie; } return null; } catch (Exception ex) { throw new CookieSecureException(Resources.CookieError2, ex.InnerException); } }
/// <summary> /// Decodes a cookie from definable protection level. /// </summary> /// <param name="cookie"> /// The encoded cookie to decode of type <see cref="System.Web.HttpCookie"/> . /// </param> /// <param name="cookieProtection"> /// An enumeration of type <see cref="System.Web.Security.CookieProtection"/> defining the level of protection to use when decoding the cookie. /// </param> /// <returns> /// An object of type <see cref="System.Web.HttpCookie"/> which is the decoded cookie. /// </returns> /// <exception cref="CookieSecureException"> /// Thrown if /// <paramref name="cookie"/> /// is invalid or tampered. /// </exception> /// <example> /// The following C# example shows how to decode a cookie that has been encoded using "Encryption" only. /// <code> /// HttpCookie standardCookie = Request.Cookies["MyCookieName"]; /// if(standardCookie!=null) /// { /// HttpCookie decodedCookie = CookieSecure.Decode(standardCookie,System.Web.Security.CookieProtection.Encryption); /// //...Go on to process decoded cookie /// } /// </code> /// </example> public static HttpCookie Decode(HttpCookie cookie, CookieProtection cookieProtection) { if (cookie != null) { var decodedCookie = CloneCookie(cookie); decodedCookie.Value = MachineKeyCryptography.Decode(cookie.Value, cookieProtection); return decodedCookie; } return null; }
public string ToEncryptedTicket() { string roles = string.Join(",", GetRoles()); string cookiePath = RoleManagerConfig.CookiePath; int approxTicketLen = roles.Length + cookiePath.Length + 64; if (_cachedArray.Length > Roles.MaxCachedResults) { return(null); } MemoryStream ticket = new MemoryStream(approxTicketLen); BinaryWriter writer = new BinaryWriter(ticket); // version writer.Write(Version); // issue datetime DateTime issueDate = DateTime.Now; writer.Write(issueDate.Ticks); // expiration datetime writer.Write(_expireDate.Ticks); writer.Write(cookiePath); writer.Write(roles); CookieProtection cookieProtection = RoleManagerConfig.CookieProtection; if (cookieProtection == CookieProtection.None) { return(GetBase64FromBytes(ticket.GetBuffer(), 0, (int)ticket.Position)); } if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Validation) { byte [] hashBytes = null; byte [] validationBytes = MachineKeySectionUtils.ValidationKeyBytes(MachineConfig); writer.Write(validationBytes); switch (MachineConfig.Validation) { case MachineKeyValidation.MD5: hashBytes = MD5.Create().ComputeHash(ticket.GetBuffer(), 0, (int)ticket.Position); break; case MachineKeyValidation.TripleDES: case MachineKeyValidation.SHA1: hashBytes = SHA1.Create().ComputeHash(ticket.GetBuffer(), 0, (int)ticket.Position); break; } writer.Seek(-validationBytes.Length, SeekOrigin.Current); writer.Write(hashBytes); } byte [] ticketBytes = null; if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Encryption) { ICryptoTransform enc; enc = TripleDES.Create().CreateEncryptor(MachineKeySectionUtils.DecryptionKey192Bits(MachineConfig), InitVector); ticketBytes = enc.TransformFinalBlock(ticket.GetBuffer(), 0, (int)ticket.Position); } if (ticketBytes == null) { return(GetBase64FromBytes(ticket.GetBuffer(), 0, (int)ticket.Position)); } else { return(GetBase64FromBytes(ticketBytes, 0, ticketBytes.Length)); } }
void DecryptTicket(string encryptedTicket) { if (encryptedTicket == null || encryptedTicket == String.Empty) { throw new ArgumentException("Invalid encrypted ticket", "encryptedTicket"); } byte [] ticketBytes = GetBytesFromBase64(encryptedTicket); byte [] decryptedTicketBytes = null; CookieProtection cookieProtection = RoleManagerConfig.CookieProtection; if (cookieProtection == CookieProtection.All) { decryptedTicketBytes = MachineKeySectionUtils.VerifyDecrypt(MachineConfig, ticketBytes); } else if (cookieProtection == CookieProtection.Encryption) { decryptedTicketBytes = MachineKeySectionUtils.Decrypt(MachineConfig, ticketBytes); } else if (cookieProtection == CookieProtection.Validation) { decryptedTicketBytes = MachineKeySectionUtils.Verify(MachineConfig, ticketBytes); } if (decryptedTicketBytes == null) { throw new HttpException("ticket validation failed"); } MemoryStream ticket = new MemoryStream(decryptedTicketBytes); BinaryReader reader = new BinaryReader(ticket); // version _version = reader.ReadInt32(); // issued date _issueDate = new DateTime(reader.ReadInt64()); // expire date _expireDate = new DateTime(reader.ReadInt64()); // cookie path _cookiePath = reader.ReadString(); // roles string roles = reader.ReadString(); if (!Expired) { InitializeRoles(roles); //update ticket if less than half of CookieTimeout remaining. if (Roles.CookieSlidingExpiration) { if (_expireDate - DateTime.Now < TimeSpan.FromTicks(RoleManagerConfig.CookieTimeout.Ticks / 2)) { _issueDate = DateTime.Now; _expireDate = DateTime.Now.Add(RoleManagerConfig.CookieTimeout); SetDirty(); } } } else { // issue a new ticket _issueDate = DateTime.Now; _expireDate = _issueDate.Add(RoleManagerConfig.CookieTimeout); } }
public void TestFixtureSetup() { this.testCookie = new HttpCookie(CookieName, Decrypted); this.cookieProtection = CookieProtection.All; }