1
0

Make RSA::encrypt safe.

GitOrigin-RevId: 0d83acb2f6c022af59320c3ea755257cd926cbe4
This commit is contained in:
levlam 2020-02-13 03:49:59 +03:00
parent fa457236e0
commit b7af94e2e4
3 changed files with 6 additions and 3 deletions

View File

@ -109,7 +109,8 @@ Status AuthKeyHandshake::on_res_pq(Slice message, Callback *connection, PublicRs
// encrypted_data := RSA (data_with_hash, server_public_key); a 255-byte long number (big endian) // encrypted_data := RSA (data_with_hash, server_public_key); a 255-byte long number (big endian)
// is raised to the requisite power over the requisite modulus, and the result is stored as a 256-byte number. // is raised to the requisite power over the requisite modulus, and the result is stored as a 256-byte number.
string encrypted_data(256, 0); string encrypted_data(256, 0);
rsa.encrypt(data_with_hash, size, reinterpret_cast<unsigned char *>(&encrypted_data[0])); rsa.encrypt(data_with_hash, size, sizeof(data_with_hash), reinterpret_cast<unsigned char *>(&encrypted_data[0]),
encrypted_data.size());
// req_DH_params#d712e4be nonce:int128 server_nonce:int128 p:string q:string public_key_fingerprint:long // req_DH_params#d712e4be nonce:int128 server_nonce:int128 p:string q:string public_key_fingerprint:long
// encrypted_data:string = Server_DH_Params // encrypted_data:string = Server_DH_Params

View File

@ -95,13 +95,15 @@ size_t RSA::size() const {
return 256; return 256;
} }
size_t RSA::encrypt(unsigned char *from, size_t from_len, unsigned char *to) const { size_t RSA::encrypt(unsigned char *from, size_t from_len, size_t max_from_len, unsigned char *to, size_t to_len) const {
CHECK(from_len > 0 && from_len <= 2550); CHECK(from_len > 0 && from_len <= 2550);
size_t pad = (25500 - from_len - 32) % 255 + 32; size_t pad = (25500 - from_len - 32) % 255 + 32;
size_t chunks = (from_len + pad) / 255; size_t chunks = (from_len + pad) / 255;
int bits = n_.get_num_bits(); int bits = n_.get_num_bits();
CHECK(bits >= 2041 && bits <= 2048); CHECK(bits >= 2041 && bits <= 2048);
CHECK(chunks * 255 == from_len + pad); CHECK(chunks * 255 == from_len + pad);
CHECK(from_len + pad <= max_from_len);
CHECK(chunks * 256 <= to_len);
Random::secure_bytes(from + from_len, pad); Random::secure_bytes(from + from_len, pad);
BigNumContext ctx; BigNumContext ctx;

View File

@ -21,7 +21,7 @@ class RSA {
RSA clone() const; RSA clone() const;
int64 get_fingerprint() const; int64 get_fingerprint() const;
size_t size() const; size_t size() const;
size_t encrypt(unsigned char *from, size_t from_len, unsigned char *to) const; size_t encrypt(unsigned char *from, size_t from_len, size_t max_from_len, unsigned char *to, size_t to_len) const;
void decrypt(Slice from, MutableSlice to) const; void decrypt(Slice from, MutableSlice to) const;