当前位置:  开发笔记 > 编程语言 > 正文

在调试中的加密操作期间发生错误

如何解决《在调试中的加密操作期间发生错误》经验,为你挑选了2个好方法。

我收到以下错误.这似乎只是在我升级我的visual studio 2015以进行第一次更新后才开始.我在这里读过一些关于机器密钥问题的线程吗?我不知道如何解决它并防止它.目前,当我使用IIS express在调试中运行时,我在本地计算机上收到此错误.

Exception Details: System.Security.Cryptography.CryptographicException: Error occurred during a cryptographic operation.

Cache = db.UserTokenCacheList.FirstOrDefault(c => c.webUserUniqueId == userId);

// place the entry in memory
this.Deserialize((Cache == null) ? null : MachineKey.Unprotect(Cache.cacheBits,"ADALCache"));


[CryptographicException: Error occurred during a cryptographic operation.]
   System.Web.Security.Cryptography.HomogenizingCryptoServiceWrapper.HomogenizeErrors(Func`2 func, Byte[] input) +115
   System.Web.Security.Cryptography.HomogenizingCryptoServiceWrapper.Unprotect(Byte[] protectedData) +70
   System.Web.Security.MachineKey.Unprotect(ICryptoServiceProvider cryptoServiceProvider, Byte[] protectedData, String[] purposes) +62
   System.Web.Security.MachineKey.Unprotect(Byte[] protectedData, String[] purposes) +121
   LEDES.Models.ADALTokenCache..ctor(String signedInUserId) in C:\Users\RLewis\Source\Workspaces\Workspace\LEDES\LEDES\Models\AdalTokenCache.cs:28
   LEDES.Startup.b__7_0(AuthorizationCodeReceivedNotification context) in C:\Users\RLewis\Source\Workspaces\Workspace\LEDES\LEDES\App_Start\Startup.Auth.cs:54
   Microsoft.Owin.Security.OpenIdConnect.d__1a.MoveNext() +4388
   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +26
   Microsoft.Owin.Security.OpenIdConnect.d__1a.MoveNext() +5776
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +28
   Microsoft.Owin.Security.Infrastructure.d__0.MoveNext() +471
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   System.Runtime.CompilerServices.TaskAwaiter.GetResult() +26
   Microsoft.Owin.Security.Infrastructure.d__0.MoveNext() +218
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   System.Runtime.CompilerServices.TaskAwaiter.GetResult() +26
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.d__5.MoveNext() +170
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   System.Runtime.CompilerServices.TaskAwaiter.GetResult() +26
   Microsoft.Owin.Security.Infrastructure.d__0.MoveNext() +525
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   System.Runtime.CompilerServices.TaskAwaiter.GetResult() +26
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.d__5.MoveNext() +170
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   System.Runtime.CompilerServices.TaskAwaiter.GetResult() +26
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.d__2.MoveNext() +166
   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +26
   Microsoft.Owin.Host.SystemWeb.Infrastructure.ErrorState.Rethrow() +26
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar) +81
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar) +30
   System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +380
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

以下是失败的代码 - 当我在设置项目时选择Azure身份验证时,这是由VS生成的.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Security;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

namespace LEDES.Models
{
    public class ADALTokenCache : TokenCache
    {
        private ApplicationDbContext db = new ApplicationDbContext();
        private string userId;
        private UserTokenCache Cache;

        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"));
        }

        // clean up the database
        public override void Clear()
        {
            base.Clear();
            var cacheEntry = db.UserTokenCacheList.FirstOrDefault(c => c.webUserUniqueId == userId);
            db.UserTokenCacheList.Remove(cacheEntry);
            db.SaveChanges();
        }

        // Notification raised before ADAL accesses the cache.
        // This is your chance to update the in-memory copy from the DB, if the in-memory version is stale
        void BeforeAccessNotification(TokenCacheNotificationArgs args)
        {
            if (Cache == null)
            {
                // first time access
                Cache = db.UserTokenCacheList.FirstOrDefault(c => c.webUserUniqueId == userId);
            }
            else
            { 
                // retrieve last write from the DB
                var status = from e in db.UserTokenCacheList
                             where (e.webUserUniqueId == userId)
                select new
                {
                    LastWrite = e.LastWrite
                };

                // if the in-memory copy is older than the persistent copy
                if (status.First().LastWrite > Cache.LastWrite)
                {
                    // read from from storage, update in-memory copy
                    Cache = db.UserTokenCacheList.FirstOrDefault(c => c.webUserUniqueId == userId);
                }
            }
            this.Deserialize((Cache == null) ? null : MachineKey.Unprotect(Cache.cacheBits, "ADALCache"));
        }

        // Notification raised after ADAL accessed the cache.
        // If the HasStateChanged flag is set, ADAL changed the content of the cache
        void AfterAccessNotification(TokenCacheNotificationArgs args)
        {
            // if state changed
            if (this.HasStateChanged)
            {
                Cache = new UserTokenCache
                {
                    webUserUniqueId = userId,
                    cacheBits = MachineKey.Protect(this.Serialize(), "ADALCache"),
                    LastWrite = DateTime.Now
                };
                // update the DB and the lastwrite 
                db.Entry(Cache).State = Cache.UserTokenCacheId == 0 ? EntityState.Added : EntityState.Modified;
                db.SaveChanges();
                this.HasStateChanged = false;
            }
        }

        void BeforeWriteNotification(TokenCacheNotificationArgs args)
        {
            // if you want to ensure that no concurrent write take place, use this notification to place a lock on the entry
        }

        public override void DeleteItem(TokenCacheItem item)
        {
            base.DeleteItem(item);
        }
    }
}

来自调用堆栈的信息和发生CryptographicEsception的点发生

    System.Web.dll!System.Web.Security.Cryptography.HomogenizingCryptoServiceWrapper.HomogenizeErrors(System.Func func, byte[] input)   Unknown
    System.Web.dll!System.Web.Security.Cryptography.HomogenizingCryptoServiceWrapper.Unprotect(byte[] protectedData)    Unknown
    System.Web.dll!System.Web.Security.MachineKey.Unprotect(System.Web.Security.Cryptography.ICryptoServiceProvider cryptoServiceProvider, byte[] protectedData, string[] purposes) Unknown
    System.Web.dll!System.Web.Security.MachineKey.Unprotect(byte[] protectedData, string[] purposes)    Unknown
>   LEDES.dll!LEDES.Models.ADALTokenCache.ADALTokenCache(string signedInUserId) Line 28 C#
    LEDES.dll!LEDES.Startup.ConfigureAuth.AnonymousMethod__7_0(Microsoft.Owin.Security.Notifications.AuthorizationCodeReceivedNotification context) Line 54 C#
    Microsoft.Owin.Security.OpenIdConnect.dll!Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationHandler.AuthenticateCoreAsync()  Unknown
    mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.InvokeMoveNext(object stateMachine)  Unknown
    mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)   Unknown
    mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)   Unknown
    mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.Run()    Unknown
    mscorlib.dll!System.Threading.Tasks.AwaitTaskContinuation.InvokeAction(object state)    Unknown
    mscorlib.dll!System.Threading.Tasks.AwaitTaskContinuation.RunCallback(System.Threading.ContextCallback callback, object state, ref System.Threading.Tasks.Task currentTask) Unknown
    mscorlib.dll!System.Threading.Tasks.SynchronizationContextAwaitTaskContinuation.Run(System.Threading.Tasks.Task task, bool canInlineContinuationTask)   Unknown
    mscorlib.dll!System.Threading.Tasks.Task.FinishContinuations()  Unknown
    mscorlib.dll!System.Threading.Tasks.Task.FinishStageThree() Unknown
    mscorlib.dll!System.Threading.Tasks.Task.TrySetResult(System.__Canon result)    Unknown
    mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult(Microsoft.Owin.IFormCollection result)    Unknown
    Microsoft.Owin.dll!Microsoft.Owin.OwinRequest.ReadFormAsync()   Unknown
    mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.InvokeMoveNext(object stateMachine)  Unknown
    mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)   Unknown
    mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)   Unknown
    mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.Run()    Unknown
    mscorlib.dll!System.Threading.Tasks.SynchronizationContextAwaitTaskContinuation..cctor.AnonymousMethod__8_0(object state)   Unknown
    System.Web.dll!System.Web.AspNetSynchronizationContext.Post.AnonymousMethod__0()    Unknown
    System.Web.dll!System.Web.Util.SynchronizationHelper.SafeWrapCallback(System.Action action) Unknown
    System.Web.dll!System.Web.Util.SynchronizationHelper.QueueAsynchronous.AnonymousMethod__0(System.Threading.Tasks.Task _)    Unknown
    mscorlib.dll!System.Threading.Tasks.ContinuationTaskFromTask.InnerInvoke()  Unknown
    mscorlib.dll!System.Threading.Tasks.Task.Execute()  Unknown
    mscorlib.dll!System.Threading.Tasks.Task.ExecutionContextCallback(object obj)   Unknown
    mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)   Unknown
    mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)   Unknown
    mscorlib.dll!System.Threading.Tasks.Task.ExecuteWithThreadLocal(ref System.Threading.Tasks.Task currentTaskSlot)    Unknown
    mscorlib.dll!System.Threading.Tasks.Task.ExecuteEntry(bool bPreventDoubleExecution) Unknown
    mscorlib.dll!System.Threading.Tasks.Task.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() Unknown
    mscorlib.dll!System.Threading.ThreadPoolWorkQueue.Dispatch()    Unknown
    mscorlib.dll!System.Threading._ThreadPoolWaitCallback.PerformWaitCallback() Unknown
    [Native to Managed Transition]  

小智.. 19

陷入同样的​​问题.在"使用它"之后超过一个小时,我进入了成员数据库(通常由Visual Studio自动创建)并从UserTokenCaches表中删除了所有行.跑过应用程序,得到了加密的错误信息.创建了一个新的缓存令牌记录并将其插入到表中.



1> 小智..:

陷入同样的​​问题.在"使用它"之后超过一个小时,我进入了成员数据库(通常由Visual Studio自动创建)并从UserTokenCaches表中删除了所有行.跑过应用程序,得到了加密的错误信息.创建了一个新的缓存令牌记录并将其插入到表中.



2> Hans Passant..:

添加了堆栈跟踪

你没有 了解为什么会收到如此无用的异常消息非常重要。这是故意的。System.Web隐藏了密码失败的真正原因。您将收到一个平淡的错误消息(“它不起作用”),并且没有失败的实际代码的堆栈跟踪。

重要的是,不这样做是很危险的,它使攻击者可以用有意格式错误的数据探查您的Web应用程序,并从异常中获取知识,从而找到破解安全代码的方法。

您需要获得更好的堆栈跟踪和异常消息以找到真正的原因。这要求您告诉调试器在引发异常时停止。真正的,而不是平淡的。在VS2015中,使用“调试”>“ Windows”>“异常设置”。单击“公共语言运行时例外”复选框,以将其从矩形变为选中标记。另外:工具>选项>调试>常规>取消选中“启用我的代码”复选框。

推荐阅读
贴进你的心聆听你的世界
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有