rsa.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #include "rsa.h"
  2. #include <library/cpp/openssl/big_integer/big_integer.h>
  3. #include <library/cpp/openssl/init/init.h>
  4. #include <util/generic/yexception.h>
  5. #include <util/generic/buffer.h>
  6. #include <openssl/bn.h>
  7. #include <openssl/rsa.h>
  8. using namespace NOpenSsl;
  9. using namespace NOpenSsl::NRsa;
  10. namespace {
  11. struct TInit {
  12. inline TInit() {
  13. InitOpenSSL();
  14. }
  15. } INIT;
  16. }
  17. TPublicKey::TPublicKey(const TBigInteger& e, const TBigInteger& n)
  18. : Key_(RSA_new())
  19. {
  20. Y_ENSURE(Key_, "RSA_new() failed");
  21. RSA_set0_key(Key_, BN_dup(n.Impl()), BN_dup(e.Impl()), nullptr);
  22. }
  23. TPublicKey::~TPublicKey() noexcept {
  24. RSA_free(Key_);
  25. }
  26. size_t TPublicKey::OutputLength() const noexcept {
  27. return RSA_size(Key_);
  28. }
  29. size_t TPublicKey::EncryptNoPad(void* dst, const void* src, size_t size) const {
  30. auto len = RSA_public_encrypt(size, (const ui8*)src, (ui8*)dst, Key_, RSA_NO_PADDING);
  31. Y_ENSURE(len >= 0, "RSA_public_encrypt() failed");
  32. return len;
  33. }
  34. TBigInteger TPublicKey::EncryptNoPad(const TBigInteger& src) const {
  35. const auto len1 = OutputLength();
  36. const auto len2 = src.NumBytes();
  37. TBuffer buf(len1 + len2);
  38. char* buf1 = (char*)buf.Data();
  39. char* buf2 = buf1 + len1;
  40. return TBigInteger::FromRegion(buf1, EncryptNoPad(buf1, buf2, src.ToRegion(buf2)));
  41. }