void eth::sha3(bytesConstRef _input, bytesRef _output) { CryptoPP::SHA3_256 ctx; ctx.Update((byte*)_input.data(), _input.size()); assert(_output.size() >= 32); ctx.Final(_output.data()); }
void dev::writeFile(std::string const& _file, bytesConstRef _data, bool _writeDeleteRename) { namespace fs = boost::filesystem; if (_writeDeleteRename) { fs::path tempPath = fs::unique_path(_file + "-%%%%%%"); writeFile(tempPath.string(), _data, false); // will delete _file if it exists fs::rename(tempPath, _file); } else { // create directory if not existent fs::path p(_file); if (!fs::exists(p.parent_path())) { fs::create_directories(p.parent_path()); DEV_IGNORE_EXCEPTIONS(fs::permissions(p.parent_path(), fs::owner_all)); } ofstream s(_file, ios::trunc | ios::binary); s.write(reinterpret_cast<char const*>(_data.data()), _data.size()); if (!s) BOOST_THROW_EXCEPTION(FileError() << errinfo_comment("Could not write to file: " + _file)); DEV_IGNORE_EXCEPTIONS(fs::permissions(_file, fs::owner_read|fs::owner_write)); } }
void Secp256k1PP::encryptECIES(Public const& _k, bytesConstRef _sharedMacData, bytes& io_cipher) { // interop w/go ecies implementation auto r = KeyPair::create(); Secret z; ecdh::agree(r.sec(), _k, z); auto key = eciesKDF(z, bytes(), 32); bytesConstRef eKey = bytesConstRef(&key).cropped(0, 16); bytesRef mKeyMaterial = bytesRef(&key).cropped(16, 16); CryptoPP::SHA256 ctx; ctx.Update(mKeyMaterial.data(), mKeyMaterial.size()); bytes mKey(32); ctx.Final(mKey.data()); bytes cipherText = encryptSymNoAuth(SecureFixedHash<16>(eKey), h128(), bytesConstRef(&io_cipher)); if (cipherText.empty()) return; bytes msg(1 + Public::size + h128::size + cipherText.size() + 32); msg[0] = 0x04; r.pub().ref().copyTo(bytesRef(&msg).cropped(1, Public::size)); bytesRef msgCipherRef = bytesRef(&msg).cropped(1 + Public::size + h128::size, cipherText.size()); bytesConstRef(&cipherText).copyTo(msgCipherRef); // tag message CryptoPP::HMAC<SHA256> hmacctx(mKey.data(), mKey.size()); bytesConstRef cipherWithIV = bytesRef(&msg).cropped(1 + Public::size, h128::size + cipherText.size()); hmacctx.Update(cipherWithIV.data(), cipherWithIV.size()); hmacctx.Update(_sharedMacData.data(), _sharedMacData.size()); hmacctx.Final(msg.data() + 1 + Public::size + cipherWithIV.size()); io_cipher.resize(msg.size()); io_cipher.swap(msg); }
bytesSec dev::decryptAES128CTR(bytesConstRef _k, h128 const& _iv, bytesConstRef _cipher) { if (_k.size() != 16 && _k.size() != 24 && _k.size() != 32) return bytesSec(); SecByteBlock key(_k.data(), _k.size()); try { CTR_Mode<AES>::Decryption d; d.SetKeyWithIV(key, key.size(), _iv.data()); bytesSec ret(_cipher.size()); d.ProcessData(ret.writable().data(), _cipher.data(), _cipher.size()); return ret; } catch (CryptoPP::Exception& _e) { cerr << _e.what() << endl; return bytesSec(); } }
bytes dev::encryptAES128CTR(bytesConstRef _k, h128 const& _iv, bytesConstRef _plain) { if (_k.size() != 16 && _k.size() != 24 && _k.size() != 32) return bytes(); SecByteBlock key(_k.data(), _k.size()); try { CTR_Mode<AES>::Encryption e; e.SetKeyWithIV(key, key.size(), _iv.data()); bytes ret(_plain.size()); e.ProcessData(ret.data(), _plain.data(), _plain.size()); return ret; } catch (CryptoPP::Exception& _e) { cerr << _e.what() << endl; return bytes(); } }
string dev::toBase58(bytesConstRef _d, string const& _alphabet) { auto begin = _d.data(); auto end = _d.data() + _d.size(); // Skip & count leading zeroes. int zeroes = 0; for (; begin != end && !*begin; begin++, zeroes++) {} // Allocate enough space in big-endian base58 representation. // log(256) / log(58), rounded up. std::vector<unsigned char> b58((end - begin) * 138 / 100 + 1); // Process the bytes. while (begin != end) { int carry = *begin; // Apply "b58 = b58 * 256 + ch". for (auto it = b58.rbegin(); it != b58.rend(); it++) { carry += 256 * (*it); *it = carry % 58; carry /= 58; } assert(!carry); begin++; } // Skip leading zeroes in base58 result. auto it = b58.begin(); while (it != b58.end() && !*it) it++; // Translate the result into a string. std::string ret; ret.reserve(zeroes + (b58.end() - it)); ret.assign(zeroes, '1'); while (it != b58.end()) ret += _alphabet[*(it++)]; return ret; }
bool Secp256k1PP::decryptECIES(Secret const& _k, bytesConstRef _sharedMacData, bytes& io_text) { // interop w/go ecies implementation // io_cipher[0] must be 2, 3, or 4, else invalidpublickey if (io_text.empty() || io_text[0] < 2 || io_text[0] > 4) // invalid message: publickey return false; if (io_text.size() < (1 + Public::size + h128::size + 1 + h256::size)) // invalid message: length return false; Secret z; if (!ecdh::agree(_k, *(Public*)(io_text.data() + 1), z)) return false; // Invalid pubkey or seckey. auto key = ecies::kdf(z, bytes(), 64); bytesConstRef eKey = bytesConstRef(&key).cropped(0, 16); bytesRef mKeyMaterial = bytesRef(&key).cropped(16, 16); bytes mKey(32); CryptoPP::SHA256 ctx; ctx.Update(mKeyMaterial.data(), mKeyMaterial.size()); ctx.Final(mKey.data()); bytes plain; size_t cipherLen = io_text.size() - 1 - Public::size - h128::size - h256::size; bytesConstRef cipherWithIV(io_text.data() + 1 + Public::size, h128::size + cipherLen); bytesConstRef cipherIV = cipherWithIV.cropped(0, h128::size); bytesConstRef cipherNoIV = cipherWithIV.cropped(h128::size, cipherLen); bytesConstRef msgMac(cipherNoIV.data() + cipherLen, h256::size); h128 iv(cipherIV.toBytes()); // verify tag CryptoPP::HMAC<CryptoPP::SHA256> hmacctx(mKey.data(), mKey.size()); hmacctx.Update(cipherWithIV.data(), cipherWithIV.size()); hmacctx.Update(_sharedMacData.data(), _sharedMacData.size()); h256 mac; hmacctx.Final(mac.data()); for (unsigned i = 0; i < h256::size; i++) if (mac[i] != msgMac[i]) return false; plain = decryptSymNoAuth(SecureFixedHash<16>(eKey), iv, cipherNoIV).makeInsecure(); io_text.resize(plain.size()); io_text.swap(plain); return true; }
//追加内容到文件 void dev::appendFile(std::string const& _file, bytesConstRef _data) { namespace fs = boost::filesystem; // create directory if not existent fs::path p(_file); if (!fs::exists(p.parent_path())) { fs::create_directories(p.parent_path()); DEV_IGNORE_EXCEPTIONS(fs::permissions(p.parent_path(), fs::owner_all)); } ofstream s(_file, ios::app | ios::binary); s.write(reinterpret_cast<char const*>(_data.data()), _data.size()); if (!s) BOOST_THROW_EXCEPTION(FileError() << errinfo_comment("Could not append write to file: " + _file)); DEV_IGNORE_EXCEPTIONS(fs::permissions(_file, fs::owner_read|fs::owner_write)); }
Public Secp256k1PP::recover(Signature _signature, bytesConstRef _message) { Public recovered; Integer r(_signature.data(), 32); Integer s(_signature.data()+32, 32); // cryptopp encodes sign of y as 0x02/0x03 instead of 0/1 or 27/28 byte encodedpoint[33]; encodedpoint[0] = _signature[64] | 2; memcpy(&encodedpoint[1], _signature.data(), 32); ECP::Element x; { m_curve.DecodePoint(x, encodedpoint, 33); if (!m_curve.VerifyPoint(x)) return recovered; } // if (_signature[64] & 2) // { // r += m_q; // Guard l(x_params); // if (r >= m_params.GetMaxExponent()) // return recovered; // } Integer z(_message.data(), 32); Integer rn = r.InverseMod(m_q); Integer u1 = m_q - (rn.Times(z)).Modulo(m_q); Integer u2 = (rn.Times(s)).Modulo(m_q); ECP::Point p; byte recoveredbytes[65]; { // todo: make generator member p = m_curve.CascadeMultiply(u2, x, u1, m_params.GetSubgroupGenerator()); if (p.identity) return Public(); m_curve.EncodePoint(recoveredbytes, p, false); } memcpy(recovered.data(), &recoveredbytes[1], 64); return recovered; }
bool contains(bytesConstRef _key) const { return _key.size() >= m_ext.size() && !memcmp(_key.data(), m_ext.data(), m_ext.size()); }
Public RLPXDatagramFace::authenticate(bytesConstRef _sig, bytesConstRef _rlp) { Signature const& sig = *(Signature const*)_sig.data(); return dev::recover(sig, sha3(_rlp)); }
bytes dev::aesDecrypt(bytesConstRef _ivCipher, std::string const& _password, unsigned _rounds, bytesConstRef _salt) { bytes pw = asBytes(_password); if (!_salt.size()) _salt = &pw; bytes target(64); CryptoPP::PKCS5_PBKDF2_HMAC<CryptoPP::SHA256>().DeriveKey(target.data(), target.size(), 0, pw.data(), pw.size(), _salt.data(), _salt.size(), _rounds); try { CryptoPP::AES::Decryption aesDecryption(target.data(), 16); auto cipher = _ivCipher.cropped(16); auto iv = _ivCipher.cropped(0, 16); CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption(aesDecryption, iv.data()); std::string decrypted; CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink(decrypted)); stfDecryptor.Put(cipher.data(), cipher.size()); stfDecryptor.MessageEnd(); return asBytes(decrypted); } catch (exception const& e) { cerr << e.what() << endl; return bytes(); } }