Пример #1
0
static X509* ParseCertificate(FILE* file, const bool fChainAdmin, const string& strPassword)
{
    OpenSSL_add_all_algorithms(); // needed to load encrypted private keys

    EVP_PKEY *privkey = EVP_PKEY_new();

    if (!PEM_read_PrivateKey(file, &privkey, NULL, strPassword.length() ? (char *)strPassword.c_str() : NULL)) {
        fclose(file);
        LogPrintf("ERROR: could not open certificate file.\n");
        return NULL;
    }

    fclose(file);

    const EC_KEY* eckey = EVP_PKEY_get1_EC_KEY(privkey);

    if (!EC_KEY_check_key(eckey)) {
        LogPrintf("ERROR: invalid key supplied\n");
        return NULL;
    }

    const BIGNUM *bnPrivKey = EC_KEY_get0_private_key(eckey);

    unsigned char buf[256];
    size_t sKeyLen = BN_bn2bin(bnPrivKey, buf);
    const vector<unsigned char> data(buf, buf + sKeyLen);

    if (fChainAdmin)
        adminPrivKey.Set(data.begin(), data.end(), false);
    else
        cvnPrivKey.Set(data.begin(), data.end(), false);

    if ((fChainAdmin && !adminPrivKey.IsValid()) || (!fChainAdmin && !cvnPrivKey.IsValid())) {
        LogPrintf("ERROR: could not validate supplied %s key\n", fChainAdmin ? "admin" : "cvn");
        return NULL;
    }

    BIO *bioCert = BIO_new(BIO_s_file());
    boost::filesystem::path certFile = GetDataDir() / (fChainAdmin ? GetArg("-admincertfile", "admin.pem") : GetArg("-cvncertfile", "cvn.pem"));
    if (!BIO_read_filename(bioCert, certFile.string().c_str())) {
        LogPrintf("ERROR: cert file not found: %s, is -%scertfile set correctly?\n", certFile, fChainAdmin ? "admin" : "cvn");
        return NULL;
    }

    X509 *x509Cert = PEM_read_bio_X509(bioCert, NULL, 0, NULL);

    BIO_free(bioCert);

    return x509Cert;
}
Пример #2
0
CKey CTransactcoinSecret::GetKey()
{
    CKey ret;
    assert(vchData.size() >= 32);
    ret.Set(vchData.begin(), vchData.begin() + 32, vchData.size() > 32 && vchData[32] == 1);
    return ret;
}
Пример #3
0
bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn)
{
    {
        LOCK(cs_KeyStore);
        if (!SetCrypted())
            return false;

        CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
        for (; mi != mapCryptedKeys.end(); ++mi)
        {
            const CPubKey &vchPubKey = (*mi).second.first;
            const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
            CKeyingMaterial vchSecret;
            if(!DecryptSecret(vMasterKeyIn, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
                return false;
            if (vchSecret.size() != 32)
                return false;
            CKey key;
            key.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed());
            if (key.GetPubKey() == vchPubKey)
                break;
            return false;
        }
        vMasterKey = vMasterKeyIn;
    }
    NotifyStatusChanged(this);
    return true;
}
Пример #4
0
    bool SetCheckpointPrivKey(std::string strPrivKey)
    {
        // do nothing for testnet
        // if (fTestNet)
        //     return true;

        // Test signing a sync-checkpoint with genesis block
        CSyncCheckpoint checkpoint;
        checkpoint.hashCheckpoint = fTestNet ? hashGenesisBlockTestNet: hashGenesisBlock;
        CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
        sMsg << (CUnsignedSyncCheckpoint)checkpoint;
        checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());

        std::vector<unsigned char> vchPrivKey = ParseHex(strPrivKey);
        CKey key;

        // if key is not correct openssl may crash
        key.Set(vchPrivKey.begin(), vchPrivKey.end(), false);
        if (!key.IsValid())
            return error("SetCheckpointPrivKey: failed to set private key.");

        if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
            return error("SetCheckpointPrivKey: failed to test sign.");

        // Test signing successful, proceed
        CSyncCheckpoint::strMasterPrivKey = strPrivKey;
        printf("SetCheckpointPrivKey: successfully set private key.");
        return true;
    }
CKey CCommerciumSecret::GetKey() {
    CKey ret;
    assert(vchData.size() >= 32);
    ret.Set(vchData.begin(), vchData.begin() + 32,
            vchData.size() > 32 && vchData[32] == 1);
    return ret;
}
Пример #6
0
    void SignAndSave(CAlert alert, const std::string filename) {
        //serialze alert message
        CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
        sMsg << (CUnsignedAlert)alert;
        alert.vchMsg.reserve(sMsg.size());
        for(size_t i=0; i<sMsg.size(); i++) {
            alert.vchMsg.push_back(sMsg[i]);
        }

        //a dummy secret key with the public key
        //0469204F0E1800E16C1F85176BDC27A245F09987DB71A1EF5C4BD48A42F9AFD1D74F21469488DB552B594AC29CE667AD60DAAD0FFBCE03FB0C2AC49FFB07B36DC5
        //set to match the mainnet vAlertPubKey from chainparams.cpp
        const std::vector<unsigned char> secretKey = ParseHex("1A4976EE6174D80B8B3FF5E9B9C6E638CABFA9A5975557FEA967BC089A5584EE");
        CKey secret;
        secret.Set(secretKey.begin(), secretKey.end(), false);
        assert(secret.IsValid());
        
        //sign alert
        secret.Sign(alert.GetHash(), alert.vchSig);
        assert(alert.CheckSignature());
        
        //serialize alert
        CDataStream ss(SER_DISK, CLIENT_VERSION);
        ss << alert;
        
        //write alert
        std::ofstream fs;
        fs.open(filename.c_str(), std::ios::out | std::ios::app | std::ios::binary);
        fs.write((char*)&ss[0], ss.size());
        fs.close();
    }
Пример #7
0
// Microbenchmark for verification of a basic P2WPKH script. Can be easily
// modified to measure performance of other types of scripts.
static void VerifyScriptBench(benchmark::State& state)
{
    const int flags = SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH;
    const int witnessversion = 0;

    // Keypair.
    CKey key;
    static const std::array<unsigned char, 32> vchKey = {
        {
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
        }
    };
    key.Set(vchKey.begin(), vchKey.end(), false);
    CPubKey pubkey = key.GetPubKey();
    uint160 pubkeyHash;
    CHash160().Write(pubkey.begin(), pubkey.size()).Finalize(pubkeyHash.begin());

    // Script.
    CScript scriptPubKey = CScript() << witnessversion << ToByteVector(pubkeyHash);
    CScript scriptSig;
    CScript witScriptPubkey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(pubkeyHash) << OP_EQUALVERIFY << OP_CHECKSIG;
    const CMutableTransaction& txCredit = BuildCreditingTransaction(scriptPubKey);
    CMutableTransaction txSpend = BuildSpendingTransaction(scriptSig, txCredit);
    CScriptWitness& witness = txSpend.vin[0].scriptWitness;
    witness.stack.emplace_back();
    key.Sign(SignatureHash(witScriptPubkey, txSpend, 0, SIGHASH_ALL, txCredit.vout[0].nValue, SigVersion::WITNESS_V0), witness.stack.back());
    witness.stack.back().push_back(static_cast<unsigned char>(SIGHASH_ALL));
    witness.stack.push_back(ToByteVector(pubkey));

    // Benchmark.
    while (state.KeepRunning()) {
        ScriptError err;
        bool success = VerifyScript(
            txSpend.vin[0].scriptSig,
            txCredit.vout[0].scriptPubKey,
            &txSpend.vin[0].scriptWitness,
            flags,
            MutableTransactionSignatureChecker(&txSpend, 0, txCredit.vout[0].nValue),
            &err);
        assert(err == SCRIPT_ERR_OK);
        assert(success);

#if defined(HAVE_CONSENSUS_LIB)
        CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
        stream << txSpend;
        int csuccess = fujicoinconsensus_verify_script_with_amount(
            txCredit.vout[0].scriptPubKey.data(),
            txCredit.vout[0].scriptPubKey.size(),
            txCredit.vout[0].nValue,
            (const unsigned char*)stream.data(), stream.size(), 0, flags, nullptr);
        assert(csuccess == 1);
#endif
    }
}
Пример #8
0
static bool DecryptKey(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char>& vchCryptedSecret, const CPubKey& vchPubKey, CKey& key)
{
    CKeyingMaterial vchSecret;
    if(!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
        return false;

    if (vchSecret.size() != 32)
        return false;

    key.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed());
    return key.VerifyPubKey(vchPubKey);
}
Пример #9
0
bool WalletUtilityDB::DecryptKey(const std::vector<unsigned char>& vchCryptedSecret, const CPubKey& vchPubKey, CKey& key)
{
    CKeyingMaterial vchSecret;
    if(!DecryptSecret(vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
        return false;

    if (vchSecret.size() != 32)
        return false;

    key.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed());
    return true;
}
Пример #10
0
bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn)
{
    {
        LOCK(cs_KeyStore);
        if (!SetCrypted())
            return false;

        bool keyPass = false;
        bool keyFail = false;
        CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
        for (; mi != mapCryptedKeys.end(); ++mi)
        {
            const CPubKey &vchPubKey = (*mi).second.first;
            const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
            CKeyingMaterial vchSecret;
            if(!DecryptSecret(vMasterKeyIn, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
            {
                keyFail = true;
                break;
            }
            if (vchSecret.size() != 32)
            {
                keyFail = true;
                break;
            }
            CKey key;
            key.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed());
            if (key.GetPubKey() != vchPubKey)
            {
                keyFail = true;
                break;
            }
            keyPass = true;
            if (fDecryptionThoroughlyChecked)
                break;
        }
        if (keyPass && keyFail)
        {
            LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.");
            assert(false);
        }
        if (keyFail || !keyPass)
            return false;
        vMasterKey = vMasterKeyIn;
        fDecryptionThoroughlyChecked = true;
    }
    NotifyStatusChanged(this);
    return true;
}
Пример #11
0
CKey DecodeSecret(const std::string& str)
{
    CKey key;
    std::vector<unsigned char> data;
    if (DecodeBase58Check(str, data)) {
        const std::vector<unsigned char>& privkey_prefix = Params().Base58Prefix(CChainParams::SECRET_KEY);
        if ((data.size() == 32 + privkey_prefix.size() || (data.size() == 33 + privkey_prefix.size() && data.back() == 1)) &&
            std::equal(privkey_prefix.begin(), privkey_prefix.end(), data.begin())) {
            bool compressed = data.size() == 33 + privkey_prefix.size();
            key.Set(data.begin() + privkey_prefix.size(), data.begin() + privkey_prefix.size() + 32, compressed);
        }
    }
    memory_cleanse(data.data(), data.size());
    return key;
}
Пример #12
0
/* The old namecoind encrypted not the 32-byte secret, but the full 279-byte
   serialised keys.  Thus, we need to handle both formats.  This is done
   by the following utility routine:  It decrypts a secret and initialises
   a CKey object from it.  */
static bool DecryptKey(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char>& vchCryptedSecret, const CPubKey& vchPubKey, CKey& key)
{
    CKeyingMaterial vchSecret;
    if(!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
        return false;
    //LogPrintf("%s : decrypted %u-byte key\n", __func__, vchSecret.size());

    if (vchSecret.size() == 32)
    {
        key.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed());
        return true;
    }

    return key.SetPrivKey(vchSecret, vchPubKey.IsCompressed());
}
Пример #13
0
void dumpKeyInfo(uint256 secret)
{
    CKey key;
    CAnoncoinSecret b58secret;
    printf("  * secret (hex): %s\n", secret.GetHex().c_str());
    for (int nCompressed=0; nCompressed<2; nCompressed++)
    {
        bool fCompressed = nCompressed == 1;
        printf("  * %s:\n", fCompressed ? "compressed" : "uncompressed");
        key.Set( secret.begin(), secret.end(), fCompressed );
        b58secret.SetKey( key );
        printf("    * secret (base58): %s\n", b58secret.ToString().c_str());
        CPubKey pubkey = key.GetPubKey();
        printf("    * address (base58): %s\n", CAnoncoinAddress(CTxDestination(pubkey.GetID())).ToString().c_str() );
    }
}
Пример #14
0
void Bip38ToolDialog::on_decryptKeyButton_DEC_clicked()
{
    string strPassphrase = ui->passphraseIn_DEC->text().toStdString();
    string strKey = ui->encryptedKeyIn_DEC->text().toStdString();

    uint256 privKey;
    bool fCompressed;
    if (!BIP38_Decrypt(strPassphrase, strKey, privKey, fCompressed)) {
        ui->statusLabel_DEC->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_DEC->setText(tr("Failed to decrypt.") + QString(" ") + tr("Please check the key and passphrase and try again."));
        return;
    }

    key.Set(privKey.begin(), privKey.end(), fCompressed);
    CPubKey pubKey = key.GetPubKey();
    CBitcoinAddress address(pubKey.GetID());

    ui->decryptedKeyOut_DEC->setText(QString::fromStdString(CBitcoinSecret(key).ToString()));
    ui->addressOut_DEC->setText(QString::fromStdString(address.ToString()));
}
Пример #15
0
bool CCryptoKeyStore::GetKey(const CKeyID &address, CKey& keyOut) const
{
    {
        LOCK(cs_KeyStore);
        if (!IsCrypted())
            return CBasicKeyStore::GetKey(address, keyOut);

        CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
        if (mi != mapCryptedKeys.end())
        {
            const CPubKey &vchPubKey = (*mi).second.first;
            const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
            CKeyingMaterial vchSecret;
            if (!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
                return false;
            if (vchSecret.size() != 32)
                return false;
            keyOut.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed());
            return true;
        }
    }
    return false;
}
Пример #16
0
    bool SendSyncCheckpoint(uint256 hashCheckpoint)
    {
        CSyncCheckpoint checkpoint;
        checkpoint.hashCheckpoint = hashCheckpoint;
        CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
        sMsg << (CUnsignedSyncCheckpoint)checkpoint;
        checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());

        if (CSyncCheckpoint::strMasterPrivKey.empty())
            return error("SendSyncCheckpoint: Checkpoint master private key unavailable.");

        std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey);
        CKey key;

        // if key is not correct openssl may crash
        key.Set(vchPrivKey.begin(), vchPrivKey.end(), false);
        if (!key.IsValid())
            return error("SendSyncCheckpoint: failed to set private key.");

        if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
            return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");

        if(!checkpoint.ProcessSyncCheckpoint(NULL))
        {
            printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n");
            return false;
        }

        printf("SendSyncCheckpoint: about to relay checkpoint.\n");
        // Relay checkpoint
        {
            LOCK(cs_vNodes);
            BOOST_FOREACH(CNode* pnode, vNodes)
                checkpoint.RelayTo(pnode);
        }
        return true;
    }
Пример #17
0
CKey CBitcoinSecret::GetKey() {
    CKey ret;
    ret.Set(&vchData[0], &vchData[32], vchData.size() > 32 && vchData[32] == 1);
    return ret;
}
Пример #18
0
CKey CCM_UppercaseCoinNameSecret::GetKey() {
    CKey ret;
    ret.Set(&vchData[0], &vchData[32], vchData.size() > 32 && vchData[32] == 1);
    return ret;
}
bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn)
{
    if (fDebug)
        LogPrintf("CCryptoKeyStore::Unlock()\n");
    
    {
        LOCK(cs_KeyStore);
        if (!SetCrypted())
            return false;
        
        int nUnlocked = 0;
        
        CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
        for (; mi != mapCryptedKeys.end(); ++mi)
        {
            const CPubKey &vchPubKey = (*mi).second.first;
            const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
            CSecret vchSecret;
            
            if (vchCryptedSecret.size() < 1) // key was recieved from stealth/anon txn with wallet locked, will be expanded after this
            {
                if (fDebug)
                    LogPrintf("Skipping unexpanded key %s.\n", vchPubKey.GetHash().ToString().c_str());
                continue;
            };
            
            if (!DecryptSecret(vMasterKeyIn, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
            {
                LogPrintf("DecryptSecret() failed.\n");
                return false;
            };
            
            if (vchSecret.size() != 32)
                return false;
            
            CKey key;
            key.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed());
            
            if (key.GetPubKey() != vchPubKey)
            {
                LogPrintf("Unlock failed: PubKey mismatch %s.\n", vchPubKey.GetHash().ToString().c_str());
                return false;
            };
            
            nUnlocked++;
            break;
        };
        
        if (nUnlocked < 1) // at least 1 key must pass the test
        {
            if (mapCryptedKeys.size() > 0)
            {
                LogPrintf("Unlock failed: No keys unlocked.\n");
                return false;
            };
        };
        
        vMasterKey = vMasterKeyIn;
    }
    
    NotifyStatusChanged(this);
    
    return true;
}
Пример #20
0
CKey CSharkfundSecret::GetKey() {
	CKey ret;
	ret.Set(&vchData[0], &vchData[32], vchData.size() > 32 && vchData[32] == 1);
	return ret;
}
Пример #21
0
CKey CMonetaryUnitSecret::GetKey() {
    CKey ret;
    ret.Set(&vchData[0], &vchData[32], vchData.size() > 32 && vchData[32] == 1);
    return ret;
}