Beispiel #1
0
            /// <summary>
            ///     Generates the specified strength in bits.
            /// </summary>
            /// <param name="strengthInBits">The strength in bits.</param>
            /// <returns></returns>
            /// <exception cref="System.ArgumentException">strengthInBits must be evenly divisible by 8.;strengthInBits</exception>
            public static string Generate(int strengthInBits)
            {
                const int bitsPerByte = 8;

                if (strengthInBits % bitsPerByte != 0)
                {
                    throw new ArgumentException("strengthInBits must be evenly divisible by 8.", "strengthInBits");
                }

                var strengthInBytes = strengthInBits / bitsPerByte;

                var data = new byte[strengthInBytes];

                Random.GetBytes(data);
                return(HttpServerUtility.UrlTokenEncode(data));
            }
Beispiel #2
0
        private static string GetFileSHA1(string filePath)
        {
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 120000))
            {
#if ASPNETCORE
                var    md5  = MD5.Create();
                byte[] hash = md5.ComputeHash(fs);
                return(WebEncoders.Base64UrlEncode(hash));
#else
                using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
                {
                    byte[] hash = md5.ComputeHash(fs);
                    return(HttpServerUtility.UrlTokenEncode(hash));
                }
#endif
            }
        }
        internal static string GetFullFileName(string path, string contentType)
        {
            var href = Path.GetFileNameWithoutExtension(path);
            var category = GetCategoryFromPath(path);

            var hrefTokenSource = href;

            if (Uri.IsWellFormedUriString(href, UriKind.Relative))
                hrefTokenSource = (SecureHelper.IsSecure() ? "https" : "http") + href;

            var hrefToken = string.Concat(HttpServerUtility.UrlTokenEncode(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(hrefTokenSource))));

            if (string.Compare(contentType, "text/css", StringComparison.OrdinalIgnoreCase) == 0)
                return string.Format("/{0}/css/{1}.css", category, hrefToken);

            return string.Format("/{0}/javascript/{1}.js", category, hrefToken);
        }
Beispiel #4
0
        protected virtual string GetBundleVirtualPath(BundleType type, IEnumerable <string> files)
        {
            if (files == null || !files.Any())
            {
                throw new ArgumentException("parts");
            }

            string prefix  = "~/bundles/js/";
            string postfix = ".js";

            if (type == BundleType.Stylesheet)
            {
                prefix  = "~/bundles/css/";
                postfix = ".css";
            }

            // TBD: routing fix
            postfix = "";

            // compute hash
            var hash = "";

            using (SHA256 sha = new SHA256Managed())
            {
                var hashInput = "";
                foreach (var file in files)
                {
                    hashInput += file;
                    hashInput += ",";
                }

                byte[] input = sha.ComputeHash(Encoding.Unicode.GetBytes(hashInput));
                hash = HttpServerUtility.UrlTokenEncode(input);

                // append StoreId & ThemeName to hash in order to vary cache by store/theme combination
                if (type == BundleType.Stylesheet && !_workContext.IsAdmin && files.Any(x => x.EndsWith(".scss", StringComparison.OrdinalIgnoreCase)))
                {
                    hash += "-s" + _storeContext.CurrentStore.Id;
                    hash += "-t" + _themeContext.CurrentTheme.ThemeName;
                }
            }

            // ensure only valid chars
            hash = SeoExtensions.GetSeName(hash);
            return(prefix + hash + postfix);
        }
        /// <summary>
        /// Name: CreateResetPasswordLink
        /// Description: Method to create reset password link
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        private string CreateResetPasswordLink(string email)
        {
            // Get front end URL
            string frontEndURL        = ConfigurationManager.AppSettings["JSPOT::FrontEndURL"];
            string frontEndController = ConfigurationManager.AppSettings["JSPOT::FrontEndRecoverController"];
            // Get current date time
            DateTime currentTime = DateTime.Now.ToUniversalTime();
            // Conver the email and user to json object
            object parameter    = new { Email = email, CreationDate = currentTime };
            string strParameter = JsonConvert.SerializeObject(parameter);
            // Encrypt the json string
            string encryptedParameter = Crypto.AES.Encrypt(strParameter);
            string safeUrl            = HttpServerUtility.UrlTokenEncode(Encoding.UTF8.GetBytes(encryptedParameter));

            // return the string
            return(string.Format("{0}/{1}/{2}", frontEndURL, frontEndController, safeUrl));
        }
        public static string ResolveHandlerPath(ICollection <Type> types)
        {
            var tenant       = ASC.Core.CoreContext.TenantManager.GetCurrentTenant();
            var version      = "";
            var resultPath   = "";
            var listHandlers = new List <ClientScript>();

            foreach (var type in types)
            {
                if (!typeof(ClientScript).IsAssignableFrom(type))
                {
                    throw new ArgumentException(string.Format("{0} is not assignable to ClientScriptHandler", type));
                }
                var instance = (ClientScript)Activator.CreateInstance(type);
                version   += instance.GetCacheHash();
                resultPath = resultPath + type.FullName.ToLowerInvariant().Replace('.', '_');

                listHandlers.Add(instance);
            }

            resultPath = HttpServerUtility.UrlTokenEncode(MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(resultPath)));

            if (!Hash.ContainsKey(resultPath))
            {
                Hash[resultPath] = new ClientScriptHandler {
                    ClientScriptHandlers = listHandlers
                };
            }

            if (tenant != null && types.All(r => r.BaseType != typeof(ClientScriptLocalization)))
            {
                version = String.Join("_",
                                      new[]
                {
                    tenant.TenantId.ToString(CultureInfo.InvariantCulture),
                    tenant.Version.ToString(CultureInfo.InvariantCulture),
                    tenant.LastModified.Ticks.ToString(CultureInfo.InvariantCulture),
                    version
                });
            }

            var versionHash = HttpServerUtility.UrlTokenEncode(MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(version)));

            return(new Uri(VirtualPathUtility.ToAbsolute("~/clientscriptbundle/" + versionHash + "/" + resultPath + ClientSettings.ClientScriptExtension),
                           UriKind.Relative).ToString());
        }
Beispiel #7
0
 static IEnumerable <(string fileName, string hash)> GetHasList(string path, bool isRelative)
 {
     foreach (var file in Directory.GetFiles(path, "*.*", SearchOption.AllDirectories))
     {
         string hash;
         using (var md5 = MD5.Create())
             using (var stream = File.OpenRead(file))
                 hash = HttpServerUtility.UrlTokenEncode(md5.ComputeHash(stream));
         if (isRelative)
         {
             yield return(file.Remove(0, path.TrimEnd('/').Length + 1), hash);
         }
         else
         {
             yield return(file, hash);
         }
     }
 }
Beispiel #8
0
        /// <summary>
        /// 创建一个字符串,其中包含适用于 HTTP Cookie 的加密的 Forms 身份验证票证。
        /// </summary>
        /// <param name="ticket">用于创建加密的 Forms 身份验证票证的 System.Web.Security.FormsAuthenticationTicket 对象。</param>
        /// <returns>一个字符串,其中包含加密的 Forms 身份验证票证。</returns>
        public static string Encrypt(FormsAuthenticationTicket ticket)
        {
            if (ticket == null)
            {
                throw new ArgumentNullException("ticket");
            }

            try
            {
                var bytes = Serializer.Serialize(ticket);
                var data  = AES.Encrypt(bytes, AES_PASSWORD, AES_KEY);
                return(HttpServerUtility.UrlTokenEncode(data));
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Beispiel #9
0
        public ActionResult Create(FormCollection collection)
        {
            var serviceNamespace = collection["Namespace"];
            var servicePath      = collection["Path"];
            var keyName          = collection["KeyName"];
            var key        = collection["Key"];
            var expiration = collection["Expiration"];

            var parsedExpiration = DateTime.Parse(expiration);
            var ttl = parsedExpiration.Subtract(DateTime.UtcNow);

            var resource = ServiceBusEnvironment.CreateServiceUri("https", serviceNamespace, servicePath).ToString().Trim('/');
            var sasToken = SharedAccessSignatureTokenProvider.GetSharedAccessSignature(keyName, key, resource, ttl);

            var encodedToken = HttpServerUtility.UrlTokenEncode(Encoding.ASCII.GetBytes(sasToken));

            return(RedirectToAction("DisplaySas", new { id = encodedToken }));
        }
Beispiel #10
0
        /// <summary>
        /// Stores the request token together with its secret.
        /// </summary>
        /// <param name="requestToken">The request token.</param>
        /// <param name="requestTokenSecret">The request token secret.</param>
        public void StoreRequestToken(string requestToken, string requestTokenSecret)
        {
            var cookie = new HttpCookie(TokenCookieKey)
            {
                HttpOnly = true
            };

            if (FormsAuthentication.RequireSSL)
            {
                cookie.Secure = true;
            }

            byte[] cookieBytes = Encoding.UTF8.GetBytes(requestTokenSecret);
            var    secretBytes = MachineKeyUtil.Protect(cookieBytes, TokenCookieKey, "Token:" + requestToken);

            cookie.Values[requestToken] = HttpServerUtility.UrlTokenEncode(secretBytes);
            this.Context.Response.Cookies.Set(cookie);
        }
Beispiel #11
0
        private static string AddDirectRef(string directRef)
        {
            var rng  = new RNGCryptoServiceProvider();
            var buff = new byte[32];

            rng.GetBytes(buff);

            var indirectRef = HttpServerUtility.UrlTokenEncode(buff);

            var map = new Dictionary <string, string>
            {
                { directRef, indirectRef },
                { indirectRef, directRef }
            };

            HttpContext.Current.Session["Map"] = map;
            return(indirectRef);
        }
    public static string Encrypt(string toEncrypt, string key)
    {
        var des = new DESCryptoServiceProvider();
        var ms  = new MemoryStream();

        VerifyKey(ref key);

        des.Key = HashKey(key, des.KeySize / 8);
        des.IV  = HashKey(key, des.KeySize / 8);
        byte[] inputBytes = Encoding.UTF8.GetBytes(toEncrypt);

        var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);

        cs.Write(inputBytes, 0, inputBytes.Length);
        cs.FlushFinalBlock();

        return(HttpServerUtility.UrlTokenEncode(ms.ToArray()));
    }
Beispiel #13
0
        /// <summary>
        /// Encode an item to be stored in a url.
        /// </summary>
        /// <typeparam name="T">The item type.</typeparam>
        /// <param name="item">The item instance.</param>
        /// <returns>The encoded token.</returns>
        public static string Encode <T>(T item)
        {
            using (var memory = new MemoryStream())
            {
                using (var gzip = new GZipStream(memory, CompressionMode.Compress))
                    using (var writer = new BsonDataWriter(gzip))
                    {
                        var serializer = JsonSerializer.CreateDefault();
                        serializer.Serialize(writer, item);
                    }
#if NET46
                var token = HttpServerUtility.UrlTokenEncode(memory.ToArray());
#else
                var token = WebEncoders.Base64UrlEncode(memory.GetBuffer(), 0, (int)memory.Length);
#endif
                return(token);
            }
        }
Beispiel #14
0
        public ActionResult Index()
        {
            byte[] sd = System.Text.Encoding.Default.GetBytes("a");
            sd = MachineKey.Protect(sd, _purposes);

            ViewBag.securet = HttpServerUtility.UrlTokenEncode(sd);

            byte[] rawProtectedBytes = HttpServerUtility.UrlTokenDecode("DgDfVEwUNeB-oQLsjtv9s2zMfDZv_ytAEQE0okbmQ5UwztkxmprpR1l1anBZw3cNAVRP7g2");
            try
            {
                byte[] ff = MachineKey.Unprotect(rawProtectedBytes, _purposes);
                ViewBag.result = System.Text.Encoding.Default.GetString(ff);
            }
            catch (Exception e) {
                ViewBag.result = "error " + e.Message;
            }

            return(View());
        }
Beispiel #15
0
        /// <summary>
        /// Requests the specified provider to start the authentication by directing users to an external website
        /// </summary>
        /// <param name="returnUrl">
        /// The return url after user is authenticated.
        /// </param>
        public void RequestAuthentication(string returnUrl)
        {
            // convert returnUrl to an absolute path
            Uri uri;

            if (!string.IsNullOrEmpty(returnUrl))
            {
                uri = UriHelper.ConvertToAbsoluteUri(returnUrl, this.requestContext);
            }
            else
            {
                uri = this.requestContext.Request.GetPublicFacingUrl();
            }

            // attach the provider parameter so that we know which provider initiated
            // the login when user is redirected back to this page
            uri = uri.AttachQueryStringParameter(ProviderQueryStringName, this.authenticationProvider.ProviderName);

            // Guard against XSRF attack by injecting session id into the redirect url and response cookie.
            // Upon returning from the external provider, we'll compare the session id value in the query
            // string and the cookie. If they don't match, we'll reject the request.n
            string sessionId = Guid.NewGuid().ToString("N");

            uri = uri.AttachQueryStringParameter(SessionIdQueryStringName, sessionId);

            // The cookie value will be the current username secured against the session id we just created.
            byte[] encryptedCookieBytes = MachineKeyUtil.Protect(Encoding.UTF8.GetBytes(GetUsername(this.requestContext)), AntiXsrfPurposeString, "Token: " + sessionId);

            var xsrfCookie = new HttpCookie(SessionIdCookieName, HttpServerUtility.UrlTokenEncode(encryptedCookieBytes))
            {
                HttpOnly = true
            };

            if (FormsAuthentication.RequireSSL)
            {
                xsrfCookie.Secure = true;
            }
            this.requestContext.Response.Cookies.Add(xsrfCookie);

            // issue the redirect to the external auth provider
            this.authenticationProvider.RequestAuthentication(this.requestContext, uri);
        }
Beispiel #16
0
        /// <summary>
        /// Encripta o dado solicitado.
        /// </summary>
        /// <param name="plainText">Texto a ser criptografado.</param>
        /// <returns>Texto criptografado no formato BASE64.</returns>
        public virtual string Encrypt(string texto)
        {
            byte[] plainByte = Encoding.UTF8.GetBytes(texto);
            byte[] keyByte   = GetKey();
            // Seta a chave privada
            _algorithm.Key = keyByte;
            SetIV();
            // Interface de criptografia / Cria objeto de criptografia
            ICryptoTransform cryptoTransform = _algorithm.CreateEncryptor();
            MemoryStream     _memoryStream   = new MemoryStream();
            CryptoStream     _cryptoStream   = new CryptoStream(_memoryStream, cryptoTransform, CryptoStreamMode.Write);

            // Grava os dados criptografados no MemoryStream
            _cryptoStream.Write(plainByte, 0, plainByte.Length);
            _cryptoStream.FlushFinalBlock();
            // Busca o tamanho dos bytes encriptados
            byte[] cryptoByte = _memoryStream.ToArray();
            // Converte para a base 64 string para uso posterior em um xml
            return(HttpServerUtility.UrlTokenEncode(cryptoByte));
            //return Convert.ToBase64String(cryptoByte, 0, cryptoByte.GetLength(0));
        }
Beispiel #17
0
        public static String ListDictionaryToString(Dictionary <string, string> dictionary)
        {
            var binFormatter = new BinaryFormatter();
            var mStream      = new MemoryStream();

            try
            {
                binFormatter.Serialize(mStream, dictionary);

                var byteArray = mStream.ToArray();

                string result = HttpServerUtility.UrlTokenEncode(byteArray);

                return(result);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Beispiel #18
0
            public async Task WillUseLowercaseNormalizedIdAndVersionAndStreamHash()
            {
                var    fileStorageSvc = new Mock <ICoreFileStorageService>();
                var    service        = CreateService(fileStorageService: fileStorageSvc);
                string path           = null;

                fileStorageSvc
                .Setup(x => x.SaveFileAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Stream>(), It.IsAny <bool>()))
                .Returns(Task.FromResult(true))
                .Callback <string, string, Stream, bool>((_, p, __, ___) => path = p);

                var package = CreatePackage();

                package.PackageRegistration.Id = Id;
                package.NormalizedVersion      = NormalizedVersion;
                package.Hash = "NzMzMS1QNENLNEczSDQ1SA=="; // This hash should not be used.

                await service.StorePackageFileInBackupLocationAsync(package, CreatePackageFileStream());

                Assert.Equal($"nuget.versioning/4.3.0-beta/{HttpServerUtility.UrlTokenEncode(Convert.FromBase64String(PackageHash))}..nupkg", path);
            }
Beispiel #19
0
        public static string EncryptForUrl(string s)
        {
            if (string.IsNullOrEmpty(s))
            {
                return(string.Empty);
            }
            string result = string.Empty;

            byte[] buffer = Encoding.ASCII.GetBytes(s);
            var    des    = new TripleDESCryptoServiceProvider();
            var    MD5    = new MD5CryptoServiceProvider();

            var sSalt = getSalt("PublicSalt");

            des.Key = MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(getKey("PublicKey")));
            des.IV  = sSalt.Split(' ').Select(ss => Convert.ToByte(ss, 10)).ToArray();

            result = HttpServerUtility.UrlTokenEncode(
                des.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length));
            return(result);
        }
Beispiel #20
0
        /// <summary>
        ///   Issue a CAS ticket and store it temporarily in the context cache
        /// </summary>
        /// <param name="strUserName"> </param>
        /// <param name="strService"> </param>
        /// <returns> Returns the corresponding ticket string. </returns>
        public static string Issue(string strUserName, string strService)
        {
            // create the ticket
            var ticket = new CasTicket(strUserName, strService);

            // create 120 bit random data
            var rdata  = new byte[15];
            var random = new Random(DateTime.Now.Millisecond);

            random.NextBytes(rdata);

            // convert random data to an URL save token of 20 characters length
            var strToken = HttpServerUtility.UrlTokenEncode(rdata);

            // build the CAS ticket string
            var strTicket = "ST-" + (++_nCounter).ToString() + "-" + strToken + "-cas";


            TicketStorage.Add(strTicket, ticket, DateTime.Now.AddMinutes(1));
            return(strTicket);
        }
Beispiel #21
0
        /// <summary>Encode an item to be stored in a url.</summary>
        /// <typeparam name="T">The item type.</typeparam>
        /// <param name="item">The item instance.</param>
        /// <returns>The encoded token.</returns>
        public static string Encode <T>(T item)
        {
            var rsa = new RSACryptoServiceProvider();
            var key = ConfigurationManager.AppSettings["EncryptionKey"];

            if (string.IsNullOrEmpty(key))
            {
                throw new Exception("AppSetting 'EncryptionKey' is missing");
            }
            rsa.ImportCspBlob(Convert.FromBase64String(key));

            using (var memoryStream = new MemoryStream())
            {
                using (var gzipStream = new GZipStream(memoryStream, CompressionMode.Compress, true))
                {
                    using (var bsonWriter = new BsonWriter(gzipStream))
                        JsonSerializer.CreateDefault().Serialize(bsonWriter, item);
                }
                return(HttpServerUtility.UrlTokenEncode(rsa.Encrypt(memoryStream.ToArray(), true)));
            }
        }
Beispiel #22
0
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                var salty = ECDHAES256s.AES.GetSalt();
                var id    = context.Request.Path.TrimStart('/').Split(new string[] { ".key" }, StringSplitOptions.None)[0];

                var pk  = context.Request.QueryString["pk"];
                var cng = new CNG(HttpServerUtility.UrlTokenDecode(pk));
                cng = DH.B(cng); //MAKE KEY

                context.Application[id + "pass"] = Convert.ToBase64String(cng.Key);
                context.Response.ContentType     = "text/plain";
                context.Response.Write(HttpServerUtility.UrlTokenEncode(cng.PublicKey));
            }
            catch
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write("error");
            }
        }
Beispiel #23
0
        public void Protect()
        {
            // Arrange
            byte[] expectedInputBytes   = new byte[] { 1, 2, 3, 4, 5 };
            byte[] expectedOutputBytes  = new byte[] { 6, 7, 8, 9, 10 };
            string expectedOutputString = HttpServerUtility.UrlTokenEncode(expectedOutputBytes);

            Func <byte[], string[], byte[]> protectThunk = (input, purposes) =>
            {
                Assert.Equal(expectedInputBytes, input);
                Assert.Equal(new string[] { "System.Web.Helpers.AntiXsrf.AntiForgeryToken.v1" }, purposes);
                return(expectedOutputBytes);
            };

            MachineKey45CryptoSystem cryptoSystem = new MachineKey45CryptoSystem(protectThunk, null);

            // Act
            string output = cryptoSystem.Protect(expectedInputBytes);

            // Assert
            Assert.Equal(expectedOutputString, output);
        }
 public static string Encrypt <T>(string value, string password) where T : SymmetricAlgorithm, new()
 {
     byte[] vectorBytes = Encoding.ASCII.GetBytes(_vector);
     byte[] saltBytes   = Encoding.ASCII.GetBytes(_salt);
     byte[] valueBytes  = Encoding.UTF8.GetBytes(value);
     byte[] encrypted;
     using (T cipher = new T()) {
         PasswordDeriveBytes _passwordBytes = new PasswordDeriveBytes(_stuffing, saltBytes, _hash, _iterations);
         byte[] keyBytes = _passwordBytes.GetBytes(_keySize / 8);
         cipher.Mode = CipherMode.CBC;
         using (ICryptoTransform encryptor = cipher.CreateEncryptor(keyBytes, vectorBytes)) {
             MemoryStream to = new MemoryStream();
             using (CryptoStream writer = new CryptoStream(to, encryptor, CryptoStreamMode.Write)) {
                 writer.Write(valueBytes, 0, valueBytes.Length);
                 writer.FlushFinalBlock();
                 encrypted = to.ToArray();
             }
         }
         cipher.Clear();
     }
     return(HttpServerUtility.UrlTokenEncode(encrypted));
 }
        public void CanGetDocumentWithBase64EncodedKey()
        {
            Run(() =>
            {
                SearchIndexClient client = Data.GetSearchIndexClient();
                string complexKey        = HttpServerUtility.UrlTokenEncode(new byte[] { 1, 2, 3, 4, 5 });

                var expectedDoc =
                    new Document()
                {
                    { "hotelId", complexKey }
                };

                var batch = new IndexBatch(new[] { new IndexAction(expectedDoc) });
                client.Documents.Index(batch);
                SearchTestUtilities.WaitForIndexing();

                DocumentGetResponse getResponse = client.Documents.Get(complexKey, expectedDoc.Keys);
                Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode);
                SearchAssert.DocumentsEqual(expectedDoc, getResponse.Document);
            });
        }
Beispiel #26
0
        public static string Encrypt(string unencrypted)
        {
            if (string.IsNullOrEmpty(unencrypted))
            {
                return(string.Empty);
            }

            try
            {
                var encryptedBytes = MachineKey.Protect(Encoder.GetBytes(unencrypted));

                if (encryptedBytes != null && encryptedBytes.Length > 0)
                {
                    return(HttpServerUtility.UrlTokenEncode(encryptedBytes));
                }
            }
            catch (Exception)
            {
                return(string.Empty);
            }

            return(string.Empty);
        }
Beispiel #27
0
        private static string GetSiteUnsubscribeLink(NoticeMessage message, MailWhiteLabelSettings settings)
        {
            var mail = message.Recipient.Addresses.FirstOrDefault(r => r.Contains("@"));

            if (string.IsNullOrEmpty(mail))
            {
                return(string.Empty);
            }

            var format = CoreContext.Configuration.CustomMode
                             ? "{0}/unsubscribe/{1}"
                             : "{0}/Unsubscribe.aspx?id={1}";

            var site = settings == null
                           ? MailWhiteLabelSettings.DefaultMailSiteUrl
                           : settings.SiteUrl;

            return(string.Format(format,
                                 site,
                                 HttpServerUtility.UrlTokenEncode(
                                     Security.Cryptography.InstanceCrypto.Encrypt(
                                         Encoding.UTF8.GetBytes(mail.ToLowerInvariant())))));
        }
Beispiel #28
0
        public void _client_Received(WindowsFormsApp3.ClientSettings cs, string received)
        {
            var cmd = received.Split('|');

            switch (cmd[0])
            {
            case "CheieRSA":
                if (mUserNameTextBox.Text.Trim() == cmd[3].Trim())
                {
                    cheie.Exponent = HttpServerUtility.UrlTokenDecode(cmd[1]);
                    cheie.Modulus  = HttpServerUtility.UrlTokenDecode(cmd[2]);
                    byte[] DataToEncrypt = System.Text.Encoding.UTF8.GetBytes(mPasswordTextBox.Text);

                    byte[] parolaCriptata = e.RSAEncrypt(cheie, false, DataToEncrypt);
                    string qwe            = HttpServerUtility.UrlTokenEncode(parolaCriptata);
                    //   MessageBox.Show("parola criptata de la client::::" + qwe);
                    //MessageBox.Show("Exponent:::::::::::" + HttpServerUtility.UrlTokenEncode(cheie.Exponent));
                    //MessageBox.Show("Modul:::::::::::" + HttpServerUtility.UrlTokenEncode(cheie.Modulus));

                    Client.Send("ParolaCriptataRSA|" + qwe.Trim() + "|" + cmd[3].Trim());
                }

                break;

            case "LogInSuccessful":
                // MessageBox.Show("1");
                if (mUserNameTextBox.Text.Trim() == cmd[1].Trim())
                {
                    Client.Connected += Client_Connected;
                    Client.Connect(ip, 3000);
                    Client.Send("Connect|" + mUserNameTextBox.Text.Trim() + "|connected");
                }
                //  CloseForm();
                //   MessageBox.Show("2");
                break;
            }
        }
        public static string Encrypt(string toEncrypt, string key)
        {
            try
            {
                var des = new DESCryptoServiceProvider();
                var ms  = new MemoryStream();

                VerifyKey(ref key);

                des.Key = HashKey(key, des.KeySize / 8);
                des.IV  = HashKey(key, des.KeySize / 8);
                byte[] inputBytes = Encoding.UTF8.GetBytes(toEncrypt);

                var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
                cs.Write(inputBytes, 0, inputBytes.Length);
                cs.FlushFinalBlock();

                return(HttpServerUtility.UrlTokenEncode(ms.ToArray()));
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("An error occured while running encryption. Exception : {0}", ex.Message), ex);
            }
        }
Beispiel #30
0
        public static string PrintData(byte[] byteProtectedData)
        {
            string outputString = string.Empty;

            switch (DefinePurpose.enumPurpose)
            {
            case EnumPurpose.OWINCOOKIE:
                outputString = Convert.ToBase64String(byteProtectedData).Replace('+', '-').Replace('/', '_').Replace("=", "");
                break;

            case EnumPurpose.ASPXAUTH:
                outputString = CryptoUtil.BinaryToHex(byteProtectedData);
                break;

            case EnumPurpose.WEBRESOURCE:
                outputString = HttpServerUtility.UrlTokenEncode(byteProtectedData);
                break;

            case EnumPurpose.SCRIPTRESOURCE:
                outputString = HttpServerUtility.UrlTokenEncode(byteProtectedData);
                break;

            case EnumPurpose.VIEWSTATE:
                //Not needs as the exploit generated using ysoseria.net
                break;

            case EnumPurpose.UNKNOWN:

                break;

            default:

                break;
            }
            return(outputString);
        }