コード例 #1
0
        public static string Encrypt(string value)
        {
            var bytes     = Encoding.Unicode.GetBytes(value);
            var encrypted = MachineKey.Encode(bytes, MachineKeyProtection.Encryption);

            return(encrypted);
        }
コード例 #2
0
        public string EncryptDealerId(string DealerId)
        {
            var plaintextBytes = Encoding.UTF8.GetBytes(DealerId);
            var v2             = MachineKey.Encode(plaintextBytes, MachineKeyProtection.All);

            return(v2);
        }
コード例 #3
0
ファイル: MachineKeyUtil.cs プロジェクト: terry2012/DSV
            /// <summary>
            /// Protects the specified user data.
            /// </summary>
            /// <param name="userData">The user data.</param>
            /// <param name="purposes">The purposes.</param>
            /// <returns>The protected data</returns>
            public byte[] Protect(byte[] userData, string[] purposes)
            {
                if (userData == null)
                {
                    throw new ArgumentNullException("userData");
                }

                // dataWithHeader = {magic header} .. {purposes} .. {userData}
                byte[] dataWithHeader = new byte[checked (4 /* magic header */ + (256 / 8) /* purposes */ + userData.Length)];
                unchecked {
                    dataWithHeader[0] = (byte)(MagicHeader >> 24);
                    dataWithHeader[1] = (byte)(MagicHeader >> 16);
                    dataWithHeader[2] = (byte)(MagicHeader >> 8);
                    dataWithHeader[3] = (byte)MagicHeader;
                }
                byte[] purposeHash = ComputeSHA256(purposes);
                Buffer.BlockCopy(purposeHash, 0, dataWithHeader, 4, purposeHash.Length);
                Buffer.BlockCopy(userData, 0, dataWithHeader, 4 + (256 / 8), userData.Length);

                // encrypt + sign
                string hexValue = MachineKey.Encode(dataWithHeader, MachineKeyProtection.All);

                // convert hex -> binary
                byte[] binary = HexToBinary(hexValue);
                return(binary);
            }
コード例 #4
0
        public string Encode(byte[] bytes)
        {
#pragma warning disable 618
            return(HexToBase64(MachineKey.Encode(bytes, MachineKeyProtection.All).ToUpperInvariant()));

#pragma warning restore 618
        }
コード例 #5
0
        public static HttpCookie Encrypt(HttpCookie httpCookie)
        {
            byte[] buffer = Encoding.Default.GetBytes(httpCookie.Value);
            httpCookie.Value = (string)MachineKey.Encode(buffer, MachineKeyProtection.All);

            return(httpCookie);
        }
コード例 #6
0
        /// <summary>
        /// Hash a string using the machine key as a salt.
        /// </summary>
        /// <returns>A guid that is tied to the value and machine key.</returns>
        public static Guid Hash(string value)
        {
            Byte[] byteArray = Encoding.Unicode.GetBytes(value);
            string hash      = MachineKey.Encode(byteArray, MachineKeyProtection.Validation);

            return(Create(IsoOidNamespace, hash));
        }
コード例 #7
0
        public void Save(byte[] data)
        {
            var str = MachineKey.Encode(data, MachineKeyProtection.All);

            data = System.Text.Encoding.UTF8.GetBytes(str);
            inner.Save(data);
        }
コード例 #8
0
        public void Encode()
        {
#if DOT_NET
            const int ALL_EXPECTED_SIZE        = 192;
            const int ENCRYPTION_EXPECTED_SIZE = 128;
#else
            const int ALL_EXPECTED_SIZE        = 128;
            const int ENCRYPTION_EXPECTED_SIZE = 64;
#endif
            const int VALIDATION_EXPECTED_SIZE = 64;

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

            string result = MachineKey.Encode(new byte[] {}, (MachineKeyProtection)12345);
            Assert.IsNotNull(result, "#A1-1");
            Assert.AreEqual(0, result.Length, "#A1-2");

            result = MachineKey.Encode(new byte[] {}, MachineKeyProtection.All);
            Assert.IsNotNull(result, "#B1-1");
            Assert.AreEqual(ALL_EXPECTED_SIZE, result.Length, "#B1-2");

            result = MachineKey.Encode(new byte [] { }, MachineKeyProtection.Encryption);
            Assert.IsNotNull(result, "#C1-1");
            Assert.AreEqual(ENCRYPTION_EXPECTED_SIZE, result.Length, "#C1-2");

            result = MachineKey.Encode(new byte [] { }, MachineKeyProtection.Validation);
            Assert.IsNotNull(result, "#D1-1");
            Assert.AreEqual(VALIDATION_EXPECTED_SIZE, result.Length, "#D1-2");
        }
コード例 #9
0
        /// <summary>
        /// Override default provider creation by using custom options
        /// </summary>
        /// <param name="sectionName"></param>
        /// <param name="configData"></param>
        /// <returns></returns>
        protected override IConfigurationProvider OnCreateDefaultProvider(string sectionName, object configData)
        {
            var provider = new ConfigurationFileConfigurationProvider <ApplicationConfiguration>()
            {
                // use the machine key to seed encoding key string or provide any other string
                EncryptionKey = MachineKey.Encode(new byte[] { 3, 233, 8, 11, 32, 44 },
                                                  MachineKeyProtection.Encryption),
                PropertiesToEncrypt = "MailServerPassword,ConnectionString",
                // Custom section - if not specified goes to AppSettings
                ConfigurationSection = "ApplicationConfiguration"
            };

            return(provider);

            // Example of Sql configuration
            //var provider = new SqlServerConfigurationProvider<ApplicationConfiguration>()
            //{
            //    FieldsToEncrypt = "MailServerPassword,ConnectionString",
            //    EncryptKey = "secret",
            //    ConnectionString = "DevSampleConnectionString",
            //    Tablename = "Configuration",
            //    Key = 1
            //};
            // Example of external XML configuration - advantage: Supports complex object hierarchies
            //var provider = new XmlFileConfigurationProvider<ApplicationConfiguration>()
            //{
            //    FieldsToEncrypt = "MailServerPassword,ConnectionString",
            //    EncryptKey = "secret",
            //    XmlConfigurationFile = HttpContext.Current.Server.MapPath("~/Configuration.xml")
            //};
        }
コード例 #10
0
ファイル: DocKey.cs プロジェクト: superbee66/dcForm
 /// <summary>
 /// </summary>
 /// <param name="DocKeys"></param>
 /// <param name="ClearText">don't Rijndael encrypt</param>
 /// <returns>A jsoned & modified base64 string suitable for parameter UrlEncoding</returns>
 public static string DocIdFromKeys(Dictionary <string, string> DocKeys, bool ClearText = false) =>
 ClearText
         ? JsonConvert.SerializeObject(DocKeys)
         : MachineKey.Encode(
     Encoding.UTF8.GetBytes(
         JsonConvert.SerializeObject(DocKeys)),
     MachineKeyProtection.Encryption);
コード例 #11
0
    private static string Proteccion(string tokenid)
    {
        var ByteSinProteccion = Encoding.ASCII.GetBytes(tokenid);
        var ByteConProteccion = MachineKey.Encode(ByteSinProteccion, MachineKeyProtection.All);


        return(ByteConProteccion);
    }
コード例 #12
0
        protected void btnPrint_Click(object sender, EventArgs e)
        {
            string id             = TBID.ToString();
            var    plaintextBytes = Encoding.UTF8.GetBytes(id);
            var    encryptedValue = MachineKey.Encode(plaintextBytes, MachineKeyProtection.All);

            Response.Redirect("~/Admin/PrintForm.aspx?TBID=" + encryptedValue);
        }
コード例 #13
0
        private static string Encode(byte[] data)
        {
#if GTNet40
            return(Convert.ToBase64String(MachineKey.Protect(data)));
#else
            return(MachineKey.Encode(data, MachineKeyProtection.Encryption));
#endif
        }
コード例 #14
0
        protected void btnServiceClick(object sender, EventArgs e)
        {
            string id             = FID.ToString();
            var    plaintextBytes = Encoding.UTF8.GetBytes(id);
            var    encryptedValue = MachineKey.Encode(plaintextBytes, MachineKeyProtection.All);

            Response.Redirect("~/Admin/FuneralServicesSelect.aspx?ID=" + encryptedValue);
        }
コード例 #15
0
 public override byte[] Encode(byte[] value)
 {
     if (value == null)
     {
         throw new ArgumentNullException("value");
     }
     return(Encoding.UTF8.GetBytes(MachineKey.Encode(value, MachineKeyProtection.All)));
 }
コード例 #16
0
        /// <summary>
        /// Create a hmac from the given data
        /// </summary>
        /// <param name="data">Data to create hmac from</param>
        /// <returns>Hmac bytes</returns>
        public byte[] GenerateHmac(byte[] data)
        {
            var encoded = MachineKey.Encode(data, MachineKeyProtection.Validation);

            var bytes = HexStringToByteArray(encoded);

            return(bytes.Skip(bytes.Length - HmacLength).ToArray());
        }
コード例 #17
0
        public void MachineKeyEncryptionTest2()
        {
            const string originalText = "Some text to encrypt";
            // ReSharper disable once CSharpWarnings::CS0618
            var data      = MachineKey.Encode(Encoding.UTF8.GetBytes(originalText), MachineKeyProtection.All);
            var decrypted = MachineKeyEncryption.Decode(data);

            Assert.AreEqual(originalText, decrypted);
        }
コード例 #18
0
        public void PrintQuotation()
        {
            string id             = FID.ToString();
            var    plaintextBytes = Encoding.UTF8.GetBytes(id);
            var    encryptedValue = MachineKey.Encode(plaintextBytes, MachineKeyProtection.All);

            //Response.Redirect("Default2.aspx?name=" + encryptedValue);
            Response.Redirect("~/Admin/PrintForm.aspx?FID=" + encryptedValue);
        }
コード例 #19
0
        private static string Protect(byte[] data)
        {
            if (data == null || data.Length == 0)
            {
                return(null);
            }

            return(MachineKey.Encode(data, MachineKeyProtection.All));
        }
コード例 #20
0
        //public void GetQuotationNumber()
        //{
        //    QuotationModel obj = client.GetQuotationNumberByID2(ParlourId);
        //    if (obj.QuotationNumber2 == string.Empty || obj.QuotationNumber2 == "")
        //    {
        //        ViewState["QuotationNumber2"] = "0001";
        //    }
        //    else
        //    {
        //    string s = obj.QuotationNumber2;
        //    s = (Int32.Parse(s) + 1).ToString("D4");
        //    ViewState["QuotationNumber2"]= s;
        //    }

        //}
        public void QuotationServicePage(int?QutID)
        {
            string id             = QutID.ToString();
            var    plaintextBytes = Encoding.UTF8.GetBytes(id);
            var    encryptedValue = MachineKey.Encode(plaintextBytes, MachineKeyProtection.All);

            //Response.Redirect("Default2.aspx?name=" + encryptedValue);
            Response.Redirect("~/Admin/QuotationServices.aspx?ID=" + encryptedValue);
        }
コード例 #21
0
        public virtual byte[] Protect(byte[] userData)
        {
#if NET40
            // THIS SHOULD BE FIXED TO ADD PURPOSES BYTES
            return(Encoding.UTF8.GetBytes(MachineKey.Encode(userData, MachineKeyProtection.All)));
#endif
#if NET45
            return(MachineKey.Protect(userData, _purposes));
#endif
        }
コード例 #22
0
ファイル: SecurityUtil.cs プロジェクト: INGEPEREZ1091/Report
        public static string Encrypt(string value)
        {
            var bytes = Encoding.Unicode.GetBytes(value);

#if NET45
            var encryptedBytes = MachineKey.Protect(bytes);
            var encrypted      = BitConverter.ToString(encryptedBytes).Replace("-", "");
#else
            var encrypted = MachineKey.Encode(bytes, MachineKeyProtection.Encryption);
#endif
            return(encrypted);
        }
        byte[] TokenToBytes(SessionSecurityToken token)
        {
            if (token == null)
            {
                return(null);
            }

            var bytes = serializer.Serialize(token);
            var str   = MachineKey.Encode(bytes, MachineKeyProtection.All);

            return(System.Text.Encoding.UTF8.GetBytes(str));
        }
コード例 #24
0
        /// <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));
        }
コード例 #25
0
ファイル: SingleSignOn.cs プロジェクト: sponnusa/Master
 public string getSSOTokenForUser(TMUser tmUser)
 {
     if (tmUser.isNull())
     {
         return(null);
     }
     if (tmUser.SSOKey.isGuid().isFalse())
     {
         tmUser.SSOKey = Guid.NewGuid().str();
     }
     TM_Xml_Database.Current.saveTmUserDataToDisk();
     return(MachineKey.Encode(tmUser.serialize(false).asciiBytes(), MachineKeyProtection.All));
 }
コード例 #26
0
 public static string ProtectData(string providerName, string providerUserId)
 {
     using (MemoryStream ms = new MemoryStream())
         using (BinaryWriter bw = new BinaryWriter(ms))
         {
             bw.Write(providerName);
             bw.Write(providerUserId);
             bw.Flush();
             byte[] serializedWithPadding = new byte[ms.Length + _padding.Length];
             Buffer.BlockCopy(_padding, 0, serializedWithPadding, 0, _padding.Length);
             Buffer.BlockCopy(ms.GetBuffer(), 0, serializedWithPadding, _padding.Length, (int)ms.Length);
             return(MachineKey.Encode(serializedWithPadding, MachineKeyProtection.All));
         }
 }
コード例 #27
0
            public string Protect(byte[] data)
            {
                byte[] dataWithHeader = new byte[data.Length + 4];
                Buffer.BlockCopy(data, 0, dataWithHeader, 4, data.Length);
                unchecked
                {
                    dataWithHeader[0] = (byte)(_magicHeader >> 24);
                    dataWithHeader[1] = (byte)(_magicHeader >> 16);
                    dataWithHeader[2] = (byte)(_magicHeader >> 8);
                    dataWithHeader[3] = (byte)(_magicHeader);
                }

                string hex = MachineKey.Encode(dataWithHeader, MachineKeyProtection.All);

                return(HexToBase64(hex));
            }
コード例 #28
0
        /// <summary>
        /// Generates a hidden input type string for the given value after hashing the value.
        /// The field for ex. CustomerId would be named _CustomerIdToken
        /// </summary>
        /// <param name="fieldName"></param>
        /// <param name="modelValue"></param>
        /// <returns></returns>
        private static MvcHtmlString GenerateHiddenFormField(string fieldName, object modelValue)
        {
            TagBuilder builder = new TagBuilder("input");

            builder.Attributes["type"] = "hidden";
            //If we have a field named CustomerId, then the token will be _CustomerIdToken
            builder.Attributes["name"] = string.Format("_{0}Token", fieldName);

            string value = GetValueFromModelValue(modelValue);

            //Now use the machine key to encrypt the value (ya, its called encode)
            value = MachineKey.Encode(Encoding.Unicode.GetBytes(value), MachineKeyProtection.Encryption);

            builder.Attributes["value"] = value.ToString();
            return(new MvcHtmlString(builder.ToString(TagRenderMode.SelfClosing)));
        }
コード例 #29
0
        public string ComputeHash()
        {
            // get the sorted cookie values
            Dictionary <string, string> sortedData = _values.ToDictionary();

            // create a salt
            byte[] data = Encoding.UTF8.GetBytes(sortedData.Values.Join("-"));
            string salt = MachineKey.Encode(data, MachineKeyProtection.Encryption);

            sortedData.Add("salt", salt);

            // compute the hash
            HMACSHA1 hmacsha1 = new HMACSHA1();
            string   hash     = hmacsha1.ComputeHash(sortedData);

            return(hash);
        }
コード例 #30
0
        public void Queue(IList <FlashMessageModel> messages)
        {
            // Serialize and digitally sign the data.
            // Encoding/signing is done using the configured encryption and key in the machineKey element.
            // TODO: Replace with MachineKey.Protect for .Net Framework >= 4.5
            var serializedMessages = FlashMessage.Serialize(messages);
            var data = MachineKey.Encode(serializedMessages, MachineKeyProtection.All);

            // Serialize messages and enforce cookie size limit.
            if (data.Length > CookieSizeLimit && CookieSizeLimit > 0)
            {
                throw new InvalidOperationException("The flash messages cookie size limit exceeded the limit value. Queue less messages.");
            }

            // Set the cookie.
            var context = new HttpContextWrapper(HttpContext.Current);
            var cookie  = new HttpCookie(CookieName, data);

            context.Response.SetCookie(cookie);
        }