Compartir a través de


Cómo: Obtener acceso a los dispositivos de cifrado de hardware

Actualización: noviembre 2007

Puede utilizar la clase CspParameters para obtener acceso a los dispositivos de cifrado de hardware. Por ejemplo, puede utilizar esta clase para integrar la aplicación con una tarjeta inteligente, un generador de números aleatorios de hardware o una implementación de hardware de un algoritmo criptográfico concreto.

La clase CspParameters crea un proveedor de servicios criptográficos (CSP) que obtiene acceso a un dispositivo de cifrado de hardware correctamente instalado. Para comprobar la disponibilidad de un CSP, examine la siguiente clave del Registro mediante el Editor del Registro (Regex.exe): HKEY_LOCAL_MACHINE\Software\Microsoft\Cryptography\Defaults\Provider.

Para firmar datos mediante una tarjeta de claves

  1. Cree una nueva instancia de la clase CspParameters, pasando al constructor el tipo de proveedor entero y el nombre del proveedor.

  2. Pase los indicadores adecuados a la propiedad Flags del objeto CspParameters recién creado. Por ejemplo, pase el indicador UseDefaultKeyContainer.

  3. Cree una nueva instancia de una clase AsymmetricAlgorithm (por ejemplo, la clase RSACryptoServiceProvider), pasando el objeto CspParameters al constructor.

  4. Firme los datos mediante uno de los métodos Sign y compruebe los datos mediante uno de los métodos Verify.

Para generar un número aleatorio mediante un generador de números aleatorios de hardware

  1. Cree una nueva instancia de la clase CspParameters, pasando al constructor el tipo de proveedor entero y el nombre del proveedor.

  2. Cree una nueva instancia de RNGCryptoServiceProvider, pasando el objeto CspParameters al constructor.

  3. Cree un valor aleatorio mediante el método GetBytes o GetNonZeroBytes.

Ejemplo

En el ejemplo de código siguiente se muestra cómo firmar datos mediante una tarjeta inteligente. En el ejemplo de código se crea un objeto CspParameters que expone una tarjeta inteligente y, a continuación, se inicializa un objeto RSACryptoServiceProvider mediante el servidor CSP. A continuación, se firman y se comprueban algunos datos.

Imports System
Imports System.Security.Cryptography



Module SCSign

    Sub Main(ByVal args() As String)
        ' To idendify the Smart Card CryptoGraphic Providers on your
        ' computer, use the Microsoft Registry Editor (Regedit.exe).
        ' The available Smart Card CryptoGraphic Providers are listed
        ' in HKEY_LOCAL_MACHINE\Software\Microsoft\Cryptography\Defaults\Provider.

        ' Create a new CspParameters object that identifies a 
        ' Smart Card CryptoGraphic Provider.
        ' The 1st parameter comes from HKEY_LOCAL_MACHINE\Software\Microsoft\Cryptography\Defaults\Provider Types.
        ' The 2nd parameter comes from HKEY_LOCAL_MACHINE\Software\Microsoft\Cryptography\Defaults\Provider.
        Dim csp As New CspParameters(1, "Schlumberger Cryptographic Service Provider")
        csp.Flags = CspProviderFlags.UseDefaultKeyContainer

        ' Initialize an RSACryptoServiceProvider object using
        ' the CspParameters object.
        Dim rsa As New RSACryptoServiceProvider(csp)

        ' Create some data to sign.
        Dim data() As Byte = {0, 1, 2, 3, 4, 5, 6, 7}


        Console.WriteLine("Data   : " + BitConverter.ToString(data))

        ' Sign the data using the Smart Card CryptoGraphic Provider.
        Dim sig As Byte() = rsa.SignData(data, "SHA1")

        Console.WriteLine("Signature : " + BitConverter.ToString(sig))

        ' Verify the data using the Smart Card CryptoGraphic Provider.
        Dim verified As Boolean = rsa.VerifyData(data, "SHA1", sig)

        Console.WriteLine("Verified")

    End Sub

End Module
using System;
using System.Security.Cryptography;

namespace SmartCardSign
{
    class SCSign
    {
        static void Main(string[] args)
        {
            // To idendify the Smart Card CryptoGraphic Providers on your
            // computer, use the Microsoft Registry Editor (Regedit.exe).
            // The available Smart Card CryptoGraphic Providers are listed
            // in HKEY_LOCAL_MACHINE\Software\Microsoft\Cryptography\Defaults\Provider.


            // Create a new CspParameters object that identifies a 
            // Smart Card CryptoGraphic Provider.
            // The 1st parameter comes from HKEY_LOCAL_MACHINE\Software\Microsoft\Cryptography\Defaults\Provider Types.
            // The 2nd parameter comes from HKEY_LOCAL_MACHINE\Software\Microsoft\Cryptography\Defaults\Provider.
            CspParameters csp = new CspParameters(1, "Schlumberger Cryptographic Service Provider");
            csp.Flags = CspProviderFlags.UseDefaultKeyContainer;

            // Initialize an RSACryptoServiceProvider object using
            // the CspParameters object.
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(csp);

            // Create some data to sign.
            byte[] data = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 };

            Console.WriteLine("Data         : " + BitConverter.ToString(data));

            // Sign the data using the Smart Card CryptoGraphic Provider.
            byte[] sig = rsa.SignData(data, "SHA1");

            Console.WriteLine("Signature    : " + BitConverter.ToString(sig));

            // Verify the data using the Smart Card CryptoGraphic Provider.
            bool verified = rsa.VerifyData(data, "SHA1", sig);

            Console.WriteLine("Verified     : " + verified);

        }
    }
}
using namespace System;
using namespace System::Security::Cryptography;
int main()
{

   // To idendify the Smart Card CryptoGraphic Providers on your
   // computer, use the Microsoft Registry Editor (Regedit.exe).
   // The available Smart Card CryptoGraphic Providers are listed
   // in HKEY_LOCAL_MACHINE\Software\Microsoft\Cryptography\Defaults\Provider.
   // Create a new CspParameters object that identifies a 
   // Smart Card CryptoGraphic Provider.
   // The 1st parameter comes from HKEY_LOCAL_MACHINE\Software\Microsoft\Cryptography\Defaults\Provider Types.
   // The 2nd parameter comes from HKEY_LOCAL_MACHINE\Software\Microsoft\Cryptography\Defaults\Provider.
   CspParameters^ csp = gcnew CspParameters( 1,L"Schlumberger Cryptographic Service Provider" );
   csp->Flags = CspProviderFlags::UseDefaultKeyContainer;

   // Initialize an RSACryptoServiceProvider object using
   // the CspParameters object.
   RSACryptoServiceProvider^ rsa = gcnew RSACryptoServiceProvider( csp );

   // Create some data to sign.
   array<Byte>^data = gcnew array<Byte>{
      0,1,2,3,4,5,6,7
   };
   Console::WriteLine( L"Data           : {0}", BitConverter::ToString( data ) );

   // Sign the data using the Smart Card CryptoGraphic Provider.
   array<Byte>^sig = rsa->SignData( data, L"SHA1" );
   Console::WriteLine( L"Signature  : {0}", BitConverter::ToString( sig ) );

   // Verify the data using the Smart Card CryptoGraphic Provider.
   bool verified = rsa->VerifyData( data, L"SHA1", sig );
   Console::WriteLine( L"Verified       : {0}", verified );
}

Compilar el código

  • Incluya los espacios de nombres System y System.Security.Cryptography.

  • Debe tener un lector de tarjetas inteligentes y controladores instalados en el equipo.

  • Debe inicializar el objeto CspParameters utilizando información específica del lector de tarjetas. Para obtener más información, consulte la documentación del lector de tarjetas.

Vea también

Otros recursos

Tareas criptográficas