Ограничение фиксированной длины открытого текста cryptopp

StackOverflow https://stackoverflow.com//questions/25070949

  •  26-12-2019
  •  | 
  •  

Вопрос

Когда я пройду initialText86, приведенный ниже код работает так, как должен.Когда я пройду initialText87 он не может построить StringSource ss1, и мы встречаем исключение invalid argument!

Как я могу закодировать строку длиной 87?

#include <string>
#include <new>

using namespace std;

#include <../pub/cryptopp/rsa.h>
#include <../pub/cryptopp/osrng.h>
#include <../pub/cryptopp/oaep.h>
#include <../pub/cryptopp/sha.h>

using namespace CryptoPP;

AutoSeededRandomPool& rng_get() {
    static AutoSeededRandomPool defRng;
    return defRng;
}

string rsa_encode( const string& plainText, const RSA::PublicKey& pubKey ) {
    RSAES_OAEP_SHA_Encryptor rsaEnc( pubKey );
    string cipherText;
    StringSource ss1( reinterpret_cast< const byte* >( plainText.c_str() ), plainText.size(), true,
        new PK_EncryptorFilter( rng_get(), rsaEnc,
            new StringSink( cipherText )
        ) // PK_EncryptorFilter
    ); // StringSource
    return move( cipherText );
}

string rsa_decode( const string& cipherText, const RSA::PrivateKey& secretKey ) {
    RSAES_OAEP_SHA_Decryptor rsaDec( secretKey );
    string plainText;
    StringSource ss2( reinterpret_cast< const byte* >( cipherText.c_str() ), cipherText.size(), true,
        new PK_DecryptorFilter( rng_get(), rsaDec,
            new StringSink( plainText )
        ) // PK_DecryptorFilter
    ); // StringSource
    return move( plainText );
}

static const size_t keyLength = 1024;
RSA::PrivateKey _secretKey;
RSA::PublicKey  _pubKey;

bool test( const string& initialText ) {
    auto cipherText = rsa_encode( initialText, _pubKey );
    auto plainText = rsa_decode( cipherText, _secretKey );
    return plainText == initialText;
}

int main() {
    _secretKey.GenerateRandomWithKeySize(rng_get(), keyLength );
    new( &_pubKey ) RSA::PublicKey( _secretKey );
    string initialText87 = "111111111111111111111111111111111111111111111111111111111111111111111111111111111111111";
    string initialText86 = "11111111111111111111111111111111111111111111111111111111111111111111111111111111111111";
    auto testResult = test( initialText87 );
    assert( testResult );
    return testResult ? 0 : -1;
}
Это было полезно?

Решение

Длина данных, которые можно зашифровать с помощью RSA, определяется в первую очередь размером используемого вами ключа.Судя по всему, вы используете OAEP, поэтому максимальная длина:

keyLength - 2 - 2 * hashLength

Где keyLength — длина модуля RSA в байтах.Вы используете 1024-битный ключ, поэтому:

keyLength = 1024 / 8 = 128

И поскольку вы используете OAEP с SHA-1

hashLength = 20

Таким образом, максимум, который вы можете зашифровать, это:

128 - 2 - 2 * 20 = 86

Именно это и показывает ваш пример.

Чтобы зашифровать больше данных, вы мог используйте больший ключ RSA, но RSA на самом деле не следует использовать для шифрования больших объемов данных, поэтому обычно он используется как часть гибридной криптосистемы, где RSA вместо этого используется для шифрования случайно сгенерированного ключа для симметричного алгоритма, такого как AES, и затем симметричный алгоритм используется для шифрования фактических данных, что позволяет избежать ограничений длины, связанных с RSA.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top