Ключевое слово в защите информации
КЛЮЧЕВОЕ СЛОВО
в защите информации
Получить ГОСТ TLS-сертификат для домена (SSL-сертификат)
Добро пожаловать, Гость! Чтобы использовать все возможности Вход или Регистрация.

Уведомление

Icon
Error

Опции
К последнему сообщению К первому непрочитанному
Offline Андрей Песков  
#1 Оставлено : 7 марта 2008 г. 19:37:05(UTC)
Андрей Песков

Статус: Участник

Группы: Участники
Зарегистрирован: 05.03.2008(UTC)
Сообщений: 11

CryptEncryptMessage очень тормозит при обработке файла в 7Мб.
А при обработке 20 Мб результата не дождался в течении часа и прервал выполнение.
Почему так происходит? Подскажите, плиз.
Листинг функции фифрования:
Код:

MYSTRUCTURE mCrypt(FILES Files, MYOUTMESSAGE inputMessage, bool test_or_not)
{
        MYSTRUCTURE outInfo;
        int errorNumber;
        char * outMessage, *alg, *ProvName;

        FILE *stream;
        BYTE* pbContent;
        DWORD cbContent;
        wchar_t * recipientName;
        int x;

       HCRYPTPROV hProv;

//--
        if (test_or_not==false)
        {
                recipientName=L"Name"; 
        }
        else
        {
                recipientName=L"Name1"
        }

//--
        if ((strlen(Files.inputFile)==0) || (strlen(Files.outputFile)==0))
        {
                cbContent = inputMessage.Number;
                pbContent = (BYTE*)malloc(cbContent);
                pbContent = inputMessage.Message;
        }
        else
        {
                 if ((stream = fopen(Files.inputFile, "rb")) == NULL)
                {
                        outInfo.outMessage.Message="Невозможно открыть входной файл";
                        outInfo.errorNumber=1;
                        return outInfo;
                }
                x = FileSizeByName(Files.inputFile);
                pbContent = (BYTE*)malloc(x);
                fread(pbContent, x, 1, stream);
                fclose(stream);
                cbContent = x;
        }

        HCERTSTORE hStoreHandle = 0;
        PCCERT_CONTEXT pRecipientCert = NULL;   
        PCCERT_CONTEXT RecipientCertArray[1];
        CRYPT_ENCRYPT_MESSAGE_PARA EncryptParams;
        BYTE*    pbEncryptedBlob = NULL;
        DWORD    cbEncryptedBlob;

        // Open a system certificate store.
        if(hStoreHandle = CertOpenSystemStore(
             NULL,
             "MY")) 
        {
                // Get a pointer to the recipient's certificate by calling GetRecipientCert.
                if(pRecipientCert = CertFindCertificateInStore(
                 hStoreHandle,
                 MY_TYPE,
                 0,
                 CERT_FIND_SUBJECT_STR,
                 recipientName,
                 NULL))
                {
                        RecipientCertArray[0] = pRecipientCert;
                                       
DWORD EncryptAlgSize;
CRYPT_ALGORITHM_IDENTIFIER EncryptAlgorithm;

DWORD EncryptParamsSize;
//memset(&EncryptAlgorithm, 0, EncryptAlgSize);
EncryptAlgorithm.Parameters.cbData = 0;
EncryptAlgorithm.Parameters.pbData = NULL;
EncryptAlgorithm.pszObjId = alg;
EncryptAlgSize = sizeof(EncryptAlgorithm);
EncryptParamsSize = sizeof(EncryptParams);
memset(&EncryptParams, 0, EncryptParamsSize);
EncryptParams.cbSize =  EncryptParamsSize;
EncryptParams.dwMsgEncodingType = MY_TYPE;

EncryptParams.hCryptProv = 0; 
EncryptParams.ContentEncryptionAlgorithm = EncryptAlgorithm;

                        // Call CryptEncryptMessage.

                        if(CryptEncryptMessage(
                         &EncryptParams,
                         1,
                         RecipientCertArray,
                         pbContent,
                         cbContent,
                         NULL,
                         &cbEncryptedBlob))
                        {
                                // Allocate memory for the returned BLOB.

                                if(pbEncryptedBlob = (BYTE*)malloc(cbEncryptedBlob))
                                {
                                        // Call CryptEncryptMessage again to encrypt the content.

                                        if(CryptEncryptMessage(
                                         &EncryptParams,
                                         1,
                                         RecipientCertArray,
                                         pbContent,
                                         cbContent,
                                         pbEncryptedBlob,
                                         &cbEncryptedBlob))
                                        {

                                                       if ((strlen(Files.inputFile)==0) || (strlen(Files.outputFile)==0))
                                                       {
                                                                outMessage=(char *)pbEncryptedBlob;
                                                                errorNumber = 0;
                                                                outInfo.outMessage.Number=cbEncryptedBlob;
                                                       }
                                                       else
                                                       {
                                                                if ((stream = fopen(Files.outputFile, "wb")) == NULL)
                                                                {
                                                                        outMessage = "Невозможно открыть выходной файл";
                                                                        errorNumber = 4;
                                                                }
                                                                else
                                                                {
                                                                        fwrite(pbEncryptedBlob, cbEncryptedBlob, 1, stream);
                                                                        fclose(stream);
                                                                        outMessage="";
                                                                        errorNumber = 0;
                                                                        outInfo.outMessage.Number=cbEncryptedBlob;
                                                                }
                                                       }
                                        }
                                        else
                                        {
                                                outMessage = "Encryption failed.";
                                                errorNumber = 5;
                                        }
                                }
                                else
                                {
                                        outMessage = "Memory allocation error while encrypting.";
                                        errorNumber = 3;
                                }
                        }
                        else
                        {
                                outMessage = "Getting EncrypBlob size failed.";
                                errorNumber = 6;
                        }
                }
                else
                {
                        outMessage = "A recipient's certificate not found.";
                        errorNumber = 7;
                }
        }
        else
        {
            outMessage = "Error getting store handle.";
            errorNumber = 2;
        }


outInfo.outMessage.Message=outMessage;
outInfo.errorNumber=errorNumber;

return outInfo;
}
Offline Андрей Песков  
#2 Оставлено : 7 марта 2008 г. 19:54:48(UTC)
Андрей Песков

Статус: Участник

Группы: Участники
Зарегистрирован: 05.03.2008(UTC)
Сообщений: 11

Задержка происходит при втором обращении к функции, когда идет непосредственная шифровка данных.
Может где какой параметр неверен или флаг не поставлен и из-за этого долго?
Кто знает проконсультируйте, плиз
Offline Kirill Sobolev  
#3 Оставлено : 7 марта 2008 г. 20:17:11(UTC)
Кирилл Соболев

Статус: Сотрудник

Группы: Участники
Зарегистрирован: 25.12.2007(UTC)
Сообщений: 1,732
Мужчина
Откуда: КРИПТО-ПРО

Поблагодарили: 177 раз в 168 постах
Техническую поддержку оказываем тут
Наша база знаний
Offline Андрей Песков  
#4 Оставлено : 11 марта 2008 г. 20:48:45(UTC)
Андрей Песков

Статус: Участник

Группы: Участники
Зарегистрирован: 05.03.2008(UTC)
Сообщений: 11

Делаю через CryptMsgOpenToEncode, что не так в параметрах((
Код:

HCRYPTMSG hMsg;

    if(hMsg = CryptMsgOpenToEncode(
        MY_TYPE,      // encoding type
        0,                     // flags
        CMSG_DATA,                     // use the default message type
                               // the message type is
                               // listed in the message header
        NULL,                  // cryptographic provider
                               // use NULL for the default provider
        NULL,                  // recipient information
        NULL))                 // stream information
    {
        printf("The message to decode is open. \n");
   }
    else
    {

    outMessage = "OpenToEncode failed";
    errorNumber = 6;
    return outInfo;
    }
    //---------------------------------------------------------------
    //  Update the message with an encoded BLOB.
    if(CryptMsgUpdate(
        hMsg,                 // handle to the message
        pbContent, // pointer to the encoded BLOB
        cbContent, // size of the encoded BLOB
        TRUE))                // last call
    {
        printf("The encoded BLOB has been added to the message. \n");
    }
    else
    {
    outMessage = "Decode MsgUpdate failed";
    errorNumber = 6;
    return outInfo;
    }

    //---------------------------------------------------------------
    //  Get the number of bytes needed for a buffer
    //  to hold the decoded message.
    if(CryptMsgGetParam(
        hMsg,                  // handle to the message
        CMSG_CONTENT_PARAM,    // parameter type
        0,                     // index
        NULL,
        &cbEncryptedBlob))           // size of the returned information
    {
        printf("The message parameter has been acquired. \n");
    }
    else
    {
    outMessage = "Encode CMSG_CONTENT_PARAM failed.";
    errorNumber = 6;
    return outInfo;
    }
    //---------------------------------------------------------------
    // Allocate memory.
    if(!(pbEncryptedBlob = (BYTE *) malloc(cbEncryptedBlob)))
    {
    outMessage = "Encode memory allocation failed.";
    errorNumber = 6;
    return outInfo;
    }

    //---------------------------------------------------------------
    // Copy the content to the buffer.
    t=0;
    if(CryptMsgGetParam(
        hMsg,                 // handle to the message
        CMSG_CONTENT_PARAM,   // parameter type
        0,                    // index
        pbEncryptedBlob,            // address for returned information
        &cbEncryptedBlob))          // size of the returned information
    {
if ((strlen(Files.inputFile)==0) || (strlen(Files.outputFile)==0))
                                                       {
                                                                outMessage=(char *)pbEncryptedBlob;
                                                                errorNumber = 0;
                                                                outInfo.outMessage.Number=cbEncryptedBlob;
                                                       }
                                                       else
                                                       {
                                                                if ((stream = fopen(Files.outputFile, "ab")) == NULL)
                                                                {
                                                                        outMessage = "Íåâîçìîæíî îòêðûòü âûõîäíîé ôàéë";
                                                                        errorNumber = 4;
                                                                }
                                                                else
                                                                {
                                                                        fwrite(pbEncryptedBlob, cbEncryptedBlob, 1, stream);
                                                                        fclose(stream);
                                                                        outMessage="";
                                                                        errorNumber = 0;
                                                                        outInfo.outMessage.Number=cbEncryptedBlob;
                                                                }
                                                       }
    }
    else
    {
    outMessage = "Encode CMSG_CONTENT_PARAM failed.";
    errorNumber = 6;
outInfo.outMessage.Message=outMessage;
outInfo.errorNumber=errorNumber;
    return outInfo;
    }
Offline Kirill Sobolev  
#5 Оставлено : 12 марта 2008 г. 18:09:32(UTC)
Кирилл Соболев

Статус: Сотрудник

Группы: Участники
Зарегистрирован: 25.12.2007(UTC)
Сообщений: 1,732
Мужчина
Откуда: КРИПТО-ПРО

Поблагодарили: 177 раз в 168 постах
а что именно не работает?
Техническую поддержку оказываем тут
Наша база знаний
Offline Андрей Песков  
#6 Оставлено : 13 марта 2008 г. 13:39:54(UTC)
Андрей Песков

Статус: Участник

Группы: Участники
Зарегистрирован: 05.03.2008(UTC)
Сообщений: 11

Получается файл. При открытии его с помощью криптографических средств он оказывается не зашифрован и не подписан. При открытии в блокноте в нутри файла лабуда.
Offline Kirill Sobolev  
#7 Оставлено : 13 марта 2008 г. 14:00:58(UTC)
Кирилл Соболев

Статус: Сотрудник

Группы: Участники
Зарегистрирован: 25.12.2007(UTC)
Сообщений: 1,732
Мужчина
Откуда: КРИПТО-ПРО

Поблагодарили: 177 раз в 168 постах
правильно, а где у Вас в коде собственно указание на то что надо шифровать или подписывать?
посмотрите пример шифрования при помощи CryptMsg* функций в http://www.cryptopro.ru/...ts/csp/20/sample-2-0.zip
Техническую поддержку оказываем тут
Наша база знаний
Offline Андрей Песков  
#8 Оставлено : 17 марта 2008 г. 14:22:38(UTC)
Андрей Песков

Статус: Участник

Группы: Участники
Зарегистрирован: 05.03.2008(UTC)
Сообщений: 11

Спасибо. Сейчас попробую разобраться
RSS Лента  Atom Лента
Пользователи, просматривающие эту тему
Быстрый переход  
Вы не можете создавать новые темы в этом форуме.
Вы не можете отвечать в этом форуме.
Вы не можете удалять Ваши сообщения в этом форуме.
Вы не можете редактировать Ваши сообщения в этом форуме.
Вы не можете создавать опросы в этом форуме.
Вы не можете голосовать в этом форуме.