Я использую Crypto ++ для шифрования массива байтов с использованием RSA. Я следовал за примерами Crypto ++ wiki, но мне не повезло заставить их работать. Шифрование и дешифрование во всех примерах выполняется в рамках одного процесса, но я пытаюсь расшифровать контент, который уже зашифрован в другом процессе.
Вот мой код:
class FixedRNG : public CryptoPP::RandomNumberGenerator
{
public:
FixedRNG(CryptoPP::BufferedTransformation &source) : m_source(source) {}
void GenerateBlock(byte *output, size_t size)
{
m_source.Get(output, size);
}
private:
CryptoPP::BufferedTransformation &m_source;
};uint16_t Encrypt()
{
byte *oaepSeed = new byte[2048];
for (int i = 0; i < 2048; i++)
{
oaepSeed[i] = (byte)i;
}
CryptoPP::ByteQueue bq;
bq.Put(oaepSeed, 2048);
FixedRNG prng(bq);
Integer n("Value of N"),
e("11H"),
d("Value of D");
RSA::PrivateKey privKey;
privKey.Initialize(n, e, d);
RSA::PublicKey pubKey(privKey);
CryptoPP::RSAES_OAEP_SHA_Encryptor encryptor( pubKey );
assert( 0 != encryptor.FixedMaxPlaintextLength() );
byte blockSize = encryptor.FixedMaxPlaintextLength();
int divisionCount = fileSize / blockSize;
int proccessedBytes = 0;
// Create cipher text space
uint16_t cipherSize = encryptor.CiphertextLength( blockSize );
assert( 0 != cipherSize );
encryptor.Encrypt(prng, (byte*)plaintext, blockSize, (byte*)output);
return cipherSize;
}
void Decrypt(uint16_t cipherSize)
{
byte *oaepSeed = new byte[2048];
for (int i = 0; i < 2048; i++)
{
oaepSeed[i] = (byte)i;
}
CryptoPP::ByteQueue bq;
bq.Put(oaepSeed, 2048);
FixedRNG prng(bq);
Integer n("Value of N"),
e("11H"),
d("Value of D");
RSA::PrivateKey privKey;
privKey.Initialize(n, e, d);
//RSA::PublicKey pubKey(privKey);
CryptoPP::RSAES_OAEP_SHA_Decryptor decryptor( privKey );
byte blockSize = decryptor.FixedMaxPlaintextLength();
assert(blockSize != 0);
size_t maxPlainTextSize = decryptor.MaxPlaintextLength( cipherSize );
assert( 0 != maxPlainTextSize );
void* subBuffer = malloc(maxPlainTextSize);
CryptoPP::DecodingResult result = decryptor.Decrypt(prng, (byte*)cipherText, cipherSize, (byte*)subBuffer);
assert( result.isValidCoding );
assert( result.messageLength <= maxPlainTextSize );
}
К сожалению, значение isValidCoding равно false. Я думаю, что я неправильно понимаю что-то о шифровании / дешифровании RSA !!
Обратите внимание, что privKey и pubKey были проверены с использованием KEY.Validate (prng, 3).
Я также попытался использовать RAW RSA вместо OAEP и SHA, но безуспешно. Я пытался отлаживать с помощью кода crypto ++, что я подозрительно ПСЧ переменная. Я думаю, что-то не так с этим. Я также использовал AutoSeededRandomPool вместо FixedRNG, но это не помогло.
Стоит знать, что, если я скопирую код дешифрования сразу после кода шифрования и выполню его в методе Encrypt (), все в порядке, и isValidCoding верен !!
Это, вероятно, не правильно
byte blockSize = encryptor.FixedMaxPlaintextLength();
...
encryptor.Encrypt(prng, (byte*)plaintext, blockSize, (byte*)output);
return cipherSize;
Пытаться:
size_t maxLength = encryptor.FixedMaxPlaintextLength();
size_t cipherLength = encryptor.CiphertextLength( blockSize );
...
SecureByteBlock secBlock(cipherLength);
cipherLength = encryptor.Encrypt(prng, (byte*)plaintext, blockSize, secBlock);
secBlock.resize(cipherLength);
FixedMaxPlaintextLength
возвращает size_t
не byte
,
Вы, вероятно, должны звонить CiphertextLength
на plaintext
,
Я не совсем уверен, как вы только что вернули uint_t
от encrypt()
,
Вы могли бы сделать лучше, начав заново, и используя пример из Crypto ++ в качестве отправной точки. Я не уверен, что этот дизайн стоит того.
Если вы начнете все сначала, то схема интегрированного шифрования Shoup Elliptic Curve (ECIES) будет хорошим выбором, поскольку она объединяет открытый ключ с симметричными шифрами и тегами аутентификации.
Других решений пока нет …