gpt4 book ai didi

c++ - 如何使用 Crypto++ 加密字节数组

转载 作者:太空狗 更新时间:2023-10-29 21:44:32 54 4
gpt4 key购买 nike

如何使用 Crypto++ 的 RSA 实现来加密字节数组?我已经找到了一个字符串的例子。但我找不到如何对字节数组执行相同操作的好示例。

这是我的第一次尝试:

//dataSize:     Size of data that is going to be send
//dataToSend Bytes to send to the user
//seedPool is an AutoSeededRandomPool

CryptoPP::RSAES_OAEP_SHA_Encryptor encryptor(publicKey);

int size = 64000;
byte * cipher = new byte(size);

CryptoPP::ArraySink* test = new CryptoPP::ArraySink(cipher, size);
CryptoPP::ArraySource as((byte*)dataToSend, dataSize, true, new CryptoPP::PK_EncryptorFilter(seedPool, encryptor, test));

int newDataSize = test->TotalPutLength();
unsigned int bytesSend = ::send(socketLink, (char *)(cipher), (int)newDataSize, 0);

delete[] cipher;

这行不通。 TotalPutLength 将始终返回 0,但有数据放入密码。

什么是安全的实现方式?我不想容易受到缓冲区溢出或任何其他攻击。

最佳答案

byte * cipher = new byte(size);

我认为这应该是:

byte * cipher = new byte[size];

否则,我认为您将一个字节初始化为 6400(截断为 0x00)。


CryptoPP::ArraySink * test = new CryptoPP::ArraySink(cipher, size);

这有点不同。如果你愿意,你可以远离内存管理器:

 CryptoPP::ArraySink test(cipher, size);

int newDataSize = test->TotalPutLength();

我从未使用过 TotalPutLength,而且我没有看到它记录在 BufferedTransformationSink 上。所以我真的没有任何关于它返回什么的建议。

TotalPutLength 可以使用。 ArraySink 可能会返回错误的值如果接收器已满。如果数组是固定的并且对于所有数据来说太小,就会发生这种情况。我们在 Crypto++ 5.6.3 或 5.6.4 中解决了这个问题。

如果你想计算处理的字节数(即使接收器不能存储它们的字节数),那么你也可以使用 MeterFilter :

byte data[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };

string encoded;
MeterFilter meter( new StringSink( encoded ) );

ArraySource( data, sizeof( data ), true,
new HexEncoder(
new Redirector( meter ),
true /*UCase*/, 2 /*Group*/,
" " /*Separator*/
)
);

cout << "processed " << meter.GetTotalBytes() << " bytes" << endl;
cout << encoded << endl;

输出:

Processed 23 bytes
00 01 02 03 04 05 06 07

How can you encrypt a byte array with Cryptopp RSA implementation

现在我们正在讨论 ;) 从 RSA Encryption 上的 Crypto++ wiki 试试这个.

////////////////////////////////////////////////
// Generate keys
AutoSeededRandomPool rng;

InvertibleRSAFunction params;
params.GenerateRandomWithKeySize( rng, 1536 );

RSA::PrivateKey privateKey( params );
RSA::PublicKey publicKey( params );

string plain="RSA Encryption", cipher, recovered;

////////////////////////////////////////////////
// Encryption
RSAES_OAEP_SHA_Encryptor e( publicKey );

StringSource ss1( plain, true,
new PK_EncryptorFilter( rng, e,
new StringSink( cipher )
) // PK_EncryptorFilter
); // StringSource

////////////////////////////////////////////////
// Decryption
RSAES_OAEP_SHA_Decryptor d( privateKey );

StringSource ss2( cipher, true,
new PK_DecryptorFilter( rng, d,
new StringSink( recovered )
) // PK_DecryptorFilter
); // StringSource

assert( plain == recovered );

关于c++ - 如何使用 Crypto++ 加密字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19814236/

54 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com