Криптографические преобразования данных. Этот класс не наследуется.

Пространство имен:  CryptoPro.Sharpei
Сборка:  CryptoPro.Sharpei.Base (в CryptoPro.Sharpei.Base.dll)

Синтаксис

Visual Basic
<ComVisibleAttribute(True)> _
Public NotInheritable Class CPCryptoAPITransform _
	Implements ICryptoTransform, IDisposable
C#
[ComVisibleAttribute(true)]
public sealed class CPCryptoAPITransform : ICryptoTransform, 
	IDisposable
Visual C++
[ComVisibleAttribute(true)]
public ref class CPCryptoAPITransform sealed : ICryptoTransform, 
	IDisposable
JavaScript
CryptoPro.Sharpei.CPCryptoAPITransform = function();

Type.createClass(
	'CryptoPro.Sharpei.CPCryptoAPITransform',
	null,
	ICryptoTransform,
	IDisposable);

Примеры

Пример шифрования при помощи CPCryptoAPITransform.
Visual Basic Copy imageCopy Code
Imports System
Imports System.Collections
Imports System.Text

Imports CryptoPro.Sharpei

Namespace DocBlock
    Class CrApiTrans
        ' CSP для шифрования.
        Shared gost As Gost28147CryptoServiceProvider = New Gost28147CryptoServiceProvider()

        <STAThread()> _
        Shared Sub Main(ByVal args As String())
            Dim message As String = "012345678901234567890"
            Dim sourceBytes As Byte() = Encoding.ASCII.GetBytes(message)
            Console.WriteLine("** Строка до зашифрования: " + message)

            Dim encodedBytes As Byte() = EncodeBytes(sourceBytes)
            ' Заменяем непечатные символы ?
            Dim encoded As StringBuilder = New StringBuilder()
            For Each c As Char In Encoding.ASCII.GetString(encodedBytes)
                If c < " "c Then encoded.Append("?"c) Else encoded.Append(c)
            Next
            Console.WriteLine("** Строка после зашифрования: " & _
                encoded.ToString())

            Dim decodedBytes As Byte() = DecodeBytes(encodedBytes)
            Console.WriteLine("** Строка после расшифрования: " & _
                Encoding.ASCII.GetString(decodedBytes))
        End Sub

        ' Шифрование байтовой строки с использованием CPCryptoAPITranform.
        Private Shared Function EncodeBytes(ByVal sourceBytes As Byte()) As Byte()
            Dim currentPosition As Integer = 0
            Dim targetBytes As Byte() = New Byte(1024) {}
            Dim sourceByteLength As Integer = sourceBytes.Length

            ' Создаем шифратор для ГОСТ 28147.
            Dim cryptoTransform As CPCryptoAPITransform = _
                gost.CreateEncryptor()

            ' Размер входного блока.
            Dim inputBlockSize As Integer = cryptoTransform.InputBlockSize

            ' Размер выходного блока.
            Dim outputBlockSize As Integer = cryptoTransform.OutputBlockSize

            Try
                ' Если возможна обработка нескольких блоков:
                If cryptoTransform.CanTransformMultipleBlocks Then
                    Dim numBytesRead As Integer = 0
                    Do While sourceByteLength - currentPosition >= inputBlockSize
                        ' Преобразуем байты начиная с currentPosition в массиве 
                        ' sourceBytes, записывая результат в массив targetBytes.
                        numBytesRead = cryptoTransform.TransformBlock( _
                            sourceBytes, _
                            currentPosition, _
                            inputBlockSize, _
                            targetBytes, _
                            currentPosition)

                        currentPosition += numBytesRead
                    Loop

                    ' Преобразуем последний блок.
                    Dim finalBytes As Byte() = cryptoTransform.TransformFinalBlock( _
                        sourceBytes, _
                        currentPosition, _
                        sourceByteLength - currentPosition)

                    ' Записываем последний зашифрованный блок 
                    ' в массив targetBytes.
                    finalBytes.CopyTo(targetBytes, currentPosition)
                    currentPosition += finalBytes.Length
                End If
            Catch ex As Exception
                Console.WriteLine("Неожиданное исключение:" + ex.ToString())
            End Try

            ' Определяем, может ли CPCryptoAPITransform использоваться повторно.
            If Not cryptoTransform.CanReuseTransform Then
                ' Освобождаем занятые ресурсы.
                cryptoTransform.Clear()
            End If

            ' Убираем неиспользуемые байты из массива.
            Array.Resize(Of Byte)(targetBytes, currentPosition)
            Return targetBytes
        End Function

        ' Расшифрование байтовой строки с использованием CPCryptoAPITranform.
        Shared Function DecodeBytes(ByVal sourceBytes As Byte()) As Byte()
            Dim targetBytes As Byte() = New Byte(1024) {}
            Dim currentPosition As Integer = 0

            ' Создаем дешифратор для ГОСТ.
            Dim cryptoTransform As CPCryptoAPITransform = _
                gost.CreateDecryptor()

            Dim inputBlockSize As Integer = cryptoTransform.InputBlockSize
            Dim sourceByteLength As Integer = sourceBytes.Length

            Try
                Dim numBytesRead As Integer = 0
                Do While sourceByteLength - currentPosition >= inputBlockSize
                    ' Преобразуем байты начиная с currentPosition в массиве 
                    ' sourceBytes, записывая результат в массив targetBytes.
                    numBytesRead = cryptoTransform.TransformBlock( _
                        sourceBytes, _
                        currentPosition, _
                        inputBlockSize, _
                        targetBytes, _
                        currentPosition)

                    currentPosition += numBytesRead
                Loop

                ' Преобразуем последний блок.
                Dim finalBytes As Byte() = cryptoTransform.TransformFinalBlock( _
                    sourceBytes, _
                    currentPosition, _
                    sourceByteLength - currentPosition)

                ' Записываем последний расшифрованный блок 
                ' в массив targetBytes.
                finalBytes.CopyTo(targetBytes, currentPosition)
                currentPosition += finalBytes.Length
            Catch ex As Exception
                Console.WriteLine("Неожиданное исключение:" + ex.ToString())
            End Try

            ' Убираем неиспользуемые байты из массива.
            Array.Resize(Of Byte)(targetBytes, currentPosition)
            Return targetBytes
        End Function
    End Class
End Namespace
C# Copy imageCopy Code
using System;
using System.Collections;
using System.Text;

using CryptoPro.Sharpei;

namespace Samples.DocBlock
{
    class CrApiTrans
    {
        // CSP для шифрования.
        static Gost28147CryptoServiceProvider gost = new Gost28147CryptoServiceProvider();

        [STAThread]
        static void Main(string[] args)
        {
            string message = "012345678901234567890";
            byte[] sourceBytes = Encoding.ASCII.GetBytes(message);
            Console.WriteLine("** Строка до зашифрования: " + message);

            byte[] encodedBytes = EncodeBytes(sourceBytes);
            // Заменяем непечатные символы ?
            StringBuilder encoded = new StringBuilder();
            foreach (char c in Encoding.ASCII.GetString(encodedBytes))
                if (c < ' ') encoded.Append('?'); else encoded.Append(c);
            Console.WriteLine("** Строка после зашифрования: " +
                encoded.ToString());

            byte[] decodedBytes = DecodeBytes(encodedBytes);
            Console.WriteLine("** Строка после расшифрования: " +
                Encoding.ASCII.GetString(decodedBytes));
        }

        // Шифрование байтовой строки с использованием CPCryptoAPITranform.
        private static byte[] EncodeBytes(byte[] sourceBytes)
        {
            int currentPosition = 0;
            byte[] targetBytes = new byte[1024];
            int sourceByteLength = sourceBytes.Length;

            // Создаем шифратор для ГОСТ 28147.
            CPCryptoAPITransform cryptoTransform = 
                (CPCryptoAPITransform)gost.CreateEncryptor();

            // Размер входного блока.
            int inputBlockSize = cryptoTransform.InputBlockSize;

            // Размер выходного блока.
            int outputBlockSize = cryptoTransform.OutputBlockSize;

            try
            {
                // Если возможна обработка нескольких блоков:
                if (cryptoTransform.CanTransformMultipleBlocks)
                {
                    int numBytesRead = 0;
                    while (sourceByteLength - currentPosition >= inputBlockSize)
                    {
                        // Преобразуем байты начиная с currentPosition в массиве 
                        // sourceBytes, записывая результат в массив targetBytes.
                        numBytesRead = cryptoTransform.TransformBlock(
                            sourceBytes,
                            currentPosition,
                            inputBlockSize,
                            targetBytes,
                            currentPosition);

                        currentPosition += numBytesRead;
                    }

                    // Преобразуем последний блок.
                    byte[] finalBytes = cryptoTransform.TransformFinalBlock(
                        sourceBytes,
                        currentPosition,
                        sourceByteLength - currentPosition);

                    // Записываем последний зашифрованный блок 
                    // в массив targetBytes.
                    finalBytes.CopyTo(targetBytes, currentPosition);
                    currentPosition += finalBytes.Length;
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine("Неожиданное исключение:" + ex.ToString());
            }

            // Определяем, может ли CPCryptoAPITransform использоваться повторно.
            if (!cryptoTransform.CanReuseTransform)
            {
                // Освобождаем занятые ресурсы.
                cryptoTransform.Clear();
            }

            // Убираем неиспользуемые байты из массива.
            Array.Resize<byte>(ref targetBytes, currentPosition);
            return targetBytes;
        }

        // Расшифрование байтовой строки с использованием CPCryptoAPITranform.
        private static byte[] DecodeBytes(byte[] sourceBytes)
        {
            byte[] targetBytes = new byte[1024];
            int currentPosition = 0;

            // Создаем дешифратор для ГОСТ.
            CPCryptoAPITransform cryptoTransform =
                (CPCryptoAPITransform)gost.CreateDecryptor();

            int inputBlockSize = cryptoTransform.InputBlockSize;
            int sourceByteLength = sourceBytes.Length;

            try
            {
                int numBytesRead = 0;
                while (sourceByteLength - currentPosition >= inputBlockSize)
                {
                    // Преобразуем байты начиная с currentPosition в массиве 
                    // sourceBytes, записывая результат в массив targetBytes.
                    numBytesRead = cryptoTransform.TransformBlock(
                        sourceBytes,
                        currentPosition,
                        inputBlockSize,
                        targetBytes,
                        currentPosition);

                    currentPosition += numBytesRead;
                }

                // Преобразуем последний блок.
                byte[] finalBytes = cryptoTransform.TransformFinalBlock(
                    sourceBytes,
                    currentPosition,
                    sourceByteLength - currentPosition);

                // Записываем последний расшифрованный блок 
                // в массив targetBytes.
                finalBytes.CopyTo(targetBytes, currentPosition);
                currentPosition += finalBytes.Length;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Неожиданное исключение:" + ex.ToString());
            }

            // Убираем неиспользуемые байты из массива.
            Array.Resize<byte>(ref targetBytes, currentPosition);
            return targetBytes;
        }
    }
}

Иерархия наследования

System..::..Object
  CryptoPro.Sharpei..::..CPCryptoAPITransform

Потокобезопасность

Любые открытые члены этого типа, объявленные как static (Shared в Visual Basic), являются потокобезопасными. Потокобезопасность членов экземпляров не гарантирована.

Версии CSP:

КриптоПро CSP 2.0, КриптоПро CSP 3.0, КриптоПро CSP 3.6

См. также: