37 #include <boost/test/unit_test.hpp> 49 BOOST_AUTO_TEST_SUITE(Crypto)
58 static
CryptoPP::AutoSeededRandomPool& rng()
60 static CryptoPP::AutoSeededRandomPool s_rng;
64 static CryptoPP::OID& curveOID()
66 static CryptoPP::OID s_curveOID(CryptoPP::ASN1::secp256k1());
70 static CryptoPP::DL_GroupParameters_EC<CryptoPP::ECP>& params()
72 static CryptoPP::DL_GroupParameters_EC<CryptoPP::ECP> s_params(curveOID());
78 BOOST_REQUIRE_EQUAL(
sha3(
""),
h256(
"c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"));
79 BOOST_REQUIRE_EQUAL(
sha3(
"hello"),
h256(
"1c8aff950685c2ed4bc3174f3472287b56d9517b9c948127319a09a7a36deac8"));
84 h256 emptySHA3(
fromHex(
"c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"));
85 BOOST_REQUIRE_EQUAL(emptySHA3,
EmptySHA3);
87 h256 emptyListSHA3(
fromHex(
"1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"));
94 BOOST_REQUIRE_EQUAL(pub,
Public{});
100 BOOST_REQUIRE(!!k.
secret());
101 BOOST_REQUIRE(!!k.
pub());
109 BOOST_REQUIRE(p.
pub() ==
Public(
fromHex(
"97466f2b32bc3bb76d4741ae51cd1d8578b48d3f1e68da206d47321aec267ce78549b514e4453d74ef11b0cd5e4e4c364effddac8b51bcfc8de80682f952896f")));
113 auto expectedRlp =
"dc80808094944400f4b88ac9589a0f17ed4671da26bddb668b8203e880";
116 auto expectedRlp2 =
"f85f80808094944400f4b88ac9589a0f17ed4671da26bddb668b8203e8801ca0bd2402a510c9c9afddf2a3f63c869573bd257475bea91d6f164638134a3386d6a0609ad9775fd2715e6a359c627e9338478e4adba65dd0dc6ef2bcbe6398378984";
123 auto keyPair = KeyPair::create();
134 auto msg =
sha3(
"msg");
135 auto sig =
sign(sec, msg);
136 auto expectedSig =
"b826808a8c41e00b7c5d71f211f005a84a7b97949d5e765831e1da4e34c9b8295d2a622eee50f25af78241c1cb7cfff11bcf2a13fe65dee1e3b86fd79a4e3ed000";
140 auto expectedPub =
"e40930c838d6cca526795596e368d16083f0672f4ab61788277abfa23c3740e1cc84453b0b24f49086feba0bd978bb4446bae8dff1e79fcc1e9cf482ec2d07c3";
147 auto msg = h256::random();
151 auto kp = KeyPair::create();
152 auto sig =
sign(kp.secret(), msg);
163 s_secp256k1->decrypt(k.
secret(), io_text);
164 BOOST_REQUIRE_EQUAL(io_text.size(), 0);
171 BOOST_REQUIRE(!kNot.
address());
173 BOOST_REQUIRE(k.address());
178 string message(
"Now is the time for all good persons to come to the aid of humanity.");
185 BOOST_REQUIRE(cipher !=
asBytes(message) && cipher.size() > 0);
190 BOOST_REQUIRE(
asString(plain) == message);
191 BOOST_REQUIRE(plain ==
asBytes(message));
198 ctx.Update(input.data(), 4);
200 bytes interimDigest(32);
201 ctx.Final(interimDigest.data());
202 ctx.Update(input.data(), 4);
203 bytes firstDigest(32);
204 ctx.Final(firstDigest.data());
205 BOOST_REQUIRE(interimDigest == firstDigest);
207 ctxCopy.Update(input.data(), 4);
208 bytes finalDigest(32);
209 ctxCopy.Final(interimDigest.data());
210 BOOST_REQUIRE(interimDigest != finalDigest);
213 ctxCopy.Update(input.data(), 4);
214 ctxCopy.Update(input.data(), 4);
216 bytes finalDigest2(32);
217 finalCtx.Final(finalDigest2.data());
218 BOOST_REQUIRE(finalDigest2 == interimDigest);
219 ctxCopy.Update(input.data(), 4);
220 bytes finalDigest3(32);
221 finalCtx.Final(finalDigest3.data());
222 BOOST_REQUIRE(finalDigest2 != finalDigest3);
227 KeyPair local = KeyPair::create();
228 KeyPair remote = KeyPair::create();
232 auto key1 = s_secp256k1->eciesKDF(z1,
bytes(), 64);
239 auto key2 = s_secp256k1->eciesKDF(z2,
bytes(), 64);
248 BOOST_REQUIRE(z1 == z2);
250 BOOST_REQUIRE(key1.size() > 0 && ((
u512)
h512(key1)) > 0);
251 BOOST_REQUIRE(key1 == key2);
258 string message(
"Now is the time for all good persons to come to the aid of humanity.");
259 string original = message;
262 s_secp256k1->encryptECIES(k.
pub(),
b);
263 BOOST_REQUIRE(b !=
asBytes(original));
264 BOOST_REQUIRE(b.size() > 0 && b[0] == 0x04);
266 s_secp256k1->decryptECIES(k.
secret(),
b);
274 string message(
"Now is the time for all good persons to come to the aid of humanity.");
275 string original = message;
278 string shared(
"shared MAC data");
279 string wrongShared(
"wrong shared MAC data");
281 s_secp256k1->encryptECIES(k.
pub(), shared,
b);
282 BOOST_REQUIRE(b !=
asBytes(original));
283 BOOST_REQUIRE(b.size() > 0 && b[0] == 0x04);
285 BOOST_REQUIRE(!s_secp256k1->decryptECIES(k.
secret(), wrongShared,
b));
287 s_secp256k1->decryptECIES(k.
secret(), shared,
b);
291 #if !defined(DISABLE_BROKEN_UNIT_TESTS_UNTIL_WE_FIX_THEM) 293 #endif // !defined(DISABLE_BROKEN_UNIT_TESTS_UNTIL_WE_FIX_THEM) 300 string message(
"Now is the time for all good persons to come to the aid of humanity.");
301 string original = message;
304 s_secp256k1->encrypt(k.
pub(),
b);
305 BOOST_REQUIRE(b !=
asBytes(original));
307 s_secp256k1->decrypt(k.
secret(),
b);
308 BOOST_REQUIRE(b ==
asBytes(original));
329 assert(dhLocal.
Agree(sharedLocal, privLocal, pubRemote));
333 assert(dhRemote.
Agree(sharedRemote, privRemote, pubLocal));
337 ssLocal.
Decode(sharedLocal.BytePtr(), sharedLocal.SizeInBytes());
338 ssRemote.Decode(sharedRemote.BytePtr(), sharedRemote.SizeInBytes());
341 assert(ssLocal == ssRemote);
346 byte puba[65] = {0x04};
350 byte pubb[65] = {0x04};
351 memcpy(&pubb[1], b.pub().data(), 64);
356 BOOST_REQUIRE(shared);
373 BOOST_REQUIRE(sremote);
374 BOOST_REQUIRE(slocal);
385 auto expectedSharedSec =
"8ac7e464348b85d9fdfc0a81f2fdc0bbbb8ee5fb3840de6ed60ad9372e718977";
398 BOOST_REQUIRE(nodeA.
pub());
403 BOOST_REQUIRE(nodeB.
pub());
420 sign(eA.seckey(), (ssA ^ nonceA).makeInsecure()).
ref().copyTo(sig);
421 sha3(eA.pubkey().ref(), hepubk);
424 auth[auth.size() - 1] = 0x0;
428 BOOST_REQUIRE_EQUAL(authcipher.size(), 279);
447 eB.pubkey().ref().copyTo(epubk);
449 auth[auth.size() - 1] = 0x0;
453 BOOST_REQUIRE_EQUAL(ackcipher.size(), 182);
455 BOOST_REQUIRE(eA.pubkey());
456 BOOST_REQUIRE(eB.pubkey());
457 BOOST_REQUIRE_NE(eA.seckey(), eB.seckey());
467 BOOST_REQUIRE(ackdecrypted.size());
473 BOOST_REQUIRE_EQUAL(eBAck, eB.pubkey());
474 BOOST_REQUIRE_EQUAL(nonceBAck, nonceB);
478 bytes keyMaterialBytes(512);
479 bytesRef keyMaterial(&keyMaterialBytes);
483 eA.agree(eBAck, ess);
491 keyMaterialBytes.resize(
h256::size + authcipher.size());
492 keyMaterial.
retarget(keyMaterialBytes.data(), keyMaterialBytes.size());
493 (aMacK ^ nonceBAck).
ref().copyTo(keyMaterial);
497 keyMaterialBytes.resize(
h256::size + ackcipher.size());
498 keyMaterial.
retarget(keyMaterialBytes.data(), keyMaterialBytes.size());
499 (aMacK ^ nonceA).
ref().copyTo(keyMaterial);
508 BOOST_REQUIRE_EQUAL(ssA, ssB);
517 BOOST_REQUIRE(authdecrypted.size());
531 BOOST_REQUIRE(nonceAAuth);
532 BOOST_REQUIRE_EQUAL(nonceA, nonceAAuth);
533 BOOST_REQUIRE(nodeAAuth);
534 BOOST_REQUIRE_EQUAL(nodeA.
pub(), nodeAAuth);
540 eAAuth =
recover(sigAuth, (ss ^ nonceAAuth).makeInsecure());
542 BOOST_REQUIRE_EQUAL(heA,
sha3(eAAuth));
543 BOOST_REQUIRE_EQUAL(eAAuth, eA.pubkey());
545 bytes keyMaterialBytes(512);
546 bytesRef keyMaterial(&keyMaterialBytes);
550 eB.agree(eAAuth, ess);
560 keyMaterialBytes.resize(
h256::size + ackcipher.size());
561 keyMaterial.
retarget(keyMaterialBytes.data(), keyMaterialBytes.size());
562 (bMacK ^ nonceAAuth).
ref().copyTo(keyMaterial);
566 keyMaterialBytes.resize(
h256::size + authcipher.size());
567 keyMaterial.
retarget(keyMaterialBytes.data(), keyMaterialBytes.size());
568 (bMacK ^ nonceB).
ref().copyTo(keyMaterial);
573 BOOST_REQUIRE_EQUAL(aEncryptK, bEncryptK);
574 BOOST_REQUIRE_EQUAL(aMacK, bMacK);
575 BOOST_REQUIRE_EQUAL(aEgressMac, bIngressMac);
576 BOOST_REQUIRE_EQUAL(bEgressMac, aIngressMac);
587 bytes magic {0x22,0x40,0x08,0x91};
588 bytes magicCipherAndMac;
591 magicCipherAndMac.resize(magicCipherAndMac.size() + 32);
593 egressMac.
ref().
copyTo(
bytesRef(&magicCipherAndMac).cropped(magicCipherAndMac.size() - 32, 32));
595 bytesConstRef cipher(&magicCipherAndMac[0], magicCipherAndMac.size() - 32);
598 plaintext.resize(magic.size());
600 BOOST_REQUIRE(plaintext.size() > 0);
601 BOOST_REQUIRE(magic == plaintext);
607 string m =
"AAAAAAAAAAAAAAAA";
615 BOOST_REQUIRE_EQUAL(
asString(plaintext), m);
620 const int aesKeyLen = 16;
621 BOOST_REQUIRE(
sizeof(
char) ==
sizeof(
byte));
624 AutoSeededRandomPool rng;
626 rng.GenerateBlock(key, key.
size());
630 rng.GenerateBlock(ctr.
data(),
sizeof(ctr));
635 string text =
"Now is the time for all good persons to come to the aid of humanity.";
636 unsigned char const* in = (
unsigned char*)&text[0];
637 unsigned char* out = (
unsigned char*)&text[0];
638 string original = text;
639 string doublespeak = text + text;
645 e.SetKeyWithIV(key, key.
size(), ctr.
data());
648 e.ProcessData(out, in, text.size());
649 ctr =
h128(
u128(ctr) + text.size() / 16);
651 BOOST_REQUIRE(text != original);
654 catch (CryptoPP::Exception& _e)
656 cerr << _e.what() << endl;
662 d.SetKeyWithIV(key, key.
size(), ctrcopy.
data());
663 d.ProcessData(out, in, text.size());
664 BOOST_REQUIRE(text == original);
666 catch (CryptoPP::Exception& _e)
668 cerr << _e.what() << endl;
675 BOOST_REQUIRE(cipherCopy != text);
676 in = (
unsigned char*)&cipherCopy[0];
677 out = (
unsigned char*)&cipherCopy[0];
680 e.SetKeyWithIV(key, key.
size(), ctrcopy.
data());
681 e.ProcessData(out, in, text.size());
684 BOOST_REQUIRE(cipherCopy == original);
686 catch (CryptoPP::Exception& _e)
688 cerr << _e.what() << endl;
695 const int aesKeyLen = 16;
696 BOOST_REQUIRE(
sizeof(
char) ==
sizeof(
byte));
698 AutoSeededRandomPool rng;
700 rng.GenerateBlock(key, key.
size());
703 byte iv[AES::BLOCKSIZE];
704 rng.GenerateBlock(iv, AES::BLOCKSIZE);
706 string string128(
"AAAAAAAAAAAAAAAA");
707 string plainOriginal = string128;
709 CryptoPP::CBC_Mode<Rijndael>::Encryption cbcEncryption(key, key.
size(), iv);
710 cbcEncryption.ProcessData((
byte*)&string128[0], (
byte*)&string128[0], string128.size());
711 BOOST_REQUIRE(string128 != plainOriginal);
714 cbcDecryption.ProcessData((
byte*)&string128[0], (
byte*)&string128[0], string128.size());
715 BOOST_REQUIRE(plainOriginal == string128);
719 string string192(
"AAAAAAAAAAAAAAAABBBBBBBB");
720 plainOriginal = string192;
725 BOOST_REQUIRE(cipher.size() == 32);
727 byte* pOut =
reinterpret_cast<byte*
>(&string192[0]);
728 byte const* pIn =
reinterpret_cast<byte const*
>(cipher.data());
729 cbcDecryption.ProcessData(pOut, pIn, cipher.size());
730 BOOST_REQUIRE(string192 == plainOriginal);
745 while (
sha3(&e, &e), secret =
sha3(secret), tests--)
754 Integer kInt(k.asBytes().data(), 32);
755 kInt %= params().GetSubgroupOrder()-1;
757 ECP::Point rp = params().ExponentiateBase(kInt);
758 Integer const& q = params().GetGroupOrder();
759 Integer r = params().ConvertElementToInteger(rp);
763 BOOST_REQUIRE(!!r && !!s);
766 for (
size_t i = 0; i < 10; i++)
774 size_t expectI = rp.
y.
IsOdd() ? 1 : 0;
776 BOOST_REQUIRE(p == pkey);
778 BOOST_REQUIRE(p != pkey);
Append input to a string object.
Adapted from code found on http://stackoverflow.com/questions/180947/base64-decode-snippet-in-c Origi...
std::string toHex(T const &_data, int _w=2, HexPrefix _prefix=HexPrefix::DontAdd)
vector_ref< _T const > ref(_T const &_t)
Elliptical Curve Point over GF(p), where p is prime.
void Encode(byte *output, size_t outputLen, Signedness sign=UNSIGNED) const
Encode in big-endian format.
byte const * data() const
Class file for modes of operation.
bool IsOdd() const
Determines if the Integer is odd parity.
CryptoPP secp256k1 algorithms.
bytes rlp(_T _t)
Export a single item in RLP format, returning a byte array.
bytesSec decryptSymNoAuth(SecureFixedHash< 16 > const &_k, h128 const &_iv, bytesConstRef _cipher)
Decrypts payload with specified IV/ctr using AES128-CTR.
bool verify(Public const &_k, Signature const &_s, h256 const &_hash)
Verify signature.
Simple class that represents a "key pair".
#define SECP256K1_CONTEXT_NONE
Classes for Keccak message digests.
h160 Address
An Ethereum address: 20 bytes.
SecureFixedHash< 32 > sha3Secure(bytesConstRef _input)
size_type size() const
Provides the count of elements in the SecBlock.
std::pair< bytes, h128 > encryptSymNoAuth(SecureFixedHash< 16 > const &_k, bytesConstRef _plain)
Encrypts payload with random IV/ctr using AES128-CTR.
ASN.1 object identifiers for algorthms and schemes.
SecureFixedHash< 32 > Secret
std::hash for asio::adress
assert(len-trim+(2 *lenIndices)<=WIDTH)
Secret const & secret() const
std::vector< T > const & makeInsecure() const
vector_ref< _T > cropped(size_t _begin, size_t _count) const
void agree(Public const &_remoteEphemeral, Secret &o_sharedSecret) const
Input public key for dh agreement, output generated shared secret.
h512 Public
A public key: 64 bytes.
Public pubkey()
Public key sent to remote.
BOOST_AUTO_TEST_CASE(sha3general)
unsigned int PublicKeyLength() const
Provides the size of the public key.
SECP256K1_API void secp256k1_context_destroy(secp256k1_context *ctx)
Destroy a secp256k1 context object.
unsigned int AgreedValueLength() const
Provides the size of the agreed value.
void retarget(_T *_d, size_t _s)
Public toPublic(Secret const &_secret)
Convert a secret key into the public key equivalent.
Do not include a signature.
bytesConstRef ref() const
bytes fromHex(std::string const &_s, WhenError _throw=WhenError::DontThrow)
Public const & pub() const
Retrieve the public key.
vector_ref< byte > bytesRef
virtual void GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
Generate a private/public key pair.
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_seckey_verify(const secp256k1_context *ctx, const unsigned char *seckey) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2)
Verify an ECDSA secret key.
Block cipher mode of operation aggregate.
FixedHash< T > const & makeInsecure() const
bool Agree(byte *agreedValue, const byte *privateKey, const byte *otherPublicKey, bool validateOtherPublicKey=true) const
Derive agreed value.
Public recover(Signature const &_sig, h256 const &_hash)
Recovers Public key from signed message hash.
std::vector< byte > bytes
Multiple precision integer with arithmetic operations.
std::vector< unsigned char > toBytes() const
vector_ref< byte const > bytesConstRef
h256 kdf(Secret const &_priv, h256 const &_hash)
Key derivation.
boost::multiprecision::number< boost::multiprecision::cpp_int_backend< 512, 512, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void >> u512
FixedHash< T > & writable()
bytes asBytes(std::string const &_b)
Converts a string to a byte array containing the string's (byte) data.
unsigned int PrivateKeyLength() const
Provides the size of the private key.
Classes for the DSA signature algorithm.
Secp256k1PP * s_secp256k1
Encodes a transaction, ready to be exported to or freshly imported from RLP.
Keccak_Final< 32 > Keccak_256
Address const & address() const
Retrieve the associated address of the public key.
boost::multiprecision::number< boost::multiprecision::cpp_int_backend< 128, 128, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void >> u128
Classes for SHA-1 and SHA-2 family of message digests.
Signature sign(Secret const &_k, h256 const &_hash)
Returns siganture of message hash.
Password based key derivation functions.
#define BOOST_FIXTURE_TEST_SUITE(a, b)
void encrypt(Public const &_k, bytesConstRef _plain, bytes &o_cipher)
Encrypts plain text using Public key.
uint8_t const size_t const size
#define BOOST_CHECK_EQUAL(v1, v2)
void * memcpy(void *a, const void *b, size_t c)
void copyTo(vector_ref< typename std::remove_const< _T >::type > _t) const
Copies the contents of this vector_ref to the contents of _t, up to the max size of _t...
bool decrypt(Secret const &_k, bytesConstRef _cipher, bytes &o_plaintext)
Decrypts cipher using Secret key.
void agree(Secret const &_s, Public const &_r, Secret &o_s)
bool sha3(bytesConstRef _input, bytesRef o_output)
Calculate SHA3-256 hash of the given input and load it into the given output.
Integer InverseMod(const Integer &n) const
calculate multiplicative inverse of *this mod n
#define BOOST_AUTO_TEST_SUITE_END()
void Decode(const byte *input, size_t inputLen, Signedness sign=UNSIGNED)
Decode from big-endian byte array.
Classes and functions for Elliptic Curves over prime and binary fields.
void sha3mac(bytesConstRef _secret, bytesConstRef _plain, bytesRef _output)
Calculate SHA3-256 MAC.
Derive DH shared secret from EC keypairs.
SECP256K1_API secp256k1_context * secp256k1_context_create(unsigned int flags) SECP256K1_WARN_UNUSED_RESULT
Create a secp256k1 context object.
std::string asString(bytes const &_b)
Converts byte array to a string containing the same (binary) data.
Classes for access to the operating system's random number generators.
Helper functions to work with json::spirit and test files.
#define BOOST_CHECK(expr)
Template implementing constructors for public key algorithm classes.