xrpld
Loading...
Searching...
No Matches
SecretKey.cpp
1#include <xrpl/protocol/SecretKey.h>
2
3#include <xrpl/basics/Buffer.h>
4#include <xrpl/basics/Slice.h>
5#include <xrpl/basics/base_uint.h>
6#include <xrpl/basics/contract.h>
7#include <xrpl/basics/strHex.h>
8#include <xrpl/beast/utility/rngfill.h>
9#include <xrpl/crypto/csprng.h>
10#include <xrpl/crypto/secure_erase.h>
11#include <xrpl/protocol/KeyType.h>
12#include <xrpl/protocol/PublicKey.h>
13#include <xrpl/protocol/Seed.h>
14#include <xrpl/protocol/detail/secp256k1.h>
15#include <xrpl/protocol/digest.h>
16#include <xrpl/protocol/tokens.h>
17
18#include <boost/utility/string_view.hpp>
19
20#include <ed25519.h>
21#include <secp256k1.h>
22
23#include <algorithm>
24#include <array>
25#include <cstdint>
26#include <cstring>
27#include <optional>
28#include <stdexcept>
29#include <utility>
30
31namespace xrpl {
32
37
39{
40 std::memcpy(buf_, key.data(), key.size());
41}
42
44{
45 if (slice.size() != sizeof(buf_))
46 logicError("SecretKey::SecretKey: invalid size");
47 std::memcpy(buf_, slice.data(), sizeof(buf_));
48}
49
52{
53 return strHex(*this);
54}
55
56namespace detail {
57
58void
60{
61 *out++ = v >> 24;
62 *out++ = (v >> 16) & 0xff;
63 *out++ = (v >> 8) & 0xff;
64 *out = v & 0xff;
65}
66
69{
70 // We fill this buffer with the seed and append a 32-bit "counter"
71 // that counts how many attempts we've had to make to generate a
72 // non-zero key that's less than the curve's order:
73 //
74 // 1 2
75 // 0 6 0
76 // buf |----------------|----|
77 // | seed | seq|
78
80 std::ranges::copy(seed, buf.begin());
81
82 // The odds that this loop executes more than once are negligible
83 // but *just* in case someone managed to generate a key that required
84 // more iterations loop a few times.
85 for (std::uint32_t seq = 0; seq != 128; ++seq)
86 {
87 copyUInt32(buf.data() + 16, seq);
88
89 auto const ret = sha512Half(buf);
90
91 if (secp256k1_ec_seckey_verify(secp256k1Context(), ret.data()) == 1)
92 {
93 secureErase(buf.data(), buf.size());
94 return ret;
95 }
96 }
97
98 Throw<std::runtime_error>("Unable to derive generator from seed");
99}
100
101//------------------------------------------------------------------------------
122{
123private:
126
127 [[nodiscard]] uint256
129 {
130 // We fill the buffer with the generator, the provided sequence
131 // and a 32-bit counter tracking the number of attempts we have
132 // already made looking for a non-zero key that's less than the
133 // curve's order:
134 // 3 3 4
135 // 0 pubGen 3 7 1
136 // buf |---------------------------------|----|----|
137 // | generator | seq| cnt|
138
141 copyUInt32(buf.data() + 33, seq);
142
143 // The odds that this loop executes more than once are negligible
144 // but we impose a maximum limit just in case.
145 for (std::uint32_t subseq = 0; subseq != 128; ++subseq)
146 {
147 copyUInt32(buf.data() + 37, subseq);
148
149 auto const ret = sha512HalfS(buf);
150
151 if (secp256k1_ec_seckey_verify(secp256k1Context(), ret.data()) == 1)
152 {
153 secureErase(buf.data(), buf.size());
154 return ret;
155 }
156 }
157
158 Throw<std::runtime_error>("Unable to derive generator from seed");
159 }
160
161public:
162 explicit Generator(Seed const& seed) : root_(deriveDeterministicRootKey(seed))
163 {
164 secp256k1_pubkey pubkey;
165 if (secp256k1_ec_pubkey_create(secp256k1Context(), &pubkey, root_.data()) != 1)
166 logicError("derivePublicKey: secp256k1_ec_pubkey_create failed");
167
168 auto len = generator_.size();
169
170 if (secp256k1_ec_pubkey_serialize(
171 secp256k1Context(), generator_.data(), &len, &pubkey, SECP256K1_EC_COMPRESSED) != 1)
172 logicError("derivePublicKey: secp256k1_ec_pubkey_serialize failed");
173 }
174
176 {
177 secureErase(root_.data(), root_.size());
178 secureErase(generator_.data(), generator_.size());
179 }
180
185 operator()(std::size_t ordinal) const
186 {
187 // Generates Nth secret key:
188 auto gsk = [this, tweak = calculateTweak(ordinal)]() {
189 auto rpk = root_;
190
191 if (secp256k1_ec_seckey_tweak_add(secp256k1Context(), rpk.data(), tweak.data()) == 1)
192 {
193 SecretKey const sk{Slice{rpk.data(), rpk.size()}};
194 secureErase(rpk.data(), rpk.size());
195 return sk;
196 }
197
198 logicError("Unable to add a tweak!");
199 }();
200
201 return {derivePublicKey(KeyType::Secp256k1, gsk), gsk};
202 }
203};
204
205} // namespace detail
206
207Buffer
208signDigest(PublicKey const& pk, SecretKey const& sk, uint256 const& digest)
209{
211 logicError("sign: secp256k1 required for digest signing");
212
213 BOOST_ASSERT(sk.size() == 32);
214 secp256k1_ecdsa_signature sigImp;
215 if (secp256k1_ecdsa_sign(
217 &sigImp,
218 reinterpret_cast<unsigned char const*>(digest.data()),
219 reinterpret_cast<unsigned char const*>(sk.data()),
220 secp256k1_nonce_function_rfc6979,
221 nullptr) != 1)
222 logicError("sign: secp256k1_ecdsa_sign failed");
223
224 unsigned char sig[72];
225 size_t len = sizeof(sig);
226 if (secp256k1_ecdsa_signature_serialize_der(secp256k1Context(), sig, &len, &sigImp) != 1)
227 logicError("sign: secp256k1_ecdsa_signature_serialize_der failed");
228
229 return Buffer{sig, len};
230}
231
232Buffer
233sign(PublicKey const& pk, SecretKey const& sk, Slice const& m)
234{
235 auto const type = publicKeyType(pk.slice());
236 if (!type)
237 logicError("sign: invalid type");
238 switch (*type)
239 {
240 case KeyType::Ed25519: {
241 Buffer b(64);
242 ed25519_sign(m.data(), m.size(), sk.data(), pk.data() + 1, b.data());
243 return b;
244 }
245 case KeyType::Secp256k1: {
247 h(m.data(), m.size());
249
250 secp256k1_ecdsa_signature sigImp;
251 if (secp256k1_ecdsa_sign(
253 &sigImp,
254 reinterpret_cast<unsigned char const*>(digest.data()),
255 reinterpret_cast<unsigned char const*>(sk.data()),
256 secp256k1_nonce_function_rfc6979,
257 nullptr) != 1)
258 logicError("sign: secp256k1_ecdsa_sign failed");
259
260 unsigned char sig[72];
261 size_t len = sizeof(sig);
262 if (secp256k1_ecdsa_signature_serialize_der(secp256k1Context(), sig, &len, &sigImp) !=
263 1)
264 logicError("sign: secp256k1_ecdsa_signature_serialize_der failed");
265
266 return Buffer{sig, len};
267 }
268 default:
269 logicError("sign: invalid type");
270 }
271}
272
273SecretKey
275{
276 std::uint8_t buf[32];
277 beast::rngfill(buf, sizeof(buf), cryptoPrng());
278 SecretKey const sk(Slice{buf, sizeof(buf)});
279 secureErase(buf, sizeof(buf));
280 return sk;
281}
282
283SecretKey
285{
286 if (type == KeyType::Ed25519)
287 {
288 auto key = sha512HalfS(Slice(seed.data(), seed.size()));
289 SecretKey const sk{Slice{key.data(), key.size()}};
290 secureErase(key.data(), key.size());
291 return sk;
292 }
293
294 if (type == KeyType::Secp256k1)
295 {
296 auto key = detail::deriveDeterministicRootKey(seed);
297 SecretKey const sk{Slice{key.data(), key.size()}};
298 secureErase(key.data(), key.size());
299 return sk;
300 }
301
302 logicError("generateSecretKey: unknown key type");
303}
304
305PublicKey
307{
308 switch (type)
309 {
310 case KeyType::Secp256k1: {
311 secp256k1_pubkey pubkeyImp;
312 if (secp256k1_ec_pubkey_create(
314 &pubkeyImp,
315 reinterpret_cast<unsigned char const*>(sk.data())) != 1)
316 logicError("derivePublicKey: secp256k1_ec_pubkey_create failed");
317
318 unsigned char pubkey[33];
319 std::size_t len = sizeof(pubkey);
320 if (secp256k1_ec_pubkey_serialize(
321 secp256k1Context(), pubkey, &len, &pubkeyImp, SECP256K1_EC_COMPRESSED) != 1)
322 logicError("derivePublicKey: secp256k1_ec_pubkey_serialize failed");
323
324 return PublicKey{Slice{pubkey, len}};
325 }
326 case KeyType::Ed25519: {
327 unsigned char buf[33];
328 buf[0] = 0xED;
329 ed25519_publickey(sk.data(), &buf[1]);
330 return PublicKey(Slice{buf, sizeof(buf)});
331 }
332 default:
333 logicError("derivePublicKey: bad key type");
334 };
335}
336
338generateKeyPair(KeyType type, Seed const& seed)
339{
340 switch (type)
341 {
342 case KeyType::Secp256k1: {
343 detail::Generator const g(seed);
344 return g(0);
345 }
346 default:
347 case KeyType::Ed25519: {
348 auto const sk = generateSecretKey(type, seed);
349 return {derivePublicKey(type, sk), sk};
350 }
351 }
352}
353
356{
357 auto const sk = randomSecretKey();
358 return {derivePublicKey(type, sk), sk};
359}
360
361template <>
364{
365 auto const result = decodeBase58Token(s, type);
366 if (result.empty())
367 return std::nullopt;
368 if (result.size() != 32)
369 return std::nullopt;
370 return SecretKey(makeSlice(result));
371}
372
373} // namespace xrpl
T begin(T... args)
Like std::vector<char> but better.
Definition Buffer.h:19
std::uint8_t const * data() const noexcept
Return a pointer to beginning of the storage.
Definition Buffer.h:148
A public key.
Definition PublicKey.h:53
std::uint8_t const * data() const noexcept
Definition PublicKey.h:79
Slice slice() const noexcept
Definition PublicKey.h:115
A secret key.
Definition SecretKey.h:24
std::size_t size() const
Definition SecretKey.h:56
std::uint8_t const * data() const
Definition SecretKey.h:50
SecretKey()=delete
std::uint8_t buf_[kSize]
Definition SecretKey.h:29
std::string toString() const
Convert the secret key to a hexadecimal string.
Definition SecretKey.cpp:51
Seeds are used to generate deterministic secret keys.
Definition Seed.h:19
std::size_t size() const
Definition Seed.h:53
std::uint8_t const * data() const
Definition Seed.h:47
An immutable linear range of bytes.
Definition Slice.h:28
std::uint8_t const * data() const noexcept
Return a pointer to beginning of the storage.
Definition Slice.h:88
std::size_t size() const noexcept
Returns the number of bytes in the storage.
Definition Slice.h:70
Produces a sequence of secp256k1 key pairs.
uint256 calculateTweak(std::uint32_t seq) const
std::pair< PublicKey, SecretKey > operator()(std::size_t ordinal) const
Generate the nth key pair.
Generator(Seed const &seed)
std::array< std::uint8_t, 33 > generator_
T copy(T... args)
T data(T... args)
T memcpy(T... args)
void rngfill(void *const buffer, std::size_t const bytes, Generator &g)
Definition rngfill.h:11
void copyUInt32(std::uint8_t *out, std::uint32_t v)
Definition SecretKey.cpp:59
uint256 deriveDeterministicRootKey(Seed const &seed)
Definition SecretKey.cpp:68
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
detail::BasicSha512HalfHasher< false > sha512_half_hasher
Definition digest.h:203
KeyType
Definition KeyType.h:8
std::pair< PublicKey, SecretKey > randomKeyPair(KeyType type)
Create a key pair using secure random numbers.
PublicKey derivePublicKey(KeyType type, SecretKey const &sk)
Derive the public key from a secret key.
static Hasher::result_type digest(void const *data, std::size_t size) noexcept
Definition tokens.cpp:140
void secureErase(void *dest, std::size_t bytes)
Attempts to clear the given blob of memory.
sha512_half_hasher::result_type sha512Half(Args const &... args)
Returns the SHA512-Half of a series of objects.
Definition digest.h:215
std::optional< AccountID > parseBase58(std::string const &s)
Parse AccountID from checked, base58 string.
std::string strHex(FwdIt begin, FwdIt end)
Definition strHex.h:13
sha512_half_hasher_s::result_type sha512HalfS(Args const &... args)
Returns the SHA512-Half of a series of objects.
Definition digest.h:232
CsprngEngine & cryptoPrng()
The default cryptographically secure PRNG.
SecretKey generateSecretKey(KeyType type, Seed const &seed)
Generate a new secret key deterministically.
std::pair< PublicKey, SecretKey > generateKeyPair(KeyType type, Seed const &seed)
Generate a key pair deterministically.
void logicError(std::string const &how) noexcept
Called when faulty logic causes a broken invariant.
std::optional< KeyType > publicKeyType(Slice const &slice)
Returns the type of public key.
Slice makeSlice(std::array< T, N > const &a)
Definition Slice.h:228
SecretKey randomSecretKey()
Create a secret key using secure random numbers.
secp256k1_context const * secp256k1Context()
Definition secp256k1.h:9
Buffer signDigest(PublicKey const &pk, SecretKey const &sk, uint256 const &digest)
Generate a signature for a message digest.
TokenType
Definition tokens.h:19
Buffer sign(PublicKey const &pk, SecretKey const &sk, Slice const &message)
Generate a signature for a message.
std::string decodeBase58Token(std::string const &s, TokenType type)
Definition tokens.cpp:191
BaseUInt< 256 > uint256
Definition base_uint.h:580
XRPL_NO_SANITIZE_ADDRESS void Throw(Args &&... args)
Definition contract.h:52
T size(T... args)