aboutsummaryrefslogtreecommitdiff
path: root/crypto/context.cc
blob: 84f717024ac6662d9fcbaac90c2a800a1441753f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
/*
 * Copyright 2019 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "crypto/context.h"

#include <math.h>

#include <algorithm>
#include <cmath>

#define GLOG_NO_ABBREVIATED_SEVERITIES
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "crypto/openssl_init.h"
#include "glog/logging.h"

namespace private_join_and_compute {

std::string OpenSSLErrorString() {
  char buf[256];
  ERR_error_string_n(ERR_get_error(), buf, sizeof(buf));
  return buf;
}

Context::Context()
    : bn_ctx_(CHECK_NOTNULL(BN_CTX_new())),
      evp_md_ctx_(CHECK_NOTNULL(EVP_MD_CTX_create())),
      zero_bn_(CreateBigNum(0)),
      one_bn_(CreateBigNum(1)),
      two_bn_(CreateBigNum(2)),
      three_bn_(CreateBigNum(3)) {
  OpenSSLInit();
  CHECK(RAND_status()) << "OpenSSL PRNG is not properly seeded.";
  HMAC_CTX_init(&hmac_ctx_);
}

Context::~Context() { HMAC_CTX_cleanup(&hmac_ctx_); }

BN_CTX* Context::GetBnCtx() { return bn_ctx_.get(); }

BigNum Context::CreateBigNum(absl::string_view bytes) {
  return BigNum(bn_ctx_.get(), bytes);
}

BigNum Context::CreateBigNum(uint64_t number) {
  return BigNum(bn_ctx_.get(), number);
}

BigNum Context::CreateBigNum(BigNum::BignumPtr bn) {
  return BigNum(bn_ctx_.get(), std::move(bn));
}

std::string Context::Sha256String(absl::string_view bytes) {
  unsigned char hash[EVP_MAX_MD_SIZE];
  CRYPTO_CHECK(1 ==
               EVP_DigestInit_ex(evp_md_ctx_.get(), EVP_sha256(), nullptr));
  CRYPTO_CHECK(
      1 == EVP_DigestUpdate(evp_md_ctx_.get(), bytes.data(), bytes.length()));
  unsigned int md_len;
  CRYPTO_CHECK(1 == EVP_DigestFinal_ex(evp_md_ctx_.get(), hash, &md_len));
  return std::string(reinterpret_cast<char*>(hash), md_len);
}

std::string Context::Sha512String(absl::string_view bytes) {
  unsigned char hash[EVP_MAX_MD_SIZE];
  CRYPTO_CHECK(1 ==
               EVP_DigestInit_ex(evp_md_ctx_.get(), EVP_sha512(), nullptr));
  CRYPTO_CHECK(
      1 == EVP_DigestUpdate(evp_md_ctx_.get(), bytes.data(), bytes.length()));
  unsigned int md_len;
  CRYPTO_CHECK(1 == EVP_DigestFinal_ex(evp_md_ctx_.get(), hash, &md_len));
  return std::string(reinterpret_cast<char*>(hash), md_len);
}

BigNum Context::RandomOracle(absl::string_view x, const BigNum& max_value,
                             RandomOracleHashType hash_type) {
  int hash_output_length = 256;
  if (hash_type == SHA512) {
    hash_output_length = 512;
  }
  int output_bit_length = max_value.BitLength() + hash_output_length;
  int iter_count =
      std::ceil(static_cast<float>(output_bit_length) / hash_output_length);
  CHECK(iter_count * hash_output_length < 130048)
      << "The domain bit length must not be greater than "
         "130048. Desired bit length: "
      << output_bit_length;
  int excess_bit_count = (iter_count * hash_output_length) - output_bit_length;
  BigNum hash_output = CreateBigNum(0);
  for (int i = 1; i < iter_count + 1; i++) {
    hash_output = hash_output.Lshift(hash_output_length);
    std::string bignum_bytes = absl::StrCat(CreateBigNum(i).ToBytes(), x);
    std::string hashed_string;
    if (hash_type == SHA512) {
      hashed_string = Sha512String(bignum_bytes);
    } else {
      hashed_string = Sha256String(bignum_bytes);
    }
    hash_output = hash_output + CreateBigNum(hashed_string);
  }
  return hash_output.Rshift(excess_bit_count).Mod(max_value);
}

BigNum Context::RandomOracleSha512(absl::string_view x,
                                   const BigNum& max_value) {
  return RandomOracle(x, max_value, SHA512);
}

BigNum Context::RandomOracleSha256(absl::string_view x,
                                   const BigNum& max_value) {
  return RandomOracle(x, max_value, SHA256);
}

BigNum Context::PRF(absl::string_view key, absl::string_view data,
                    const BigNum& max_value) {
  CHECK_GE(key.size() * 8, 80);
  CHECK_LE(max_value.BitLength(), 512)
      << "The requested output length is not supported. The maximum "
         "supported output length is 512. The requested output length is "
      << max_value.BitLength();
  CRYPTO_CHECK(1 == HMAC_Init_ex(&hmac_ctx_, key.data(), key.size(),
                                 EVP_sha512(), nullptr));
  CRYPTO_CHECK(1 ==
               HMAC_Update(&hmac_ctx_,
                           reinterpret_cast<const unsigned char*>(data.data()),
                           data.size()));
  unsigned int md_len;
  unsigned char hash[EVP_MAX_MD_SIZE];
  CRYPTO_CHECK(1 == HMAC_Final(&hmac_ctx_, hash, &md_len));
  BigNum hash_bn(bn_ctx_.get(), hash, md_len);
  BigNum hash_bn_reduced = hash_bn.GetLastNBits(max_value.BitLength());
  if (hash_bn_reduced < max_value) {
    return hash_bn_reduced;
  } else {
    return Context::PRF(key, hash_bn.ToBytes(), max_value);
  }
}

BigNum Context::GenerateSafePrime(int prime_length) {
  BigNum r(bn_ctx_.get());
  CRYPTO_CHECK(1 == BN_generate_prime_ex(r.bn_.get(), prime_length, 1, nullptr,
                                         nullptr, nullptr));
  return r;
}

BigNum Context::GeneratePrime(int prime_length) {
  BigNum r(bn_ctx_.get());
  CRYPTO_CHECK(1 == BN_generate_prime_ex(r.bn_.get(), prime_length, 0, nullptr,
                                         nullptr, nullptr));
  return r;
}

BigNum Context::GenerateRandLessThan(const BigNum& max_value) {
  BigNum r(bn_ctx_.get());
  CRYPTO_CHECK(1 == BN_rand_range(r.bn_.get(), max_value.bn_.get()));
  return r;
}

BigNum Context::GenerateRandBetween(const BigNum& start, const BigNum& end) {
  CHECK(start < end);
  return GenerateRandLessThan(end - start) + start;
}

std::string Context::GenerateRandomBytes(int num_bytes) {
  CHECK_GE(num_bytes, 0) << "num_bytes must be nonnegative, provided value was "
                         << num_bytes << ".";
  std::unique_ptr<unsigned char[]> bytes(new unsigned char[num_bytes]);
  CRYPTO_CHECK(1 == RAND_bytes(bytes.get(), num_bytes));
  return std::string(reinterpret_cast<char*>(bytes.get()), num_bytes);
}

BigNum Context::RelativelyPrimeRandomLessThan(const BigNum& num) {
  BigNum rand_num = GenerateRandLessThan(num);
  while (rand_num.Gcd(num) > One()) {
    rand_num = GenerateRandLessThan(num);
  }
  return rand_num;
}

}  // namespace private_join_and_compute