Beispiel #1
0
//------------------------------------------------------------------------------
// returns message signature generated from a URI path, a nonce 
// and postdata, message signature is created as a follows:
// 
//   hmac_sha512(path + sha256(nonce + postdata), b64decode(secret)) 
//
// and the result is converted in a base64 string: 
std::string KClient::signature(const std::string& path, 
			    const std::string& nonce, 
			    const std::string& postdata) const
{
   // add path to data to encrypt
   std::vector<unsigned char> data(path.begin(), path.end());

   // concatenate nonce and postdata and compute SHA256
   std::vector<unsigned char> nonce_postdata = sha256(nonce + postdata);

   // concatenate path and nonce_postdata (path + sha256(nonce + postdata))
   data.insert(data.end(), nonce_postdata.begin(), nonce_postdata.end());

   // and compute HMAC
   return b64_encode( hmac_sha512(data, b64_decode(secret_)) );
}
Beispiel #2
0
	/**
	 * @brief        Add a matrix to workspace
	 *
	 * @param  name  Name
	 * @param  m     The added matrix
     *
	 * @return       Success
	 */
	template<class T> inline Matrix<T>&
	AddMatrix        (const std::string& name, boost::shared_ptr< Matrix<T> > m) {

	  std::vector<std::string> tag(2);
		boost::any value = m;
        
		tag[0] = sha256(name);
		tag[1] = typeid(T).name();
		assert (m_ref.find (name) == m_ref.end());
		m_ref.insert (refent(name, tag));
		m_store.insert (entry (tag[0], value));

        m->SetClassName(name.c_str());
        
		return *m;

	}
Beispiel #3
0
void hmac_sha256_init(hmac_sha256_ctx *ctx, unsigned char *key,
                      unsigned int key_size)
{
    unsigned int fill;
    unsigned int num;

    unsigned char *key_used;
    unsigned char key_temp[SHA256_DIGEST_SIZE];
    int i;

    if (key_size == SHA256_BLOCK_SIZE) {
        key_used = key;
        num = SHA256_BLOCK_SIZE;
    } else {
        if (key_size > SHA256_BLOCK_SIZE){
            key_used = key_temp;
            num = SHA256_DIGEST_SIZE;
            sha256(key, key_size, key_used);
        } else { /* key_size > SHA256_BLOCK_SIZE */
            key_used = key;
            num = key_size;
        }
        fill = SHA256_BLOCK_SIZE - num;

        memset(ctx->block_ipad + num, 0x36, fill);
        memset(ctx->block_opad + num, 0x5c, fill);
    }

    for (i = 0; i < num; i++) {
        ctx->block_ipad[i] = key_used[i] ^ 0x36;
        ctx->block_opad[i] = key_used[i] ^ 0x5c;
    }

    sha256_init(&ctx->ctx_inside);
    sha256_update(&ctx->ctx_inside, ctx->block_ipad, SHA256_BLOCK_SIZE);

    sha256_init(&ctx->ctx_outside);
    sha256_update(&ctx->ctx_outside, ctx->block_opad,
                  SHA256_BLOCK_SIZE);

    /* for hmac_reinit */
    memcpy(&ctx->ctx_inside_reinit, &ctx->ctx_inside,
           sizeof(sha256_ctx));
    memcpy(&ctx->ctx_outside_reinit, &ctx->ctx_outside,
           sizeof(sha256_ctx));
}
static TEE_Result essiv(uint8_t iv[TEE_AES_BLOCK_SIZE],
			const uint8_t fek[TEE_FS_KM_FEK_SIZE],
			uint16_t blk_idx)
{
	TEE_Result res;
	uint8_t sha[TEE_SHA256_HASH_SIZE];
	uint8_t pad_blkid[TEE_AES_BLOCK_SIZE] = { 0, };

	res = sha256(sha, sizeof(sha), fek, TEE_FS_KM_FEK_SIZE);
	if (res != TEE_SUCCESS)
		return res;

	pad_blkid[0] = (blk_idx & 0xFF);
	pad_blkid[1] = (blk_idx & 0xFF00) >> 8;

	return aes_ecb(iv, pad_blkid, sha, 16);
}
Beispiel #5
0
void hmac_sha256_init(struct hmac_sha256_ctx *ctx,
		      const void *k, size_t ksize)
{
	struct sha256 hashed_key;
	/* We use k_opad as k_ipad temporarily. */
	uint64_t *k_ipad = ctx->k_opad;

	/* (keys longer than B bytes are first hashed using H) */
	if (ksize > HMAC_SHA256_BLOCKSIZE) {
		sha256(&hashed_key, k, ksize);
		k = &hashed_key;
		ksize = sizeof(hashed_key);
	}

	/* From RFC2104:
	 *
	 * (1) append zeros to the end of K to create a B byte string
	 *  (e.g., if K is of length 20 bytes and B=64, then K will be
	 *   appended with 44 zero bytes 0x00)
	 */
	memcpy(k_ipad, k, ksize);
	memset((char *)k_ipad + ksize, 0, HMAC_SHA256_BLOCKSIZE - ksize);

	/*
	 * (2) XOR (bitwise exclusive-OR) the B byte string computed
	 * in step (1) with ipad
	 */
	xor_block(k_ipad, IPAD);

	/*
	 * We start (4) here, appending text later:
	 *
	 * (3) append the stream of data 'text' to the B byte string resulting
	 * from step (2)
	 * (4) apply H to the stream generated in step (3)
	 */
	sha256_init(&ctx->sha);
	sha256_update(&ctx->sha, k_ipad, HMAC_SHA256_BLOCKSIZE);

	/*
	 * (5) XOR (bitwise exclusive-OR) the B byte string computed in
	 * step (1) with opad
	 */
	xor_block(ctx->k_opad, IPAD^OPAD);
}
int WorkerThread::insert_query(void)
{
    struct row_data data;

    data.num =  __64bit_generator();
    data.string_a = __generate_rand_string(256);
    data.string_b = __generate_rand_string(256);
    data.sha_digest = sha256(data.string_a + data.string_b + std::to_string(data.num));

    // uint64_t num = __64bit_generator();
    // std::string str1 = __generate_rand_string(256);
    // std::string str2 = __generate_rand_string(256);
    // std::string sha_digest = sha256(str1+str2+std::to_string(num));
    //insert_entry(connection_string, num, str1, str2, sha_digest);
    insert_entry(connection_string, data);

    return 0;
}
Beispiel #7
0
static bool do_test(const struct test *t)
{
	struct sha256 h, expected;

	if (t->repetitions == 1)
		sha256(&h, t->test, strlen(t->test));
	else {
		struct sha256_ctx ctx = SHA256_INIT;
		size_t i;

		for (i = 0; i < t->repetitions; i++)
			sha256_update(&ctx, t->test, strlen(t->test));
		sha256_done(&ctx, &h);
	}

	hex_decode(t->result, strlen(t->result), &expected, sizeof(expected));
	return memcmp(&h, &expected, sizeof(h)) == 0;
}
Beispiel #8
0
bool
Floodgate::addRecord(StellarMessage const& msg, Peer::pointer peer)
{
    Hash index = sha256(xdr::xdr_to_opaque(msg));
    auto result = mFloodMap.find(index);
    if (result == mFloodMap.end())
    { // we have never seen this message
        mFloodMap[index] = std::make_shared<FloodRecord>(
            msg, mApp.getLedgerManager().getLedgerNum(), peer);
        mFloodMapSize.set_count(mFloodMap.size());
        return true;
    }
    else
    {
        result->second->mPeersTold.push_back(peer);
        return false;
    }
}
        /**
          *   keys for basic authentication;
          *   result is: sha256( s2 + sha256( s1 + key ) );
          *   s1 and s2 are open information
         **/
        void create_key( const std::string &key,
                         const std::string &s1, const std::string &s2,
                               std::string &result )
        {
            std::string tkey(key);
            std::string ts1 (s1 );
            std::string ts2 (s2 );

            vtrc::unique_ptr<hash_iface> sha256( hash::sha2::create256( ) );

            ts1.append( tkey.begin( ), tkey.end( ) );
            ts1.assign( sha256->get_data_hash( ts1.c_str( ), ts1.size( ) ) );

            ts2.append( ts1.begin( ), ts1.end( ) );
            ts2.assign( sha256->get_data_hash( ts2.c_str( ), ts2.size( ) ) );

            result.swap( ts2 );

        }
QString sha256( QString in )
{
    unsigned char digest[ SHA512_DIGEST_SIZE];
    unsigned char* toHash = (unsigned char*)in.toUtf8().data();
    
    sha256( toHash , qstrlen( ( char* )toHash ), digest );

    // this part copied from main() in sha256.cpp
    unsigned char output[2 * SHA512_DIGEST_SIZE + 1];
    int i;

    output[2 * SHA256_DIGEST_SIZE ] = '\0';

    for (i = 0; i < SHA256_DIGEST_SIZE ; i++) {
       sprintf((char *) output + 2*i, "%02x", digest[i]);
    }
    
    return QString::fromAscii( (const char*)output );
}
Beispiel #11
0
// send message to anyone you haven't gotten it from
void
Floodgate::broadcast(StellarMessage const& msg, bool force)
{
    if (mShuttingDown)
    {
        return;
    }
    Hash index = sha256(xdr::xdr_to_opaque(msg));
    auto result = mFloodMap.find(index);
    if (result == mFloodMap.end() || force)
    { // no one has sent us this message
        FloodRecord::pointer record = std::make_shared<FloodRecord>(
            msg, mApp.getHerder().getCurrentLedgerSeq(), Peer::pointer());
        record->mPeersTold = mApp.getOverlayManager().getPeers();

        mFloodMap[index] = record;
        mFloodMapSize.set_count(mFloodMap.size());
        for (auto peer : mApp.getOverlayManager().getPeers())
        {
            if (peer->isAuthenticated())
            {
                peer->sendMessage(msg);
                record->mPeersTold.push_back(peer);
            }
        }
    }
    else
    { // send it to people that haven't sent it to us
        std::vector<Peer::pointer>& peersTold = result->second->mPeersTold;
        for (auto peer : mApp.getOverlayManager().getPeers())
        {
            if (find(peersTold.begin(), peersTold.end(), peer) ==
                peersTold.end())
            {
                if (peer->isAuthenticated())
                {
                    peer->sendMessage(msg);
                    peersTold.push_back(peer);
                }
            }
        }
    }
}
Beispiel #12
0
string Utility::importMedia(string pathname) {
  string container;
  
  if(file::exists(pathname) && file::size(pathname) <= 0x10000) {
    // Check if it's one of the system ROMs
    if(auto manifest = program->getUserResource("Nintendo DS.sys/manifest.bml")) {
      auto elem     = Markup::Document(vectorstream(manifest()).text());
      auto contents = file::read(pathname);
      auto hash     = sha256(contents.data(), contents.size());
      auto sysfolder = program->savePath("Nintendo DS.sys/");
      
      if(hash == elem["system/memory/arm9/sha256"].text()) {
        string dest = {sysfolder, elem["system/memory/arm9/data"].text()};
        file::write(dest, contents);
        return "<system>";
      }
      else if(hash == elem["system/memory/arm7/sha256"].text()) {
        string dest = {sysfolder, elem["system/memory/arm7/data"].text()};
        file::write(dest, contents);
        return "<system>";
      }
    }
  }
  
  if(!NintendoDS::validateHeader(filestream(pathname, file::mode::read))) {
    MessageWindow().setTitle("Import failed").setText(
      {"Couldn't import ",pathname,".\n"
       "\n"
       "This file doesn't look like a Nintendo DS title.\n"})
      .error();
    return "";
  }
  else if(!NintendoDS::importROMImage(container, libraryPath(), pathname)) {
    MessageWindow().setTitle("Import failed").setText(
      {"Couldn't import ",pathname,".\n"
       "\n"
       "Check to see if you've got sufficient permissions and disk space."})
      .error();
    return "";
  }
  return container;
}
Beispiel #13
0
static int validate_response(connection *c) {
    char *source, *ret_hash, *nonce, *freeme;
    char scratch[512];

    unsigned char vhash[SHA_LENGTH];
    int valid = 0;

    /* printf("c->buf = %s.\n", c->buf); */
    freeme = source = strdup(c->buf);
    ret_hash = strsep(&source, ":");
    nonce = source;
    /* printf("nonce = %s.\n", nonce); */

    /* no colon: nope */
    if (nonce != NULL) {
        /* returned hash != sent hash: nope */
        if (memcmp(ret_hash, c->hash, SHA_LENGTH * 2) == 0) {
            strcpy(scratch, ret_hash);
            strcat(scratch, nonce);
            sha256(scratch, strlen(scratch), vhash);

            /* is the work proved? */
            if (vhash[SHA_LENGTH - 1] == 0) {
                valid = 1;
                strcpy(c->last_hash, c->hash);
                hexillate(vhash, c->hash, SHA_LENGTH);
            }
            else {
                printf("%s is not a valid proof of work.\n", c->buf);
            }
        }
        else {
            printf("received payload %s doesn't match sent payload %s.\n", ret_hash, c->hash);
        }
    }
    else {
        printf("input %s is missing a nonce.\n", c->buf);
    }

    free(freeme);
    return valid;
}
Beispiel #14
0
	/**
	 * @brief        Get data from recon (Local connector)
	 *
	 * @param  name  Name
	 * @param  m     CXFL data storage 
	 */
	template <class T> inline void
	SetMatrix          (const std::string& name, Matrix<T>& m) {

	  std::vector<std::string> tag(2);
		tag[0] = sha256(name);
		tag[1] = typeid(T).name();

		boost::shared_ptr<Matrix<T> > pm = boost::make_shared<Matrix<T> >();
		boost::any val     = pm;

		if (m_ref.find (name) == m_ref.end()) {
			m_ref.insert (refent(name,tag));
			m_store.insert (entry(tag[0], val));
		} else 

		m.SetClassName(name.c_str());

		*pm = m;

	}
Beispiel #15
0
	/**
	 * @brief        Add a matrix to workspace
	 *
	 * @param  name  Name
	 * @param  m     The added matrix
     *
	 * @return       Success
	 */
	template<class T> inline Matrix<T>&
	AddMatrix        (const std::string& name) {

		shrd_ptr<Matrix<T> > m = mk_shared<Matrix<T> >();
		std::vector<std::string> tag(2);
		boost::any value = m;
        
		tag[0] = sha256(name);
		tag[1] = typeid(T).name();
		reflist::iterator ri = m_ref.find (name);
		if (ri != m_ref.end())
			Free (name);
		m_ref.insert (refent(name, tag));
		m_store.insert (entry (tag[0], value));

        m->SetClassName(name.c_str());
        
		return *m;

	}
int main(int argc, char *argv[])
{
	const tal_t *ctx = tal_arr(NULL, char, 0);
	struct sha256 seed, revocation_hash, rval;
	struct pkt *pkt;
	unsigned update_num;

	err_set_progname(argv[0]);

	opt_register_noarg("--help|-h", opt_usage_and_exit,
			   "<seed> <update-number> <r-value>\n"
			   "Create a new HTLC complete message",
			   "Print this message.");
	opt_register_version();

 	opt_parse(&argc, argv, opt_log_stderr_exit);

	if (argc != 4)
		opt_usage_exit_fail("Expected 3 arguments");

	if (!hex_decode(argv[1], strlen(argv[1]), &seed, sizeof(seed)))
		errx(1, "Invalid seed '%s' - need 256 hex bits", argv[1]);
	update_num = atoi(argv[2]);
	if (!update_num)
		errx(1, "Update number %s invalid", argv[2]);

	if (!hex_decode(argv[3], strlen(argv[3]), &rval, sizeof(rval)))
		errx(1, "Invalid rvalue '%s' - need 256 hex bits", argv[3]);

	/* Get next revocation hash. */
	shachain_from_seed(&seed, update_num, &revocation_hash);
	sha256(&revocation_hash,
	       revocation_hash.u.u8, sizeof(revocation_hash.u.u8));

	pkt = update_htlc_complete_pkt(ctx, &revocation_hash, &rval);
	if (!write_all(STDOUT_FILENO, pkt, pkt_totlen(pkt)))
		err(1, "Writing out packet");

	tal_free(ctx);
	return 0;
}
Beispiel #17
0
void test_sha256() {
	const char * tests[4] = {
		"", "A", "0123456789", "abcdefghijklmnopqrstuvwxyz"
	};
	const char * oks[4] = {
		"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
		"559aead08264d5795d3909718cdd05abd49572e84fe55590eef31a88a08fdffd",
		"84d89877f0d4041efb6bf91a16f0248f2fd573e6af05c19f96bedb9f882f7882",
		"71c480df93d6ae2f1efad1447c66c9525e316218cf51fc8d9ed832f2daf18b73"
	};
	uint8_t hash[SHA256_HASH_SIZE];
	char string[SHA256_STRING_HASH_SIZE];
	int i;
	puts("\n\nTesting SHA256...\n");
	for (i = 0; i < 4; i++) {
		sha256(tests[i], strlen(tests[i]), hash);
		sha256_hash_to_string(hash, string);
		printf("%s\n%s\n--> %s\n\n", tests[i], string, strcmp(string, oks[i]) == 0 ? "OK" : "FAIL");
	}
	puts("\nTest done.\n");
}
Beispiel #18
0
void hmac_sha256_init(hmac_sha256_ctx_t *s, void* key, uint16_t keylength_b){
	uint8_t buffer[SHA256_HASH_BYTES];
	uint8_t i;
	
	memset(buffer, 0, SHA256_HASH_BYTES);
	if (keylength_b > SHA256_BLOCK_BITS){
		sha256((void*)buffer, key, keylength_b);
	} else {
		memcpy(buffer, key, (keylength_b+7)/8);
	}
	
	for (i=0; i<SHA256_HASH_BYTES; ++i){
		buffer[i] ^= IPAD;
	}
	
	sha256_init(s);
	sha256_nextBlock(s, buffer);
#if defined SECURE_WIPE_BUFFER
	memset(buffer, 0, SHA256_HASH_BYTES);
#endif
}
Beispiel #19
0
void CoinQKeychainSqlite3::insertMultiSigRedeemScript(const std::vector<uchar_vector>& pubKeys, int type, int status, const std::string& label, int minHeight, int maxHeight)
{
    if (type < 1 || type > 2) {
        throw CoinQ::Exception("Invalid type.", CoinQ::Exception::INVALID_PARAMETERS);
    }

    if (status < 1 || status > 2) {
        throw CoinQ::Exception("Invalid status.", CoinQ::Exception::INVALID_PARAMETERS);
    }

    Coin::MultiSigRedeemScript multiSig;
    for (auto& pubKey: pubKeys) {
        multiSig.addPubKey(pubKey);
    }

    SQLite3Tx sqliteTx(db, SQLite3Tx::IMMEDIATE);
    SQLite3Stmt stmt;
    stmt.prepare(db, "INSERT INTO `redeemscripts` (`hash`, `type`, `status`, `minheight`, `maxheight`, `label`) VALUES (?,?,?,?,?,?)");
    stmt.bindText(1, ripemd160(sha256(multiSig.getRedeemScript())).getHex());
    stmt.bindInt (2, type);
    stmt.bindInt (3, status);
    stmt.bindInt (4, minHeight);
    stmt.bindInt (5, maxHeight);
    stmt.bindText(6, label);
    stmt.step();
    stmt.finalize();

    std::stringstream sql;
    sql << "INSERT INTO `multisigs` (`redeemscript_id`, `pubkey`, `index`) VALUES (" << db.lastInsertRowId() << ",?,?)";
    stmt.prepare(db, sql.str());

    int i = 0;
    for (auto& pubKey: pubKeys) {
        stmt.reset();
        stmt.bindText(1, pubKey.getHex());
        stmt.bindInt (2, i++);
        stmt.step();
    }
}
Beispiel #20
0
void parse_partitions(void* buf, char* target_dir){
	char part_dir[256];
	uint8_t hash[SHA256_DIGEST_LENGTH];
	uint8_t* buffer = (uint8_t*)buf + 0x200;
	uint32_t cur_part = PART_BASE;
	uint32_t part_length = 0;
	uint32_t hash_tbl_length = 0;

	if(mkdir(target_dir, 0766) < 0){
		fprintf(stderr, "Couldn't create dir %s\n", target_dir);
		return;
	}

	chdir(target_dir);
	while(!strncmp((char*)buffer, "DIFI", 4)){
		snprintf(part_dir, sizeof(part_dir), "part-%d", buffer[FS_INDEX_OFF]);
		hash_tbl_length = *((uint32_t*)&buffer[HASH_TBL_LEN_OFF]);
		part_length = *((uint32_t*)&buffer[PARTITION_LEN_OFF]);
		for(int i = 0; i < hash_tbl_length; i += SHA256_DIGEST_LENGTH){
			for(int j = 0; j < part_length; j += SECTOR_SIZE){
				sha256(buf + j + cur_part + hash_tbl_length, (part_length - j > SECTOR_SIZE) ? SECTOR_SIZE : part_length - j, hash);
				if(!memcmp(buf + i + cur_part, hash, sizeof(hash))){
					printf("Block (%08X) matches entry %d (", j + cur_part + hash_tbl_length, i / SHA256_DIGEST_LENGTH);
					for(int x = 0; x < SHA256_DIGEST_LENGTH; x++)
						printf("%02x", hash[x]);
					printf(")\n");
				}
			}
		}
#ifdef DEBUG
		printf("Partition @ %06X (%06X)\n", cur_part, part_length + hash_tbl_length);
#endif /* DEBUG */
		cur_part += hash_tbl_length;
		parse_fs(buf + cur_part, part_dir);
		cur_part += part_length;
		buffer += DIFI_LENGTH;
	}	
}
Beispiel #21
0
void hmac_sha256( const unsigned char *key, size_t keyLen,
                  const unsigned char *msg, size_t msgLen,
                  unsigned char hash[] )
{
    unsigned char	pad[ HMAC_SHA256_BLOCK_SIZE ];
    unsigned char	normalizedKey[ HMAC_SHA256_BLOCK_SIZE ];
    unsigned char	intermediateHash[ HMAC_SHA256_HASH_SIZE ];
    size_t		i;
    sha256_ctx	ctx;

    memset( normalizedKey, 0, HMAC_SHA256_BLOCK_SIZE );
    if ( keyLen > HMAC_SHA256_BLOCK_SIZE )
        sha256( key, keyLen, normalizedKey );
    else	{
        for ( i = 0; i < keyLen; i++ )
            normalizedKey[ i ] = key[ i ];
    }

    memset( pad, 0x36, HMAC_SHA256_BLOCK_SIZE );
    for ( i = 0; i < HMAC_SHA256_BLOCK_SIZE; i++ )
        pad[ i ] ^= normalizedKey[ i ];
    sha256_init( &ctx );
    sha256_update( &ctx, pad, HMAC_SHA256_BLOCK_SIZE );
    sha256_update( &ctx, msg, msgLen );
    sha256_final( &ctx, intermediateHash );

    memset( pad, 0x5c, HMAC_SHA256_BLOCK_SIZE );
    for ( i = 0; i < HMAC_SHA256_BLOCK_SIZE; i++ )
        pad[ i ] ^= normalizedKey[ i ];
    sha256_init( &ctx );
    sha256_update( &ctx, pad, HMAC_SHA256_BLOCK_SIZE );
    sha256_update( &ctx, intermediateHash, HMAC_SHA256_HASH_SIZE );
    sha256_final( &ctx, hash );

    memset( pad, 0, sizeof( pad ));
    memset( normalizedKey, 0, sizeof( normalizedKey ));
    memset( intermediateHash, 0, sizeof( intermediateHash ));
}
Beispiel #22
0
void
Node::cacheQuorumSet(const SCPQuorumSet& qSet)
{
    uint256 qSetHash = sha256(xdr::xdr_to_opaque(qSet));
    CLOG(DEBUG, "SCP") << "Node::cacheQuorumSet"
                       << "@" << binToHex(mNodeID).substr(0, 6)
                       << " qSet: " << binToHex(qSetHash).substr(0, 6);

    if (mCache.find(qSetHash) != mCache.end())
    {
        return;
    }

    while (mCacheCapacity >= 0 && mCache.size() >= (size_t)mCacheCapacity)
    {
        assert(mCacheLRU.size() == mCache.size());
        auto it = mCacheLRU.begin();
        mCache.erase(*it);
        mCacheLRU.erase(it);
    }
    mCacheLRU.push_back(qSetHash);
    mCache[qSetHash] = qSet;
}
Beispiel #23
0
int main(void) {
  eeprom_load_id(id);
  eeprom_load_secret(secret);

  sei();
  SW_UART_Enable();

  /*----- Send start condition -----*/
  SW_UART_Transmit(0x99);
  /*----- Transmit ID -----*/
  swu_transmit(id, 2);
  
  /*----- Receive challenge -----*/
  swu_receive(challenge, 32);

  /*----- AND challenge and secret and hash the result -----*/
  for (int i=0; i<32; i++) {
    challenge[i] &= secret[i];
  }
  sha256(&hash, challenge, 256);

  /*----- Transmit response -----*/
  swu_transmit(hash, 32);
}
Beispiel #24
0
void CoinQKeychainSqlite3::generateNewKeys(int count, int type, bool bCompressed)
{
    SQLite3Stmt stmt;

    CoinKey key;
    key.setCompressed(bCompressed);

    stmt.prepare(db, "INSERT INTO `keys` (`hash`, `pubkey`, `privkey`, `type`, `status`, `minheight`, `maxheight`) VALUES (?,?,?,?,?,-1,-1)");
    for (int i = 0; i < count; i++) {
        key.generateNewKey();
        uchar_vector pubkey = key.getPublicKey();
        std::string pubkeyhash = ripemd160(sha256(pubkey)).getHex();
        std::string pubkeyhex = pubkey.getHex();
        uchar_vector privkey = key.getPrivateKey();
        std::string privkeyhex = privkey.getHex();
        stmt.reset();
        stmt.bindText(1, pubkeyhash);
        stmt.bindText(2, pubkeyhex);
        stmt.bindText(3, privkeyhex);
        stmt.bindInt (4, type);
        stmt.bindInt (5, Status::POOL);
        stmt.step();
    }
}
Beispiel #25
0
Pkt *accept_pkt_htlc_fulfill(struct peer *peer, const Pkt *pkt)
{
	const UpdateFulfillHtlc *f = pkt->update_fulfill_htlc;
	struct htlc *htlc;
	struct sha256 rhash;
	struct rval r;
	Pkt *err;
	union htlc_staging stage;

	err = find_commited_htlc(peer, f->id, &htlc);
	if (err)
		return err;

	/* Now, it must solve the HTLC rhash puzzle. */
	proto_to_rval(f->r, &r);
	sha256(&rhash, &r, sizeof(r));

	if (!structeq(&rhash, &htlc->rhash))
		return pkt_err(peer, "Invalid r for %"PRIu64, f->id);

	/* We can relay this upstream immediately. */
	our_htlc_fulfilled(peer, htlc, &r);

	/* BOLT #2:
	 *
	 * ... and the receiving node MUST add the HTLC fulfill/fail
	 * to the unacked changeset for its local commitment.
	 */
	cstate_fulfill_htlc(peer->local.staging_cstate, htlc, OURS);

	stage.fulfill.fulfill = HTLC_FULFILL;
	stage.fulfill.htlc = htlc;
	stage.fulfill.r = r;
	add_unacked(&peer->local, &stage);
	return NULL;
}
#include "main/Application.h"
#include "main/test.h"
#include "overlay/PeerDoor.h"
#include "main/Config.h"
#include "util/Logging.h"
#include "simulation/Simulation.h"
#include "overlay/OverlayManager.h"

namespace stellar
{

TEST_CASE("TCPPeer can communicate", "[overlay]")
{
    Simulation::pointer s = std::make_shared<Simulation>(Simulation::OVER_TCP);

    auto v10SecretKey = SecretKey::fromSeed(sha256("v10"));
    auto v11SecretKey = SecretKey::fromSeed(sha256("v11"));

    SCPQuorumSet n0_qset;
    n0_qset.threshold = 1;
    n0_qset.validators.push_back(v10SecretKey.getPublicKey());
    auto n0 =
        s->getNode(s->addNode(v10SecretKey, n0_qset, s->getClock()));

    SCPQuorumSet n1_qset;
    n1_qset.threshold = 1;
    n1_qset.validators.push_back(v11SecretKey.getPublicKey());
    auto n1 =
        s->getNode(s->addNode(v11SecretKey, n1_qset, s->getClock()));

    s->startAllNodes();
Beispiel #27
0
static void sha256_wrap( const unsigned char *input, size_t ilen,
                    unsigned char *output )
{
    sha256( input, ilen, output, 0 );
}
Beispiel #28
0
/* BOLT #3:
 *
 * The corresponding private key can be derived once the `per_commitment_secret`
 * is known:
 *
 *     revocationprivkey = revocation_basepoint_secret * SHA256(revocation_basepoint || per_commitment_point) + per_commitment_secret * SHA256(per_commitment_point || revocation_basepoint)
 */
bool derive_revocation_privkey(const struct secret *base_secret,
			       const struct secret *per_commitment_secret,
			       const struct pubkey *basepoint,
			       const struct pubkey *per_commitment_point,
			       struct privkey *key)
{
	struct sha256 sha;
	unsigned char der_keys[PUBKEY_CMPR_LEN * 2];
	struct secret part2;

	pubkey_to_der(der_keys, basepoint);
	pubkey_to_der(der_keys + PUBKEY_CMPR_LEN, per_commitment_point);
	sha256(&sha, der_keys, sizeof(der_keys));
#ifdef SUPERVERBOSE
	printf("# SHA256(revocation_basepoint || per_commitment_point)\n");
	printf("# => SHA256(0x%s || 0x%s)\n",
	       tal_hexstr(tmpctx, der_keys, PUBKEY_CMPR_LEN),
	       tal_hexstr(tmpctx, der_keys + PUBKEY_CMPR_LEN, PUBKEY_CMPR_LEN));
	printf("# = 0x%s\n", tal_hexstr(tmpctx, sha.u.u8, sizeof(sha.u.u8))),
#endif

	key->secret = *base_secret;
	if (secp256k1_ec_privkey_tweak_mul(secp256k1_ctx, key->secret.data,
					   sha.u.u8)
	    != 1)
		return false;
#ifdef SUPERVERBOSE
	printf("# * revocation_basepoint_secret (0x%s)",
	       tal_hexstr(tmpctx, base_secret, sizeof(*base_secret))),
	printf("# = 0x%s\n", tal_hexstr(tmpctx, key, sizeof(*key))),
#endif

	pubkey_to_der(der_keys, per_commitment_point);
	pubkey_to_der(der_keys + PUBKEY_CMPR_LEN, basepoint);
	sha256(&sha, der_keys, sizeof(der_keys));
#ifdef SUPERVERBOSE
	printf("# SHA256(per_commitment_point || revocation_basepoint)\n");
	printf("# => SHA256(0x%s || 0x%s)\n",
	       tal_hexstr(tmpctx, der_keys, PUBKEY_CMPR_LEN),
	       tal_hexstr(tmpctx, der_keys + PUBKEY_CMPR_LEN, PUBKEY_CMPR_LEN));
	printf("# = 0x%s\n", tal_hexstr(tmpctx, sha.u.u8, sizeof(sha.u.u8))),
#endif

	part2 = *per_commitment_secret;
	if (secp256k1_ec_privkey_tweak_mul(secp256k1_ctx, part2.data,
					   sha.u.u8) != 1)
		return false;
#ifdef SUPERVERBOSE
	printf("# * per_commitment_secret (0x%s)",
	       tal_hexstr(tmpctx, per_commitment_secret,
			  sizeof(*per_commitment_secret))),
		printf("# = 0x%s\n", tal_hexstr(tmpctx, &part2, sizeof(part2)));
#endif

	if (secp256k1_ec_privkey_tweak_add(secp256k1_ctx, key->secret.data,
					   part2.data) != 1)
		return false;

#ifdef SUPERVERBOSE
	printf("# => 0x%s\n", tal_hexstr(tmpctx, key, sizeof(*key)));
#endif
	return true;
}
Beispiel #29
0
/* BOLT #3:
 *
 * The `revocationpubkey` is a blinded key: when the local node wishes to
 * create a new commitment for the remote node, it uses its own
 * `revocation_basepoint` and the remote node's `per_commitment_point` to
 * derive a new `revocationpubkey` for the commitment. After the remote node
 * reveals the `per_commitment_secret` used (thereby revoking that
 * commitment), the local node can then derive the `revocationprivkey`, as it
 * now knows the two secrets necessary to derive the key
 * (`revocation_basepoint_secret` and `per_commitment_secret`).
 *
 * The `per_commitment_point` is generated using elliptic-curve multiplication:
 *
 * 	per_commitment_point = per_commitment_secret * G
 *
 * And this is used to derive the revocation pubkey from the remote node's
 * `revocation_basepoint`:
 *
 * 	revocationpubkey = revocation_basepoint * SHA256(revocation_basepoint || per_commitment_point) + per_commitment_point * SHA256(per_commitment_point || revocation_basepoint)
 */
bool derive_revocation_key(const struct pubkey *basepoint,
			const struct pubkey *per_commitment_point,
			struct pubkey *key)
{
	struct sha256 sha;
	unsigned char der_keys[PUBKEY_CMPR_LEN * 2];
	secp256k1_pubkey add[2];
	const secp256k1_pubkey *args[2];

	pubkey_to_der(der_keys, basepoint);
	pubkey_to_der(der_keys + PUBKEY_CMPR_LEN, per_commitment_point);
	sha256(&sha, der_keys, sizeof(der_keys));
#ifdef SUPERVERBOSE
	printf("# SHA256(revocation_basepoint || per_commitment_point)\n");
	printf("# => SHA256(0x%s || 0x%s)\n",
	       tal_hexstr(tmpctx, der_keys, PUBKEY_CMPR_LEN),
	       tal_hexstr(tmpctx, der_keys + PUBKEY_CMPR_LEN, PUBKEY_CMPR_LEN));
	printf("# = 0x%s\n", tal_hexstr(tmpctx, sha.u.u8, sizeof(sha.u.u8))),
#endif

	add[0] = basepoint->pubkey;
	if (secp256k1_ec_pubkey_tweak_mul(secp256k1_ctx, &add[0], sha.u.u8) != 1)
		return false;
#ifdef SUPERVERBOSE
	printf("# x revocation_basepoint = 0x%s\n",
	       type_to_string(tmpctx, secp256k1_pubkey, &add[0]));
#endif

	pubkey_to_der(der_keys, per_commitment_point);
	pubkey_to_der(der_keys + PUBKEY_CMPR_LEN, basepoint);
	sha256(&sha, der_keys, sizeof(der_keys));
#ifdef SUPERVERBOSE
	printf("# SHA256(per_commitment_point || revocation_basepoint)\n");
	printf("# => SHA256(0x%s || 0x%s)\n",
	       tal_hexstr(tmpctx, der_keys, PUBKEY_CMPR_LEN),
	       tal_hexstr(tmpctx, der_keys + PUBKEY_CMPR_LEN, PUBKEY_CMPR_LEN));
	printf("# = 0x%s\n", tal_hexstr(tmpctx, sha.u.u8, sizeof(sha.u.u8))),
#endif

	add[1] = per_commitment_point->pubkey;
	if (secp256k1_ec_pubkey_tweak_mul(secp256k1_ctx, &add[1], sha.u.u8) != 1)
		return false;
#ifdef SUPERVERBOSE
	printf("# x per_commitment_point = 0x%s\n",
	       type_to_string(tmpctx, secp256k1_pubkey, &add[1]));
#endif

	args[0] = &add[0];
	args[1] = &add[1];
	if (secp256k1_ec_pubkey_combine(secp256k1_ctx, &key->pubkey, args, 2)
	    != 1)
		return false;

#ifdef SUPERVERBOSE
	printf("# 0x%s + 0x%s => 0x%s\n",
	       type_to_string(tmpctx, secp256k1_pubkey, args[0]),
	       type_to_string(tmpctx, secp256k1_pubkey, args[1]),
	       type_to_string(tmpctx, struct pubkey, key));
#endif
	return true;
}
Beispiel #30
0
/*main*/
int main(int argc, char** argv)
{
  struct sockaddr_in srv;
  struct hostent* bserv;
  int n;
  int m;
  char c;
  int con;
  int nport;
  char buff[MAX];
  char buff2[MAX];
  char nick[MAX];
  char user_name_output[MAX];
  char password[MAX];
  char hash_pass[MAX];
  signal(SIGINT, notime);
  /*check for number of arguments when starting a client*/
  if(argc < 3)
    {
      puts("Use: [host] [nport]");
      exit(0);
    }
  nport = atoi(argv[2]);
  sockfd = socket(AF_INET, SOCK_STREAM, 0);
  /*check is socket is valid*/
  if (sockfd < 0)
    {
      puts("invalid socket");
      exit(0);
    }
  bserv = gethostbyname(argv[1]);
  if (bserv == NULL)
    {
      puts("no host");
      exit(0);
    }
  memset(&srv, 0, sizeof(srv));
  srv.sin_family = AF_INET;
  srv.sin_port = htons(nport);
  memcpy(&srv.sin_addr.s_addr, bserv->h_addr, bserv->h_length);
  /*check if connection is successful*/
  con = connect(sockfd,  (struct sockaddr *)&srv, sizeof(srv));
  if(con<0)
    {
      printf("%s", "Could not connect to");
      puts(argv[1]);
      exit(0);
    }
  /*authentication process*/
  puts("                    WELCOME TO ENCLOSED");
  puts(" |~| Would you like to 'create' an account or 'login' using existing account");
  n = read(0, buff, MAX-6);
  n = write(sockfd, buff, MAX-6);
  signal(SIGINT, notime2);
  usleep(3000);
  /*while user doesn't input create or login display this error message*/
  while((strncmp(buff, "create", 6) != 0) && (strncmp(buff,"login",5) != 0))
    {
      puts(" [###] ERROR: Incorrect command, use: create or login");
      n = read(0, buff, MAX-6);
      n = write(sockfd, buff, MAX-6);
      signal(SIGINT, notime2);
      usleep(3000);
    }
  /*if user enters create go here*/
  if(strncmp(buff, "create", 6) == 0)
    {
      puts(" |~| enter username: "******"Invalid socket");
      nick[n-1] = '\0';
      strncpy(user_name_output,nick,n);
      while(n < 3)
	{
	  puts(" [###] ERROR: Invalid username, must be at least 3 letters long\n");
	  puts(" |~| enter username: "******"Invalid socket");
	  nick[n-1] = '\0';

	}
      n = write(sockfd, nick, MAX-6);
      signal(SIGINT, notime2);
      usleep(3000);
      n = read(sockfd, nick, MAX-6);

	      if(nick[0] != '~')
	{
	  puts("server down\n");
      exit(0);
	}

      /*check for password*/
      puts(" |~| enter password: "******"Invalid socket");

      int i = 0;
      for (;;) {
        c = getch();
	password[i] = c;
	i++;
        if(c == '\n')
	  {
	    //i=0;
	    break;
	  }
      }

      //password[n-1] = '\0';

      //      puts(password);
      while(i<5)
	{
	  puts(" [###] ERROR: Invalid password, must be atleast 5 charachters long");
	  puts(" |~| enter password: "******"          [!] Creating new account...");
      usleep(500000);
      puts(" |~| Account has been successfuly created");
    }
  /*if user enters login go here*/
  else if(strncmp(buff, "login", 5) == 0)
    {
      puts(" |~| enter username: "******"Invalid socket");
      nick[n-1] = '\0';

      n = write(sockfd, nick, MAX-6);
      signal(SIGINT, notime2);
      usleep(3000);
      n = read(sockfd, nick, MAX-6);

      if(nick[0] != '~')
	{
	  puts("server down\n");
      exit(0);
	}
      /*check for password*/
      puts(" |~| enter password: "******"Invalid socket");
      /*
      while (password != "test123")
	{
	  puts(" ### ERROR: user name and password does not match");
	  puts(" ~ enter password: "******"          [!] Logging in");
      usleep(500000);

    }
  /*introductory message*/
  printf("                    You are now logged in as %s \n", user_name_output);
  puts("          [!] What would you like to do?");
  puts("     |~| Your options include: ");
  puts("     |~| /help: to view this message again");
  puts("     |~| /exit: to quit the program");
  puts("     |~| /view_passes: to view all saved passwords");
  puts("     |~| /change_mpass: to change master password");
  puts("     |~| /add_acc: add new account to your password database");
  puts("  |~|~adding more later on!");
  while(1)
    {
      n = read(0, buff, MAX-6);
      buff[n-1] = '\0';

      if(n <= 0)
	  puts("Invalid read");

/*check commands just simple commands in alpha*/
      write(sockfd,buff,MAX-6);
      if(strncmp(buff, "/change_mpass", 13) == 0)
	{
	  puts("          [!] Accessing user database to change master password...");
	  usleep(500000);
	  puts(" |~| please input current master password: "******"Invalid socket");
	  buff2[n] = '\0';

	  n = write(sockfd, buff2, MAX-6);
	  signal(SIGINT, notime2);
	  usleep(3000);
	  //n = read(sockfd, buff2, MAX-6);
	  puts(" |~| please input new master password: "******"Invalid socket");
	  password[n-1] = '\0';

	  signal(SIGINT, notime2);
	  usleep(3000);
	  puts(" |~| please re-enter new master password: "******"Invalid socket");
	  buff[n-1] = '\0';

	  signal(SIGINT, notime2);
	  usleep(3000);
	  while(strcmp(buff, password) != 0 )
	    {
	      puts(" [###] Error: New password didn't match");
	      puts(" |~| please input new master password: "******"Invalid socket");
	      password[n-1] = '\0';

	      signal(SIGINT, notime2);
	      usleep(3000);
	      puts(" |~| please re-enter new master password: "******"Invalid socket");
	      buff[n-1] = '\0';

	      signal(SIGINT, notime2);
	      usleep(3000);
	      //bzero(password,MAX);
	      //bzero(buff2,MAX);
	    }
	  n = write(sockfd, password, MAX-6);
	  n = write(sockfd, buff, MAX-6);
	  puts ("         [!] Changing master password...");
	  usleep(500000);
	  puts(" |~| Your master password has been successfully saved");
	  //n = read(sockfd, buff2, MAX-6);
	 	   bzero(buff2,MAX);
	  //puts("          ! your master password is now changed");
	}

      if(strncmp(buff, "/add_acc", 8) == 0)
	{
	  puts(" |~| please input website for this account: ");

	  n = read(0, buff2, MAX-6);
	  if(n < 0)
	    puts("Invalid socket");
	  buff2[n-1] = '\0';

	  n = write(sockfd, buff2, MAX-6);
	  signal(SIGINT, notime2);
	  usleep(3000);
	  n = read(sockfd, buff2, MAX-6);
	  puts(" |~| please input your username for that account: ");
	  n = read(0, buff2, MAX-6);
	  if(n < 0)
	    puts("Invalid socket");
	  buff2[n-1] = '\0';

	  n = write(sockfd, buff2, MAX-6);
	  signal(SIGINT, notime2);
	  usleep(3000);
	  n = read(sockfd, buff2, MAX-6);

	  puts(" |~| please input your password for that account: ");
	  n = read(0, buff2, MAX-6);
	  if(n < 0)
	    puts("Invalid socket");
	  buff2[n-1] = '\0';

	  n = write(sockfd, buff2, MAX-6);
	  signal(SIGINT, notime2);
	  usleep(50000);
	  n = read(sockfd, buff2, MAX-6);
	  puts("          [!] Account has been added");
	  bzero(buff2,MAX);
	}

      if(strncmp(buff, "/exit", 5) == 0)
	{
	  //fflush((char*)buff);
	  puts("exiting server");
	  //free(buff);
	  //fflush(buff);
	  exit(0);
	}
      if(strncmp(buff, "/view_passes", 12) == 0)
	{
	  //puts("Here are your saved passwords");
	  puts("          [!] Accessing password database...");
	  usleep(500000);
	  puts(" |~| Which passwords would you like to view?");
	  puts(" |~| You can either view '/all' or individual passwords using website names");
	    n = read(0, buff2, MAX-6);
	  if(n < 0)
	    puts("Invalid socket");
	  buff2[n-1] = '\0';
	  n = write(sockfd, buff2, MAX-6);
	  signal(SIGINT, notime2);
	  usleep(3000);
	  n = read(sockfd, buff2, MAX-6);
	  if (strncmp(buff2, "/all", 4) == 0)
	    {
	      //TO DO
	      puts("print all passwords for this user");
	    }

	  bzero(buff2,MAX);
	}
      if(strncmp(buff, "/help", 5) == 0)
	{
          puts("     |~| Your options include: ");
	  puts("     |~| /help: to view this message again");
	  puts("     |~| /exit: to quit the program");
	  puts("     |~| /view_passes: to view all saved passwords");
	  puts("     |~| /change_mpass: to change master password");
	  puts("     |~| /add_acc: add new account to your password database");
	  puts("          |!| adding more later on!");

	}

      /*
      if(buff[0] != '~')
	{
	  puts("server down");
	  exit(0);
	}
      */
      /*if user inputs non of the above commands*/
      else if(((strncmp(buff, "/help", 5) != 0) && (strncmp(buff, "/exit", 5) != 0) && (strncmp(buff, "/add_acc", 8) != 0) && (strncmp(buff, "/view_passes", 12) != 0) && (strncmp(buff, "/change_mpass", 13) != 0)))
	{

	   bzero(buff,MAX);
	   bzero(buff2, MAX);
	  //n = write(sockfd, buff, MAX-6);
	   printf(" [###] ERROR: unknown command %s, type: help to view available actions \n", buff);
	  //usleep(3000);
	  //n = read(sockfd, buff, MAX-6);
	}
    }
  /*freeing buffer, password and nickname*/
  free(buff);
  free(password);
  free(hash_pass);
  free(nick);
  free(buff2);
}