zoukankan      html  css  js  c++  java
  • 多线程下System.Security.Cryptography.Aes CreateDecryptor报“Safe handle has been closed”的解决方案

    因为系统需要对一些核心数据进行预加载以保证查询速度。

    所以在application_start 事件中启用了后台线程对相关的数据进行加载并解密(为了保证解密的效率,将AES对像做了静态对像来保存:private static readonly Aes aesAlg = Aes.Create();)

    但是在有些情况下报“Safe handle has been closed”异常导致加载失败。

    具体的堆栈信息:

    System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean& success)
    at System.StubHelpers.StubHelpers.SafeHandleAddRef(SafeHandle pHandle, Boolean& success)
    at System.Security.Cryptography.CapiNative.UnsafeNativeMethods.CryptDuplicateKey(SafeCapiKeyHandle hKey, IntPtr pdwReserved, Int32 dwFlags, SafeCapiKeyHandle& phKey)
    at Microsoft.Win32.SafeHandles.SafeCapiKeyHandle.Duplicate()
    at System.Security.Cryptography.CapiSymmetricAlgorithm.SetupKey(SafeCapiKeyHandle key, Byte[] iv, CipherMode cipherMode, Int32 feedbackSize)
    at System.Security.Cryptography.AesCryptoServiceProvider.CreateDecryptor(SafeCapiKeyHandle key, Byte[] iv)

    经查阅到一篇资料得知:

    在通常情况下可以重用这个对像,但是最好不要在多线程中使用。

    所以,解决方法:

    要么将AES对像每次实例化(但效率会降低),

    要么就用其它的来代替,比如(RijndaelManaged,正在测试,目前没有发现此问题了)。

  • 相关阅读:
    适配器模式
    事务
    JUnit4
    命令模式
    组合模式
    MySQL语法
    MyEclipse工具
    数据源和连接池
    Annotation
    Java反射机制
  • 原文地址:https://www.cnblogs.com/dengxi/p/7150824.html
Copyright © 2011-2022 走看看