RSACryptoServiceProvider.SignData Метод

Определение

Вычисляет хэш-значение указанных данных и подписывает его.

Перегрузки

SignData(Byte[], Object)

Вычисляет хэш-значение заданного массива байтов с помощью указанного алгоритма хэширования и подписывает результирующее хэш-значение.

SignData(Stream, Object)

Вычисляет хэш-значение заданного потока с помощью указанного алгоритма хэширования и подписывает результирующее хэш-значение.

SignData(Byte[], Int32, Int32, Object)

Вычисляет хэш-значение подмножества заданного массива байтов с помощью указанного алгоритма хэширования и подписывает результирующее хэш-значение.

SignData(Byte[], Object)

Исходный код:
RSACryptoServiceProvider.Unix.cs
Исходный код:
RSACryptoServiceProvider.Unix.cs
Исходный код:
RSACryptoServiceProvider.Unix.cs

Вычисляет хэш-значение заданного массива байтов с помощью указанного алгоритма хэширования и подписывает результирующее хэш-значение.

public byte[] SignData(byte[] buffer, object halg);

Параметры

buffer
Byte[]

Входные данные для хэширования и подписи.

halg
Object

Хэш-алгоритм, который следует использовать для создания хэш-значения.

Возвращаемое значение

Byte[]

Подпись RSA для указанных данных.

Исключения

Параметр halg имеет значение null.

Параметр halg не является допустимым типом.

Примеры

В следующем примере кода подписывается и проверяется данные.

using System;
using System.Security.Cryptography;
using System.Text;

class RSACSPSample
{
    static void Main()
    {
        try
        {
            // Create a UnicodeEncoder to convert between byte array and string.
            ASCIIEncoding ByteConverter = new ASCIIEncoding();

            string dataString = "Data to Sign";

            // Create byte arrays to hold original, encrypted, and decrypted data.
            byte[] originalData = ByteConverter.GetBytes(dataString);
            byte[] signedData;

            // Create a new instance of the RSACryptoServiceProvider class
            // and automatically create a new key-pair.
            RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider();

            // Export the key information to an RSAParameters object.
            // You must pass true to export the private key for signing.
            // However, you do not need to export the private key
            // for verification.
            RSAParameters Key = RSAalg.ExportParameters(true);

            // Hash and sign the data.
            signedData = HashAndSignBytes(originalData, Key);

            // Verify the data and display the result to the
            // console.
            if(VerifySignedHash(originalData, signedData, Key))
            {
                Console.WriteLine("The data was verified.");
            }
            else
            {
                Console.WriteLine("The data does not match the signature.");
            }
        }
        catch(ArgumentNullException)
        {
            Console.WriteLine("The data was not signed or verified");
        }
    }
    public static byte[] HashAndSignBytes(byte[] DataToSign, RSAParameters Key)
    {
        try
        {
            // Create a new instance of RSACryptoServiceProvider using the
            // key from RSAParameters.
            RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider();

            RSAalg.ImportParameters(Key);

            // Hash and sign the data. Pass a new instance of SHA256
            // to specify the hashing algorithm.
            return RSAalg.SignData(DataToSign, SHA256.Create());
        }
        catch(CryptographicException e)
        {
            Console.WriteLine(e.Message);

            return null;
        }
    }

    public static bool VerifySignedHash(byte[] DataToVerify, byte[] SignedData, RSAParameters Key)
    {
        try
        {
            // Create a new instance of RSACryptoServiceProvider using the
            // key from RSAParameters.
            RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider();

            RSAalg.ImportParameters(Key);

            // Verify the data using the signature.  Pass a new instance of SHA256
            // to specify the hashing algorithm.
            return RSAalg.VerifyData(DataToVerify, SHA256.Create(), SignedData);
        }
        catch(CryptographicException e)
        {
            Console.WriteLine(e.Message);

            return false;
        }
    }
}

Комментарии

Этот метод создает цифровую подпись, проверенную с помощью VerifyData метода .

Параметр halg может принимать String, или HashAlgorithmType.

См. также раздел

Применяется к

.NET 10 и другие версии
Продукт Версии
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

SignData(Stream, Object)

Исходный код:
RSACryptoServiceProvider.Unix.cs
Исходный код:
RSACryptoServiceProvider.Unix.cs
Исходный код:
RSACryptoServiceProvider.Unix.cs

Вычисляет хэш-значение заданного потока с помощью указанного алгоритма хэширования и подписывает результирующее хэш-значение.

public byte[] SignData(System.IO.Stream inputStream, object halg);

Параметры

inputStream
Stream

Входной поток для хэширования и подписи.

halg
Object

Хэш-алгоритм, который следует использовать для создания хэш-значения.

Возвращаемое значение

Byte[]

Подпись RSA для указанных данных.

Исключения

Параметр halg имеет значение null.

Параметр halg не является допустимым типом.

Примеры

В следующем примере кода подписывается и проверяется данные.

using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;

class RSACSPSample
{
    static void Main()
    {
        try
        {
            ASCIIEncoding ByteConverter = new ASCIIEncoding();

            // Create some bytes to be signed.
            byte[] dataBytes = ByteConverter.GetBytes("Here is some data to sign!");

            // Create a buffer for the memory stream.
            byte[] buffer = new byte[dataBytes.Length];

            // Create a MemoryStream.
            MemoryStream mStream = new MemoryStream(buffer);

            // Write the bytes to the stream and flush it.
            mStream.Write(dataBytes, 0, dataBytes.Length);

            mStream.Flush();

            // Create a new instance of the RSACryptoServiceProvider class
            // and automatically create a new key-pair.
            RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider();

            // Export the key information to an RSAParameters object.
            // You must pass true to export the private key for signing.
            // However, you do not need to export the private key
            // for verification.
            RSAParameters Key = RSAalg.ExportParameters(true);

            // Hash and sign the data.
            byte[] signedData = HashAndSignBytes(mStream, Key);

            // Verify the data and display the result to the
            // console.
            if(VerifySignedHash(dataBytes, signedData, Key))
            {
                Console.WriteLine("The data was verified.");
            }
            else
            {
                Console.WriteLine("The data does not match the signature.");
            }

            // Close the MemoryStream.
            mStream.Close();
        }
        catch(ArgumentNullException)
        {
            Console.WriteLine("The data was not signed or verified");
        }
    }
    public static byte[] HashAndSignBytes(Stream DataStream, RSAParameters Key)
    {
        try
        {
            // Reset the current position in the stream to
            // the beginning of the stream (0). RSACryptoServiceProvider
            // can't verify the data unless the stream position
            // is set to the starting position of the data.
            DataStream.Position = 0;

            // Create a new instance of RSACryptoServiceProvider using the
            // key from RSAParameters.
            RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider();

            RSAalg.ImportParameters(Key);

            // Hash and sign the data. Pass a new instance of SHA256
            // to specify the hashing algorithm.
            return RSAalg.SignData(DataStream, SHA256.Create());
        }
        catch(CryptographicException e)
        {
            Console.WriteLine(e.Message);

            return null;
        }
    }

    public static bool VerifySignedHash(byte[] DataToVerify, byte[] SignedData, RSAParameters Key)
    {
        try
        {
            // Create a new instance of RSACryptoServiceProvider using the
            // key from RSAParameters.
            RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider();

            RSAalg.ImportParameters(Key);

            // Verify the data using the signature.  Pass a new instance of SHA256
            // to specify the hashing algorithm.
            return RSAalg.VerifyData(DataToVerify, SHA256.Create(), SignedData);
        }
        catch(CryptographicException e)
        {
            Console.WriteLine(e.Message);

            return false;
        }
    }
}

Комментарии

Параметр halg может принимать String, или HashAlgorithmType.

См. также раздел

Применяется к

.NET 10 и другие версии
Продукт Версии
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

SignData(Byte[], Int32, Int32, Object)

Исходный код:
RSACryptoServiceProvider.Unix.cs
Исходный код:
RSACryptoServiceProvider.Unix.cs
Исходный код:
RSACryptoServiceProvider.Unix.cs

Вычисляет хэш-значение подмножества заданного массива байтов с помощью указанного алгоритма хэширования и подписывает результирующее хэш-значение.

public byte[] SignData(byte[] buffer, int offset, int count, object halg);

Параметры

buffer
Byte[]

Входные данные для хэширования и подписи.

offset
Int32

Смещение в массиве, начиная с которого следует использовать данные.

count
Int32

Число байтов в массиве для использования в качестве данных.

halg
Object

Хэш-алгоритм, который следует использовать для создания хэш-значения.

Возвращаемое значение

Byte[]

Подпись RSA для указанных данных.

Исключения

Параметр halg имеет значение null.

Параметр halg не является допустимым типом.

Примеры

В следующем примере кода подписывается и проверяется данные.

using System;
using System.Security.Cryptography;
using System.Text;

class RSACSPSample
{
    static void Main()
    {
        try
        {
            // Create a UnicodeEncoder to convert between byte array and string.
            ASCIIEncoding ByteConverter = new ASCIIEncoding();

            string dataString = "Data to Sign";

            // Create byte arrays to hold original, encrypted, and decrypted data.
            byte[] originalData = ByteConverter.GetBytes(dataString);
            byte[] signedData;
            byte[] smallArray;

            // Create a new instance of the RSACryptoServiceProvider class
            // and automatically create a new key-pair.
            RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider();

            // Export the key information to an RSAParameters object.
            // You must pass true to export the private key for signing.
            // However, you do not need to export the private key
            // for verification.
            RSAParameters Key = RSAalg.ExportParameters(true);

            // Hash and sign the data.  Start at the fifth offset
            // only use data from the next 7 bytes.
            signedData = HashAndSignBytes(originalData, Key, 5, 7 );

            // The previous method only signed one segment
            // of the array.  Create a new array for verification
            // that only holds the data that was actually signed.
            //
            // Initialize the array.
            smallArray = new byte[7];
            // Copy 7 bytes starting at the 5th index to
            // the new array.
            Array.Copy(originalData, 5 , smallArray, 0, 7);

            // Verify the data and display the result to the
            // console.
            if(VerifySignedHash(smallArray, signedData, Key))
            {
                Console.WriteLine("The data was verified.");
            }
            else
            {
                Console.WriteLine("The data does not match the signature.");
            }
        }
        catch(ArgumentNullException)
        {
            Console.WriteLine("The data was not signed or verified");
        }
    }
    public static byte[] HashAndSignBytes(byte[] DataToSign, RSAParameters Key, int Index, int Length)
    {
        try
        {
            // Create a new instance of RSACryptoServiceProvider using the
            // key from RSAParameters.
            RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider();

            RSAalg.ImportParameters(Key);

            // Hash and sign the data. Pass a new instance of SHA256
            // to specify the hashing algorithm.
            return RSAalg.SignData(DataToSign,Index,Length, SHA256.Create());
        }
        catch(CryptographicException e)
        {
            Console.WriteLine(e.Message);

            return null;
        }
    }

    public static bool VerifySignedHash(byte[] DataToVerify, byte[] SignedData, RSAParameters Key)
    {
        try
        {
            // Create a new instance of RSACryptoServiceProvider using the
            // key from RSAParameters.
            RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider();

            RSAalg.ImportParameters(Key);

            // Verify the data using the signature.  Pass a new instance of SHA256
            // to specify the hashing algorithm.
            return RSAalg.VerifyData(DataToVerify, SHA256.Create(), SignedData);
        }
        catch(CryptographicException e)
        {
            Console.WriteLine(e.Message);

            return false;
        }
    }
}

Комментарии

Этот метод создает цифровую подпись, проверенную с помощью VerifyData метода .

Параметр halg может принимать String, или HashAlgorithmType. Строковое значение может быть одним из следующих:

  • Понятное имя идентификатора объекта (OID) используемого хэш-алгоритма: имя, зарегистрированное в файле конфигурации шифрования или в таблице OID API шифрования.

  • Значение времени существования OID. Идентификатор OID должен быть распознаваемым API шифрования.

Например, можно использовать SignData(new byte[5], "1.3.14.3.2.26") или SignData(new byte[5], "sha1") или SignData(new byte[5], "SHA1").

См. также раздел

Применяется к

.NET 10 и другие версии
Продукт Версии
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1