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