Supoort BigNum::{from,to}_le_binary for OpenSSL < 1.1.0.

GitOrigin-RevId: c104af3f22c814df6946a9218c83cae015823832
This commit is contained in:
levlam 2019-08-22 19:22:31 +03:00
parent e1046570a3
commit 72ce03b84b
3 changed files with 23 additions and 6 deletions

View File

@ -89,8 +89,9 @@ BigNum BigNum::from_le_binary(Slice str) {
#if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
return BigNum(make_unique<Impl>(BN_lebin2bn(str.ubegin(), narrow_cast<int>(str.size()), nullptr)));
#else
LOG(FATAL) << "Unsupported from_le_binary";
return BigNum();
string str_copy = str.str();
std::reverse(str_copy.begin(), str_copy.end());
return from_binary(str_copy);
#endif
}
@ -216,8 +217,9 @@ string BigNum::to_le_binary(int exact_size) const {
BN_bn2lebinpad(impl_->big_num, MutableSlice(res).ubegin(), exact_size);
return res;
#else
LOG(FATAL) << "Unsupported to_le_binary";
return "";
string result = to_binary(exact_size);
std::reverse(result.begin(), result.end());
return result;
#endif
}

View File

@ -43,7 +43,6 @@ class BigNum {
static BigNum from_binary(Slice str);
// Available only if OpenSSL >= 1.1.0
static BigNum from_le_binary(Slice str);
static Result<BigNum> from_decimal(CSlice str);
@ -72,7 +71,6 @@ class BigNum {
string to_binary(int exact_size = -1) const;
// Available only if OpenSSL >= 1.1.0
string to_le_binary(int exact_size = -1) const;
string to_decimal() const;

View File

@ -454,6 +454,23 @@ TEST(BigNum, from_decimal) {
ASSERT_TRUE(BigNum::from_decimal("999999999999999999999999999999999999999999999999").is_ok());
}
TEST(BigNum, from_binary) {
ASSERT_STREQ(BigNum::from_binary("").to_decimal(), "0");
ASSERT_STREQ(BigNum::from_binary("a").to_decimal(), "97");
ASSERT_STREQ(BigNum::from_binary("\x00\xff").to_decimal(), "255");
ASSERT_STREQ(BigNum::from_le_binary("").to_decimal(), "0");
ASSERT_STREQ(BigNum::from_le_binary("a").to_decimal(), "97");
ASSERT_STREQ(BigNum::from_le_binary("\x00\xff").to_decimal(), "65280");
ASSERT_STREQ(BigNum::from_decimal("255").move_as_ok().to_binary(), "\xff");
ASSERT_STREQ(BigNum::from_decimal("255").move_as_ok().to_le_binary(), "\xff");
ASSERT_STREQ(BigNum::from_decimal("255").move_as_ok().to_binary(2), "\x00\xff");
ASSERT_STREQ(BigNum::from_decimal("255").move_as_ok().to_le_binary(2), "\xff\x00");
ASSERT_STREQ(BigNum::from_decimal("65280").move_as_ok().to_binary(), "\xff\x00");
ASSERT_STREQ(BigNum::from_decimal("65280").move_as_ok().to_le_binary(), "\x00\xff");
ASSERT_STREQ(BigNum::from_decimal("65280").move_as_ok().to_binary(2), "\xff\x00");
ASSERT_STREQ(BigNum::from_decimal("65280").move_as_ok().to_le_binary(2), "\x00\xff");
}
static void test_get_ipv4(uint32 ip) {
td::IPAddress ip_address;
ip_address.init_ipv4_port(td::IPAddress::ipv4_to_str(ip), 80).ensure();