Ejemplo n.º 1
0
 protected void btnDecrypt_Click(object sender, EventArgs e)
 {
     try
     {
         txtResult.Text = string.Empty;
         txtResult.Text = Encoding.UTF8.GetString(MachineKey.Unprotect(Convert.FromBase64String(txtValue.Text.Trim()), txtPurpose.Text.Trim()));
     }
     catch (Exception ex)
     {
         lblErr.Text = ex.Message;
     }
 }
Ejemplo n.º 2
0
 public ADALTokenCache(string signedInUserId)
 {
     // Asociar la memoria caché al usuario actual de la aplicación web
     userId            = signedInUserId;
     this.AfterAccess  = AfterAccessNotification;
     this.BeforeAccess = BeforeAccessNotification;
     this.BeforeWrite  = BeforeWriteNotification;
     // Buscar la entrada en la base de datos
     Cache = db.UserTokenCacheList.FirstOrDefault(c => c.webUserUniqueId == userId);
     // Colocar la entrada en la memoria
     this.Deserialize((Cache == null) ? null : MachineKey.Unprotect(Cache.cacheBits, "ADALCache"));
 }
Ejemplo n.º 3
0
 public AdalTokenCache(string signedInUserId)
 {
     // associate the cache to the current user of the web app
     _userId      = signedInUserId;
     AfterAccess  = AfterAccessNotification;
     BeforeAccess = BeforeAccessNotification;
     BeforeWrite  = BeforeWriteNotification;
     // look up the entry in the database
     _cache = _db.UserTokenCacheList.FirstOrDefault(c => c.WebUserUniqueId == _userId);
     // place the entry in memory
     Deserialize(_cache == null ? null : MachineKey.Unprotect(_cache.CacheBits, "ADALCache"));
 }
Ejemplo n.º 4
0
 public static string Decrypt(this string encryptedValue)
 {
     try
     {
         var decryptedBytes = MachineKey.Unprotect(Convert.FromBase64String(encryptedValue), "Authentication token");
         return(Encoding.UTF8.GetString(decryptedBytes));
     }
     catch
     {
         throw new SecurityException("token forgery");
     }
 }
 /// <summary>
 /// Decrypt string by machine key.
 /// </summary>
 /// <param name="encryptedValue">The string for decryption.</param>
 /// <returns>Decrypted string.</returns>
 public static string Decrypt(string encryptedValue)
 {
     try
     {
         byte[] decryptedBytes = MachineKey.Unprotect(Convert.FromBase64String(encryptedValue), "MachineKeyProtection.All");
         return(Encoding.UTF8.GetString(decryptedBytes));
     }
     catch
     {
         return(null);
     }
 }
        public void DecodeAddresses()
        {
            var bytes       = Convert.FromBase64String(SerializedAddresses);
            var unprotected = MachineKey.Unprotect(bytes, AddressEncryptionPurpose);

            if (unprotected != null)
            {
                SetAddressesVM(
                    JsonConvert.DeserializeObject <AddressesVM>(
                        Encoding.UTF8.GetString(unprotected)));
            }
        }
Ejemplo n.º 7
0
        public string Unprotect(string text, string purpose)
        {
            if (string.IsNullOrEmpty(text))
            {
                return(string.Empty);
            }

            var stream       = HttpServerUtility.UrlTokenDecode(text);
            var decodedValue = MachineKey.Unprotect(stream, purpose);

            return(Encoding.UTF8.GetString(decodedValue));
        }
 public ADALTokenCache(string signedInUserId)
 {
     // associate the cache to the current user of the web app
     userId            = signedInUserId;
     this.AfterAccess  = AfterAccessNotification;
     this.BeforeAccess = BeforeAccessNotification;
     this.BeforeWrite  = BeforeWriteNotification;
     // look up the entry in the database
     Cache = db.UserTokenCacheList.FirstOrDefault(c => c.webUserUniqueId == userId);
     // place the entry in memory
     this.Deserialize((Cache == null) ? null : MachineKey.Unprotect(Cache.cacheBits, "ADALCache"));
 }
Ejemplo n.º 9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AdalTokenCache"/> class.
 /// </summary>
 /// <param name="signedInUserId">The signed in user identifier.</param>
 public AdalTokenCache(string signedInUserId)
 {
     // associate the cache to the current user of the web app
     userId       = signedInUserId;
     AfterAccess  = AfterAccessNotification;
     BeforeAccess = BeforeAccessNotification;
     BeforeWrite  = BeforeWriteNotification;
     // look up the entry in the cache
     userToken = cache.Get(userId) as UserToken;
     // place the entry in memory
     Deserialize((userToken == null) ? null : MachineKey.Unprotect(userToken.CacheBits, "ADALCache"));
 }
        byte[] Unprotect(string value, HttpContext ctx)
        {
            if (String.IsNullOrWhiteSpace(value))
            {
                return(null);
            }

            var purpose = GetMachineKeyPurpose(ctx.User.Identity.Name);
            var bytes   = Convert.FromBase64String(value);

            return(MachineKey.Unprotect(bytes, purpose));
        }
Ejemplo n.º 11
0
    public static T Decrypt <T>(this string encrypted)
    {
        var    ba         = Convert.FromBase64String(encrypted);
        var    decodedArr = MachineKey.Unprotect(ba, "encrypted data");
        object o;

        using (var ms = new MemoryStream(decodedArr))
        {
            o = formatterPool.Value.Deserialize(ms);
        }
        return((T)o);
    }
Ejemplo n.º 12
0
        /// <summary>Decrypts text with MachineKey from Base64 string.</summary>
        public static string UnProtectWithMachineKey(string base64, string purpose, Encoding encoding = null)
        {
            if (string.IsNullOrEmpty(base64))
            {
                return(base64);
            }
            var encrypted = System.Convert.FromBase64String(base64);
            var decrypted = MachineKey.Unprotect(encrypted, purpose);
            var text      = (encoding ?? Encoding.UTF8).GetString(decrypted);

            return(text);
        }
        private byte[] Unprotect(string value)
        {
            if (String.IsNullOrWhiteSpace(value))
            {
                return(null);
            }
            string purpose = GetMachineKeyPurpose(Thread.CurrentPrincipal);

            byte[] bytes = Convert.FromBase64String(value);

            return(MachineKey.Unprotect(bytes, purpose));
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Unprotects the specified text.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="purpose">The purpose.</param>
        /// <returns>the Unprotect</returns>
        private static string Unprotect(string text, string purpose)
        {
            if (string.IsNullOrEmpty(text))
            {
                return(null);
            }

            byte[] stream       = HttpServerUtility.UrlTokenDecode(text);
            byte[] decodedValue = MachineKey.Unprotect(stream, purpose);

            return(Encoding.UTF8.GetString(decodedValue));
        }
Ejemplo n.º 15
0
        /// <summary>
        /// The body.
        /// </summary>
        /// <param name="id">The activity id.</param>
        protected override void ExecuteInternal(Guid id)
        {
            var exceptions = new List <Exception>();

            using (PerformanceProfiler.Instance.StartMarker(PerformanceMarkerName.Cache, PerformanceMarkerArea.Cms, PerformanceMarkerTagName.WarmupCache))
            {
                if (!this.Settings.AppDataRetryPolicy.DirectoryExists(this.AppDataFullPath))
                {
                    return;
                }

                var directory = this.Settings.AppDataRetryPolicy.GetDirectory(this.AppDataFullPath);
                var files     = directory.GetFiles(this.Settings.FilenameFormat.FormatWith("*"));
                var expiresOn = DateTimeOffset.UtcNow - this.Settings.ExpirationWindow;

                foreach (var file in files)
                {
                    try
                    {
                        var expired = file.LastWriteTimeUtc < expiresOn;

                        if (!expired)
                        {
                            ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Reading: " + file.FullName);

                            var bytes   = this.Settings.AppDataRetryPolicy.ReadAllBytes(file.FullName);
                            var json    = Encoding.UTF8.GetString(MachineKey.Unprotect(bytes, this.Settings.GetType().ToString()));
                            var request = CrmJsonConvert.DeserializeObject(json) as OrganizationRequest;

                            if (request != null)
                            {
                                this.Context.Service.ExecuteRequest(request);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        WebEventSource.Log.GenericWarningException(e);

                        if (this.Settings.PropagateExceptions)
                        {
                            exceptions.Add(e);
                        }
                    }
                }
            }

            if (this.Settings.PropagateExceptions && exceptions.Any())
            {
                throw new AggregateException(exceptions);
            }
        }
Ejemplo n.º 16
0
        public override async Task GrantCustomExtension(OAuthGrantCustomExtensionContext context)
        {
            if (context.GrantType != "anonymous")
            {
                return;
            }

            var db = new KiwiContext();

            var protectedToken = HttpServerUtility.UrlTokenDecode(context.Parameters.Get("token"));

            if (protectedToken == null)
            {
                return;
            }

            var anonymousToken = Encoding.UTF8.GetString(MachineKey.Unprotect(protectedToken));

            var tokenArray = anonymousToken.Split('‼');

            var reportId = Int32.Parse(tokenArray[0]);
            var time     = DateTime.Parse(tokenArray[1]);

            if (tokenArray.Length != 2 && reportId != 0 && time != new DateTime())
            {
                context.SetError("invalid_grant", "This token is invalid");
                return;
            }

            if (time < DateTime.Now)
            {
                context.SetError("invalid_grant", "This token has expired");
                return;
            }

            if (await db.Reports.FindAsync(reportId) == null)
            {
                context.SetError("invalid_grant", "No report found with that ID");
                return;
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Role, "Anonymous"));
            identity.AddClaim(new Claim("reportId", reportId.ToString()));
            identity.AddClaim(new Claim("is_anonymous", "true"));

            // token for reporting users should be valid for 10 minutes
            //context.Options.AccessTokenExpireTimeSpan = new TimeSpan(0, 10, 0);

            context.Validated(identity);
        }
Ejemplo n.º 17
0
 public static string Decryption(string decryptionString)
 {
     try
     {
         var bytes = Convert.FromBase64String(decryptionString);
         return(Encoding.UTF8.GetString(MachineKey.Unprotect(bytes, "Insus.NET")));
     }
     catch (Exception exception)
     {
         Console.WriteLine(exception.Message);
         return(decryptionString);
     }
 }
Ejemplo n.º 18
0
 public static string DecryptCookie(string value)
 {
     try
     {
         var encryptedBytes = Convert.FromBase64String(value);
         var decryptedBytes = MachineKey.Unprotect(encryptedBytes, "Cookie protection");
         return(decryptedBytes != null?Encoding.UTF8.GetString(decryptedBytes) : value);
     }
     catch
     {
         return(value);
     }
 }
        void BeforeAccessNotification(TokenCacheNotificationArgs args)
        {
            var latestToken = _repository.GetAllTokensForUser(userId)
                              .OrderByDescending(a => a.LastWrite)
                              .FirstOrDefault();

            if (Cache == null || (latestToken != null && Cache.LastWrite < latestToken.LastWrite))
            {
                Cache = latestToken;
            }

            this.Deserialize((Cache == null) ? null : MachineKey.Unprotect(Cache.CacheBits, "ADALTableCache"));
        }
Ejemplo n.º 20
0
 public static int?Unprotect(string protectedText)
 {
     if (!String.IsNullOrEmpty(protectedText))
     {
         var protectedBytes = HttpServerUtility.UrlTokenDecode(protectedText);
         //var protectedBytes = Convert.FromBase64String(protectedText);
         var unprotectedBytes = MachineKey.Unprotect(protectedBytes, Purpose);
         var unprotectedText  = Encoding.UTF8.GetString(unprotectedBytes);
         var finalString      = unprotectedText.Substring(Secret1.Length, unprotectedText.Length - Secret2.Length - Secret1.Length);
         return(int.Parse(finalString));
     }
     return(null);
 }
Ejemplo n.º 21
0
        /// <summary>
        /// Unprotects (decrypts) the given string value using MachineKey.UnProtect and the MachineKeyPurpose
        /// </summary>
        /// <param name="value">The value to decrypt</param>
        /// <param name="additionalPurposes">Any additional encryption Purposes you want to add to the default MachineKey Purpose. The list of purposes has to be in the same order as they where when Protect was called</param>
        /// <returns>The decrypted data</returns>
        private static byte[] Unprotect(string value, params string[] additionalPurposes)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                return(null);
            }

            string purpose = MachineKeyEncryption.MachineKeyPurpose + (additionalPurposes.Length > 0 ? "_" + additionalPurposes.Aggregate((s1, s2) => { return(s1 + "_" + s2); }) : string.Empty);

            var bytes = Convert.FromBase64String(value);

            return(MachineKey.Unprotect(bytes, purpose));
        }
Ejemplo n.º 22
0
        private static readonly string[] Purposes = { "key" }; // Todo: read in config

        public static string GetCookie(this HttpContextBase httpContext, string key)
        {
            HttpCookie cookie = httpContext.Request.Cookies[key];

            if (cookie != null && !string.IsNullOrEmpty(cookie.Value))
            {
                var base64  = Convert.FromBase64String(cookie.Value);
                var decrypt = MachineKey.Unprotect(base64, Purposes);
                return(Encoding.UTF8.GetString(decrypt ?? throw new InvalidOperationException()));
            }

            return(null);
        }
        public static void ValidateToken(string token)
        {
            var encrypted  = Convert.FromBase64String(token);
            var bytes      = MachineKey.Unprotect(encrypted, Purpose);
            var ticks      = BitConverter.ToInt64(bytes, 0);
            var expiredUtc = new DateTime(ticks, DateTimeKind.Utc);

            // add 5 mins clock skew
            if (expiredUtc.AddMinutes(5) < DateTime.UtcNow)
            {
                throw new InvalidOperationException(string.Format("Token has expired at {0}", expiredUtc));
            }
        }
Ejemplo n.º 24
0
 protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
 {
     if (Request.Cookies["email"] != null)
     {
         var    authCookie = Request.Cookies["email"].Value;
         var    bytes      = Convert.FromBase64String(authCookie);
         var    output     = MachineKey.Unprotect(bytes, "ProtectCookie");
         string result     = Encoding.UTF8.GetString(output);
         var    identity   = new GenericIdentity(result);
         var    principal  = new GenericPrincipal(identity, null);
         SetPrincipal(principal);
     }
 }
Ejemplo n.º 25
0
        public ActionResult ResetPassword(string userEmail, string code, string accountname)
        {
            ResetPasswordViewModel resetPasswordViewModel = new ResetPasswordViewModel();
            var resetpasswordpage = "ResetPassword";

            try
            {
                var securedUserEmail     = Convert.FromBase64String(userEmail);
                var decryptedUserId      = MachineKey.Unprotect(securedUserEmail);
                var securedAccountName   = Convert.FromBase64String(accountname);
                var decryptedAccountName = MachineKey.Unprotect(securedAccountName);
                userEmail   = GetString(decryptedUserId);
                accountname = GetString(decryptedAccountName);
                if (userEmail == null || code == null || accountname == null)
                {
                    Logger.Current.Informational("Any one or more of the parameters  is null.");
                    ModelState.AddModelError("", "Invalid details");
                    return(View(resetPasswordViewModel));
                }
                string modifiedCode = code.Replace(" ", "+");
                GetAccountAuthorizationRequest request = new GetAccountAuthorizationRequest();
                request.name = DomainName;
                var accountID = default(int);
                GetAccountAuthorizationResponse response = accountService.GetAccountByDomainUrl(request);
                if (response.Exception != null)
                {
                    ExceptionHandler.Current.HandleException(response.Exception, DefaultExceptionPolicies.LOG_ONLY_POLICY);
                    ModelState.AddModelError("", "Invalid Account.");
                    return(View(resetPasswordViewModel));
                }
                GetSubscriptionSettingsRequest ssRequest = new GetSubscriptionSettingsRequest();
                if (response != null)
                {
                    accountID = response.AccountId;
                    ssRequest.SubscriptionId = response.SubscriptionId;
                }
                GetSubscriptionSettingsResponse ssResponse = accountService.GetSubscriptionSettings(ssRequest);
                resetpasswordpage = ssResponse.SubscriptionSettings.Where(p => p.SubscriptionSettingType == SubscriptionSettingTypes.ResetPassword).Select(p => p.Value).FirstOrDefault();
                resetPasswordViewModel.AccountId   = accountID;
                resetPasswordViewModel.AccountName = accountname;
                resetPasswordViewModel.Email       = userEmail;
                resetPasswordViewModel.Code        = modifiedCode;
            }
            catch (Exception ex)
            {
                ExceptionHandler.Current.HandleException(ex, DefaultExceptionPolicies.LOG_ONLY_POLICY);
                ModelState.AddModelError("", "[|An error occurred, please try again later.|]");
                return(View(resetpasswordpage, resetPasswordViewModel));
            }
            return(View(resetpasswordpage, resetPasswordViewModel));
        }
Ejemplo n.º 26
0
        public static List <SerializableClaim> GetClaimsFromTicket(string ticket)
        {
            var compressedBytes = Convert.FromBase64String(ticket);

            var protectedBytes = MachineKey.Unprotect(compressedBytes, "CookieAuthentication");

            var unprotectedBytes = CompressionHelper.DecompressDeflate(protectedBytes);

            var claimsJson = Encoding.UTF8.GetString(unprotectedBytes);

            var serializableClaims = JsonConvert.DeserializeObject <IEnumerable <SerializableClaim> >(claimsJson);

            return(serializableClaims.ToList());
        }
Ejemplo n.º 27
0
        private void GetCahceAndDeserialize()
        {
            var cacheBits = GetUserTokenCache(userId);

            if (cacheBits != null)
            {
                try
                {
                    var data = MachineKey.Unprotect(cacheBits, MachinKeyProtectPurpose);
                    this.Deserialize(data);
                }
                catch { }
            }
        }
Ejemplo n.º 28
0
 public static string Unprotect(string protectedText)
 {
     try
     {
         var protectedBytes   = Convert.FromBase64String(protectedText);
         var unprotectedBytes = MachineKey.Unprotect(protectedBytes, Purpose);
         var unprotectedText  = Encoding.UTF8.GetString(unprotectedBytes);
         return(unprotectedText);
     }
     catch (Exception ex)
     {
         throw;
     }
 }
        public byte[] Load()
        {
            var bytes = inner.Load();

            try
            {
                return(MachineKey.Unprotect(bytes, Purpose));
            }
            catch
            {
                inner.Save(null);
            }
            return(null);
        }
Ejemplo n.º 30
0
        public Result<ServiceResponse> ResetPassword(ResetPasswordRequest request)
        {
            return this.InTransaction("Default", uow =>
            {
                request.CheckNotNull();

                if (string.IsNullOrEmpty(request.Token))
                    throw new ArgumentNullException("token");

                int userId;
                using (var ms = new MemoryStream(MachineKey.Unprotect(
                    Convert.FromBase64String(request.Token), "ResetPassword")))
                using (var br = new BinaryReader(ms))
                {
                    var dt = DateTime.FromBinary(br.ReadInt64());
                    if (dt < DateTime.UtcNow)
                        throw new ValidationError(Texts.Validation.InvalidResetToken);

                    userId = br.ReadInt32();
                }

                UserRow user;
                using (var connection = SqlConnections.NewFor<UserRow>())
                {
                    user = connection.TryById<UserRow>(userId);
                    if (user == null)
                        throw new ValidationError(Texts.Validation.InvalidResetToken);
                }

                if (request.ConfirmPassword != request.NewPassword)
                    throw new ValidationError("PasswordConfirmMismatch", LocalText.Get("Validation.PasswordConfirm"));

                request.NewPassword = UserRepository.ValidatePassword(user.Username, request.NewPassword, false);

                var salt = Membership.GeneratePassword(5, 1);
                var hash = SiteMembershipProvider.ComputeSHA512(request.NewPassword + salt);
                UserRepository.CheckPublicDemo(user.UserId);

                uow.Connection.UpdateById(new UserRow
                {
                    UserId = user.UserId.Value,
                    PasswordSalt = salt,
                    PasswordHash = hash
                });

                BatchGenerationUpdater.OnCommit(uow, UserRow.Fields.GenerationKey);

                return new ServiceResponse();
            });
        }