NFe.SafeNativeMethods.CertSetCertificateContextProperty C# (CSharp) Method

CertSetCertificateContextProperty() private method

private CertSetCertificateContextProperty ( IntPtr pCertContext, CertificateProperty propertyId, uint dwFlags, IntPtr pvData ) : bool
pCertContext System.IntPtr
propertyId CertificateProperty
dwFlags uint
pvData System.IntPtr
return bool
        internal static extern bool CertSetCertificateContextProperty(
            IntPtr pCertContext,
            CertificateProperty propertyId,
            uint dwFlags,
            IntPtr pvData
            );

Usage Example

        /// <summary>
        /// Passa PIN Code (Senha/Password) para Certificados
        ///  eToken como o A3 do SERASA do Brasil
        /// </summary>
        /// <param name="_Certificado">O Certificado que está sendo usado
        /// para a criptografia</param>
        /// <param name="_PinPassword">O Pin Code / Senha / Password</param>
        public static void SetPinPrivateKey(this X509Certificate2 _Certificado, string _PinPassword)
        {
            if (_Certificado == null)
            {
                throw new ArgumentNullException("_Certificado == null!");
            }
            var key = (RSACryptoServiceProvider)_Certificado.PrivateKey;

            IntPtr ProviderHandle = IntPtr.Zero;

            byte[] PinBuffer = Encoding.ASCII.GetBytes(_PinPassword);

            //Não é necessário descarregar o handle
            SafeNativeMethods.Execute(() => SafeNativeMethods.CryptAcquireContext(
                                          ref ProviderHandle,
                                          key.CspKeyContainerInfo.KeyContainerName,
                                          key.CspKeyContainerInfo.ProviderName,
                                          key.CspKeyContainerInfo.ProviderType,
                                          SafeNativeMethods.CryptContextFlags.Silent)
                                      );
            SafeNativeMethods.Execute(() => SafeNativeMethods.CryptSetProvParam(
                                          ProviderHandle,
                                          SafeNativeMethods.CryptParameter.KeyExchangePin,
                                          PinBuffer,
                                          0)
                                      );
            SafeNativeMethods.Execute(() => SafeNativeMethods.CertSetCertificateContextProperty(
                                          _Certificado.Handle,
                                          SafeNativeMethods.CertificateProperty.CryptoProviderHandle,
                                          0,
                                          ProviderHandle)
                                      );
        }