コード例 #1
0
        public byte[] Decode(string value)
        {
#pragma warning disable 618
            return(MachineKey.Decode(Base64ToHex(value), MachineKeyProtection.All));

#pragma warning restore 618
        }
コード例 #2
0
ファイル: MachineKeyUtil.cs プロジェクト: terry2012/DSV
            /// <summary>
            /// Unprotects the specified protected data.
            /// </summary>
            /// <param name="protectedData">The protected data.</param>
            /// <param name="purposes">The purposes.</param>
            /// <returns>The unprotected data</returns>
            public byte[] Unprotect(byte[] protectedData, string[] purposes)
            {
                if (protectedData == null)
                {
                    throw new ArgumentNullException("protectedData");
                }

                // convert binary -> hex and calculate what the purpose should read
                string hexEncodedData = BinaryToHex(protectedData);

                byte[] purposeHash = ComputeSHA256(purposes);

                try {
                    // decrypt / verify signature
                    byte[] dataWithHeader = MachineKey.Decode(hexEncodedData, MachineKeyProtection.All);

                    // validate magic header and purpose string
                    if (dataWithHeader != null &&
                        dataWithHeader.Length >= (4 + (256 / 8)) &&
                        (uint)IPAddress.NetworkToHostOrder(BitConverter.ToInt32(dataWithHeader, 0)) == MagicHeader &&
                        AreByteArraysEqual(new ArraySegment <byte>(purposeHash), new ArraySegment <byte>(dataWithHeader, 4, 256 / 8)))
                    {
                        // validation succeeded
                        byte[] userData = new byte[dataWithHeader.Length - 4 - (256 / 8)];
                        Buffer.BlockCopy(dataWithHeader, 4 + (256 / 8), userData, 0, userData.Length);
                        return(userData);
                    }
                }
                catch {
                    // swallow since will be rethrown immediately below
                }

                // if we reached this point, some cryptographic operation failed
                throw new CryptographicException(Strings.Generic_CryptoFailure);
            }
コード例 #3
0
        public string DecryptDealerId(string DealerId)
        {
            var decryptedBytes = MachineKey.Decode(DealerId, MachineKeyProtection.All);
            var DecryptedId    = Encoding.UTF8.GetString(decryptedBytes);

            return(DecryptedId);
        }
コード例 #4
0
        /// <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));
        }
コード例 #5
0
        private static string TryOldDecode(string text)
        {
            // Detta är bara med som support för gamla cookies under en kort tid. Tas med fördel bort i release efter .net 4.5.
            var buf = MachineKey.Decode(text, MachineKeyProtection.All);

            return(Encoding.UTF8.GetString(buf, 0, buf.Length));
        }
コード例 #6
0
        public static string Decrypt(string encrypted)
        {
            var bytes = MachineKey.Decode(encrypted, MachineKeyProtection.Encryption);
            var value = Encoding.Unicode.GetString(bytes);

            return(value);
        }
コード例 #7
0
        //#region PageInit
        //protected void Page_Init(object sender, EventArgs e)
        //{
        //    SecureUserGroupsModel[] obj = client.EditSecurUserbyID(UserID);
        //    List<int> list = new List<int>();
        //    list.Add(6);
        //    list.Add(4);
        //    list.Add(12);
        //    var result = obj.Where(x => list.Contains(x.fkiSecureGroupID));
        //    if (result.FirstOrDefault() == null)
        //    {
        //        Response.Redirect("~/Admin/403Error.aspx", false);
        //    }
        //}
        //#endregion

        #region Pageload
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request.QueryString.ToString()))
            {
                var decryptedBytes = MachineKey.Decode(Request.QueryString["ID"], MachineKeyProtection.All);
                var decryptedValue = Encoding.UTF8.GetString(decryptedBytes);
                int QouID          = Convert.ToInt32(decryptedValue);
                ViewState["_QuotationID"] = QouID;
            }
            else
            {
                Response.Redirect("~/Admin/Qoutation.aspx");
            }
            if (!IsPostBack)
            {
                GetCompDetails();
                bindServicesType();
                GetQuotationData();
                bindServiceListList();
                DiscountCal();
                //GetQuotationNumber();
                BindRejectMsg();
                BindAllPackage();
                LoadUserRights();
            }
        }
コード例 #8
0
        public static bool UnprotectData(
            string protectedData,
            out string providerName,
            out string providerUserId
            )
        {
            providerName   = null;
            providerUserId = null;
            if (String.IsNullOrEmpty(protectedData))
            {
                return(false);
            }
#pragma warning disable 0618 // Decode is [Obsolete] in 4.5
            byte[] decodedWithPadding = MachineKey.Decode(protectedData, MachineKeyProtection.All);
#pragma warning restore 0618
            if (decodedWithPadding.Length < _padding.Length)
            {
                return(false);
            }

            // timing attacks aren't really applicable to this, so we just do the simple check.
            for (int i = 0; i < _padding.Length; i++)
            {
                if (_padding[i] != decodedWithPadding[i])
                {
                    return(false);
                }
            }

            using (
                MemoryStream ms = new MemoryStream(
                    decodedWithPadding,
                    _padding.Length,
                    decodedWithPadding.Length - _padding.Length
                    )
                )
                using (BinaryReader br = new BinaryReader(ms))
                {
                    try
                    {
                        // use temp variable to keep both out parameters consistent and only set them when the input stream is read completely
                        string name   = br.ReadString();
                        string userId = br.ReadString();

                        // make sure that we consume the entire input stream
                        if (ms.ReadByte() == -1)
                        {
                            providerName   = name;
                            providerUserId = userId;
                            return(true);
                        }
                    }
                    catch
                    {
                        // Any exceptions will result in this method returning false.
                    }
                }
            return(false);
        }
コード例 #9
0
 public override byte[] Decode(byte[] encoded)
 {
     if (encoded == null)
     {
         throw new ArgumentNullException("encoded");
     }
     return(MachineKey.Decode(Encoding.UTF8.GetString(encoded), MachineKeyProtection.All));
 }
コード例 #10
0
        public virtual byte[] Unprotect(byte[] protectedData)
        {
#if NET40
            return(MachineKey.Decode(Encoding.UTF8.GetString(protectedData), MachineKeyProtection.All));
#endif
#if NET45
            return(MachineKey.Unprotect(protectedData, _purposes));
#endif
        }
コード例 #11
0
        private static byte[] Unprotect(string value)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                return(null);
            }

            return(MachineKey.Decode(value, MachineKeyProtection.All));
        }
コード例 #12
0
        private static byte[] Decode(string encryptedData)
        {
#if GTNet40
            byte[] data = Convert.FromBase64String(encryptedData);
            return(MachineKey.Unprotect(data));
#else
            return(MachineKey.Decode(encryptedData, MachineKeyProtection.Encryption));
#endif
        }
        SessionSecurityToken BytesToToken(byte[] bytes)
        {
            if (bytes == null || bytes.Length == 0)
            {
                return(null);
            }

            var str = System.Text.Encoding.UTF8.GetString(bytes);

            bytes = MachineKey.Decode(str, MachineKeyProtection.All);
            return(serializer.Deserialize(bytes));
        }
コード例 #14
0
 public static string Decrypt(string encryptedValue)
 {
     try
     {
         var decryptedBytes = MachineKey.Decode(encryptedValue, MachineKeyProtection.All);
         return(Encoding.UTF8.GetString(decryptedBytes));
     }
     catch
     {
         return(null);
     }
 }
コード例 #15
0
 private static string Desproteccion(string tokenID)
 {
     try
     {
         var ByteSinProteccion = MachineKey.Decode(tokenID, MachineKeyProtection.All);
         return(Encoding.ASCII.GetString(ByteSinProteccion));
     }
     catch
     {
         return(null);
     }
 }
コード例 #16
0
        /// <summary>
        /// Decrypt string
        /// </summary>
        /// <param name="data">Data to decrypt</param>
        /// <returns>Decrypted string</returns>
        public string Decrypt(string data)
        {
            try
            {
                var bytes = MachineKey.Decode(data, MachineKeyProtection.Encryption);

                return(Encoding.UTF8.GetString(bytes));
            }
            catch (Exception)
            {
                return(string.Empty);
            }
        }
コード例 #17
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //The hidden form field that contains our hash - for ex. CustomerId is rendered as a hidden input  id="_CustomerIdToken"
            string encryptedPropertyName = string.Format("_{0}Token", _propertyName);

            //grab the token
            string hashToken = filterContext.HttpContext.Request.Form[encryptedPropertyName];

            //The encrypted form data MUST be there. We do not allow empty strings otherwise this could give
            //an attack vector in our filter as a means to bypass checks by simply passing in an empty validation token.
            if (string.IsNullOrEmpty(hashToken))
            {
                throw new MissingFieldException(string.Format("The hidden form field named value {0} was missing. This is created by the Html.AntiModelInjection methods. Ensure the name used on your [ValidateAntiModelInjectionAttribute(\"!HERE!\")] matches the field name used in Html.AntiModelInjection method. If this attribute is used on a controller method that is meant for HttpGet, then the form value would not yet exist. This attribute is meant to be used on controller methods accessed via HttpPost.", encryptedPropertyName));
            }


            //Get the plain text value
            string formValue = filterContext.HttpContext.Request.Form[_propertyName];

            //Plain text must be available to compare.
            if (string.IsNullOrEmpty(formValue))
            {
                throw new MissingFieldException(string.Format("The form value {0} was missing. If this attribute is used on a controller method that is meant for HttpGet, then the form value would not yet exist. This attribute is meant to be used on controller methods accessed via HttpPost.", _propertyName));
            }


            //We cannot encrypt the form value and compare to the previously encrypted form token.
            //Each time you Encrypt() with the MachineKey class even using the same plain text, the end result is difference.
            byte[] plainTextBytes = MachineKey.Decode(hashToken, MachineKeyProtection.Encryption);

            string plainText = Encoding.Unicode.GetString(plainTextBytes);


            //TODO: Note that this implementation still can be fiddled with by copying both form value and token to another
            //session. Soon this will likely be user specific.


            //And compare
            if (string.Compare(plainText, formValue, false, CultureInfo.InvariantCulture) != 0)
            {
                throw new HttpAntiModelInjectionException(string.Format("Failed security validation for {0}. It is possible the data was tampered with as the original value used to create the form field does not match the current property value for this field. Ensure if this is a web farm, the machine keys are the same.", _propertyName));
            }


            filterContext.HttpContext.Trace.Write("(Logging Filter)Action Executing: " +
                                                  filterContext.ActionDescriptor.ActionName);

            base.OnActionExecuting(filterContext);
        }
コード例 #18
0
        public byte[] Load()
        {
            var bytes = inner.Load();

            try
            {
                var str = System.Text.Encoding.UTF8.GetString(bytes);
                return(MachineKey.Decode(str, MachineKeyProtection.All));
            }
            catch
            {
                inner.Save(null);
            }
            return(null);
        }
コード例 #19
0
        public bool TryDeserializeOAuthProviderUserId(string protectedData, out string providerName, out string providerUserId)
        {
            providerName   = null;
            providerUserId = null;
            if (String.IsNullOrEmpty(protectedData))
            {
                return(false);
            }

            var decodedWithPadding = MachineKey.Decode(protectedData, MachineKeyProtection.All);

            if (decodedWithPadding.Length < _padding.Length)
            {
                return(false);
            }

            // timing attacks aren't really applicable to this, so we just do the simple check.
            for (var i = 0; i < _padding.Length; i++)
            {
                if (_padding[i] != decodedWithPadding[i])
                {
                    return(false);
                }
            }

            using (var ms = new MemoryStream(decodedWithPadding, _padding.Length, decodedWithPadding.Length - _padding.Length))
                using (var br = new BinaryReader(ms))
                {
                    try
                    {
                        // use temp variable to keep both out parameters consistent and only set them when the input stream is read completely
                        var name   = br.ReadString();
                        var userId = br.ReadString();
                        // make sure that we consume the entire input stream
                        if (ms.ReadByte() == -1)
                        {
                            providerName   = name;
                            providerUserId = userId;
                            return(true);
                        }
                    }
                    catch
                    {
                        // Any exceptions will result in this method returning false.
                    }
                }
            return(false);
        }
コード例 #20
0
            public byte[] Unprotect(string protectedData)
            {
                string hex = Base64ToHex(protectedData);

                byte[] dataWithHeader = MachineKey.Decode(hex, MachineKeyProtection.All);

                if (dataWithHeader == null || dataWithHeader.Length < 4 || (uint)IPAddress.NetworkToHostOrder(BitConverter.ToInt32(dataWithHeader, 0)) != _magicHeader)
                {
                    // the decoded data is blank or doesn't begin with the magic header
                    return(null);
                }

                byte[] retVal = new byte[dataWithHeader.Length - 4];
                Buffer.BlockCopy(dataWithHeader, 4, retVal, 0, retVal.Length);
                return(retVal);
            }
コード例 #21
0
        public List <FlashMessageModel> Peek()
        {
            // Attempt to retrieve cookie. If the cookie is non existent, return an empty message list.
            var context = new HttpContextWrapper(HttpContext.Current);
            var cookie  = context.Request.Cookies[CookieName];

            if (cookie == null)
            {
                return(new List <FlashMessageModel>());
            }

            // Decode and deserialize the data.
            var serializedMessages = MachineKey.Decode(cookie.Value, MachineKeyProtection.All);

            return(FlashMessage.Deserialize(serializedMessages));
        }
コード例 #22
0
ファイル: SecurityUtil.cs プロジェクト: INGEPEREZ1091/Report
        public static string Decrypt(string encrypted)
        {
#if NET45
            var encryptedBytes = Hex2Bytes(encrypted);
            var bytes          = MachineKey.Unprotect(encryptedBytes);
#else
            var bytes = MachineKey.Decode(encrypted, MachineKeyProtection.Encryption);
#endif
            if (bytes == null)
            {
                throw new InvalidOperationException("Data cannot be decrypted using Machine Key");
            }

            var value = Encoding.Unicode.GetString(bytes);
            return(value);
        }
コード例 #23
0
ファイル: SingleSignOn.cs プロジェクト: sponnusa/Master
 public string decodeSSOToken(string ssoToken)
 {
     if (ssoToken.isNull())
     {
         return(null);
     }
     try
     {
         return(MachineKey.Decode(ssoToken, MachineKeyProtection.All).ascii());
     }
     catch (Exception ex)
     {
         ex.log();
         return(null);
     }
 }
コード例 #24
0
        public List <FlashMessageModel> GetQueued()
        {
            // Attempt to retrieve cookie.
            var context = new HttpContextWrapper(HttpContext.Current);
            var cookie  = context.Response.Cookies[CookieName];

            // If the cookie is non existent, return an empty message list.
            // If the cookie value is null, also return an empty list, as MachineKey.Decode does not like empty strings.
            if (cookie == null || string.IsNullOrEmpty(cookie.Value))
            {
                return(new List <FlashMessageModel>());
            }

            // Decode and deserialize the data.
            var serializedMessages = MachineKey.Decode(cookie.Value, MachineKeyProtection.All);

            return(FlashMessage.Deserialize(serializedMessages));
        }
コード例 #25
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request.QueryString.ToString()))
            {
                if (Request.QueryString["QID"] != null)
                {
                    var decryptedBytes = MachineKey.Decode(Request.QueryString["QID"], MachineKeyProtection.All);
                    var decryptedValue = Encoding.UTF8.GetString(decryptedBytes);
                    int QouID          = Convert.ToInt32(decryptedValue);
                    ViewState["_QuotationID"] = QouID;
                }
                else if (Request.QueryString["FID"] != null)
                {
                    var decryptedBytes = MachineKey.Decode(Request.QueryString["FID"], MachineKeyProtection.All);
                    var decryptedValue = Encoding.UTF8.GetString(decryptedBytes);
                    int FID            = Convert.ToInt32(decryptedValue);
                    ViewState["_FID"] = FID;
                }
                else if (Request.QueryString["TBID"] != null)
                {
                    var decryptedBytes = MachineKey.Decode(Request.QueryString["TBID"], MachineKeyProtection.All);
                    var decryptedValue = Encoding.UTF8.GetString(decryptedBytes);
                    int TBID           = Convert.ToInt32(decryptedValue);
                    ViewState["_TBID"] = TBID;
                }
            }

            else
            {
                Response.Redirect("~/Admin/Dashboard.aspx");
            }
            if (!IsPostBack)
            {
                lblSubtotal.Visible = false;
                getServiceData();
                BindCompany();
                BindCustomerDetails();
                TotalCal();
            }
        }
コード例 #26
0
        private string UnEncodePassword(string encodedPassword)
        {
            string password = encodedPassword;

            switch (PasswordFormat)
            {
            case MembershipPasswordFormat.Clear:
                break;

            case MembershipPasswordFormat.Encrypted:
                password = Encoding.Unicode.GetString(DecryptPassword(Convert.FromBase64String(password)));
                break;

            case MembershipPasswordFormat.Hashed:
                password = Encoding.Unicode.GetString(MachineKey.Decode(encodedPassword, MachineKeyProtection.Validation));
                break;

            default:
                throw new ProviderException("Unsupported password format.");
            }

            return(password);
        }
コード例 #27
0
        public List <FlashMessageModel> Retrieve()
        {
            // Attempt to retrieve cookie. If the cookie is non existent, return an empty message list.
            var context = new HttpContextWrapper(HttpContext.Current);
            var cookie  = context.Request.Cookies[CookieName];

            if (cookie == null)
            {
                return(new List <FlashMessageModel>());
            }

            var data = cookie.Value;

            // Clear the cookie by setting it to expired.
            cookie.Value   = null;
            cookie.Expires = DateTime.Now.AddDays(-1);
            context.Response.SetCookie(cookie);

            // Decode and deserialize the data.
            var serializedMessages = MachineKey.Decode(data, MachineKeyProtection.All);

            return(FlashMessage.Deserialize(serializedMessages));
        }
コード例 #28
0
ファイル: DocKey.cs プロジェクト: superbee66/dcForm
 public static Dictionary <string, string> DocIdToKeys(string DocId) =>
 string.IsNullOrWhiteSpace(DocId)
         ? new Dictionary <string, string>()
         : JsonConvert.DeserializeObject <Dictionary <string, string> >(
     Encoding.UTF8.GetString(
         MachineKey.Decode(DocId, MachineKeyProtection.Encryption)));
コード例 #29
0
        public void Decode()
        {
            byte[] decoded;

            AssertExtensions.Throws <ArgumentNullException> (() => {
                MachineKey.Decode(null, MachineKeyProtection.All);
            }, "#A1-1");

            AssertExtensions.Throws <ArgumentException> (() => {
                decoded = MachineKey.Decode(String.Empty, MachineKeyProtection.All);
            }, "#A1-2");

            var sb = new StringBuilder().Append('0', 192);

            decoded = MachineKey.Decode(sb.ToString(), (MachineKeyProtection)12345);
            Assert.IsNotNull(decoded, "#A2-1");
            Assert.AreEqual(96, decoded.Length, "#A2-2");

            sb      = new StringBuilder().Append('0', 128);
            decoded = MachineKey.Decode(sb.ToString(), (MachineKeyProtection)12345);
            Assert.IsNotNull(decoded, "#A3-1");
            Assert.AreEqual(64, decoded.Length, "#A3-2");

            sb      = new StringBuilder().Append('0', 96);
            decoded = MachineKey.Decode(sb.ToString(), (MachineKeyProtection)12345);
            Assert.IsNotNull(decoded, "#A4-1");
            Assert.AreEqual(48, decoded.Length, "#A4-2");

            sb      = new StringBuilder().Append('0', 10);
            decoded = MachineKey.Decode(sb.ToString(), (MachineKeyProtection)12345);
            Assert.IsNotNull(decoded, "#A5-1");
            Assert.AreEqual(5, decoded.Length, "#A5-2");

            AssertExtensions.Throws <ArgumentException> (() => {
                decoded = MachineKey.Decode("test", MachineKeyProtection.All);
            }, "#B1-1");

            AssertExtensions.Throws <ArgumentException> (() => {
                decoded = MachineKey.Decode("test", MachineKeyProtection.Encryption);
            }, "#B1-2");

            AssertExtensions.Throws <ArgumentException> (() => {
                decoded = MachineKey.Decode("test", MachineKeyProtection.Validation);
            }, "#B1-3");

            sb = new StringBuilder().Append('0', 1);
            try {
                decoded = MachineKey.Decode(sb.ToString(), MachineKeyProtection.All);
                Assert.Fail("#C1-2 [no exception]");
            } catch (ArgumentException) {
                // success
            } catch {
                Assert.Fail("#C1-2 [invalid exception]");
            }

            sb = new StringBuilder().Append('0', 2);
            try {
                decoded = MachineKey.Decode(sb.ToString(), MachineKeyProtection.All);
            } catch (ArgumentException ex) {
                Console.WriteLine(ex);
                Assert.Fail("#C1-3");
            } catch {
                // success
            }

            sb = new StringBuilder().Append('0', 193);
            try {
                decoded = MachineKey.Decode(sb.ToString(), MachineKeyProtection.All);
                Assert.Fail("#C2-1 [no exception]");
            } catch (ArgumentException) {
                // success
            } catch {
                Assert.Fail("#C2-1 [invalid exception]");
            }

            sb = new StringBuilder().Append('0', 129);
            try {
                decoded = MachineKey.Decode(sb.ToString(), MachineKeyProtection.All);
                Assert.Fail("#C3-1 [no exception]");
            } catch (ArgumentException) {
                // success
            } catch {
                Assert.Fail("#C3-2 [invalid exception]");
            }

            sb = new StringBuilder().Append('0', 64);
            try {
                decoded = MachineKey.Decode(sb.ToString(), MachineKeyProtection.All);
            } catch (ArgumentException) {
                Assert.Fail("#C4-1");
            } catch {
                // Success
            }
        }
コード例 #30
0
 public virtual byte[] Unprotect(byte[] protectedData)
 {
     return(MachineKey.Decode(Encoding.UTF8.GetString(protectedData), MachineKeyProtection.All));
 }