• 多线程下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,正在测试,目前没有发现此问题了)。

  • 相关阅读:
    SQL语句在数据库中可以执行在mybatis执行不了
    spring_08aop原理及案例
    spring_07使用spring的特殊bean、完成分散配置
    spring_06装配bean_2
    spring_05装配bean
    spring_03ApplicationContext三种经常用到的实现
    spring_04bean的生命周期
    spring_02工具及接口案例
    深入理解Ribbon之源码解析
    深入理解Feign之源码解析
  • 原文地址:https://www.cnblogs.com/dengxi/p/7150824.html
Copyright © 2020-2023  润新知