Public_PEM Keystore::public_PEM() { auto pem = Botan::X509::PEM_encode(public_key()); //printf("PEM:\n%s\n", pem.c_str()); //auto pem = Botan::PEM_Code::encode(data, "PUBLIC KEY"); return pem; }
int main() { ifstream common("common.ecs"); /* construct file I/O streams */ ifstream public_key("public.ecs"); ifstream message; ifstream signature; ECn G,Pub; int bits,ep; Big a,b,p,q,x,y,v,u1,u2,r,s,h; char ifname[13],ofname[13]; miracl *mip=&precision; /* get public data */ common >> bits; mip->IOBASE=16; common >> p >> a >> b >> q >> x >> y; mip->IOBASE=10; ecurve(a,b,p,MR_PROJECTIVE); G=ECn(x,y); /* get public key of signer */ public_key >> ep >> x; Pub=ECn(x,ep); // decompress /* get message */ cout << "signed file = " ; cin.sync(); cin.getline(ifname,13); strcpy(ofname,ifname); strip(ofname); strcat(ofname,".ecs"); message.open(ifname,ios::binary|ios::in|ios::nocreate); if (!message) { /* no message */ cout << "Unable to open file " << ifname << "\n"; return 0; } h=hash(message); signature.open(ofname,ios::in|ios::nocreate); if (!signature) { /* no signature */ cout << "signature file " << ofname << " does not exist\n"; return 0; } signature >> r >> s; if (r>=q || s>=q) { cout << "Signature is NOT verified\n"; return 0; } s=inverse(s,q); u1=(h*s)%q; u2=(r*s)%q; G=mul(u2,Pub,u1,G); G.get(v); v%=q; if (v==r) cout << "Signature is verified\n"; else cout << "Signature is NOT verified\n"; return 0; }
public_key private_key::get_public_key()const { FC_ASSERT( my->_key != empty_priv ); public_key_data pub; unsigned int pk_len; FC_ASSERT( secp256k1_ec_pubkey_create( detail::_get_context(), (unsigned char*) pub.begin(), (int*) &pk_len, (unsigned char*) my->_key.data(), 1 ) ); FC_ASSERT( pk_len == pub.size() ); return public_key(pub); }
static bool generate_keys(ScopedEVP_PKEY &private_key_out, ScopedEVP_PKEY &public_key_out) { ScopedEVP_PKEY private_key(EVP_PKEY_new(), EVP_PKEY_free); ScopedEVP_PKEY public_key(EVP_PKEY_new(), EVP_PKEY_free); ScopedRSA rsa(RSA_new(), RSA_free); ScopedBIGNUM e(BN_new(), BN_free); if (!private_key) { LOGE("Failed to allocate private key"); openssl_log_errors(); return false; } if (!public_key) { LOGE("Failed to allocate public key"); openssl_log_errors(); return false; } if (!rsa) { LOGE("Failed to allocate RSA"); openssl_log_errors(); return false; } if (!e) { LOGE("Failed to allocate BIGNUM"); openssl_log_errors(); return false; } BN_set_word(e.get(), RSA_F4); if (RSA_generate_key_ex(rsa.get(), 2048, e.get(), nullptr) < 0) { LOGE("RSA_generate_key_ex() failed"); openssl_log_errors(); return false; } if (!EVP_PKEY_assign_RSA(private_key.get(), RSAPrivateKey_dup(rsa.get()))) { LOGE("EVP_PKEY_assign_RSA() failed for private key"); openssl_log_errors(); return false; } if (!EVP_PKEY_assign_RSA(public_key.get(), RSAPublicKey_dup(rsa.get()))) { LOGE("EVP_PKEY_assign_RSA() failed for public key"); openssl_log_errors(); return false; } private_key_out = std::move(private_key); public_key_out = std::move(public_key); return true; }
SigVerifyResult verify_signature(const char *path, const char *sig_path) { for (const std::string &hex_der : valid_certs) { std::string der; if (!hex2bin(hex_der, der)) { LOGE("Failed to convert hex-encoded certificate to binary: %s", hex_der.c_str()); return SigVerifyResult::Failure; } // Cast to (void *) is okay since BIO_new_mem_buf() creates a read-only // BIO object ScopedBIO bio_x509_cert(BIO_new_mem_buf( der.data(), static_cast<int>(der.size())), BIO_free); if (!bio_x509_cert) { LOGE("Failed to create BIO for X509 certificate: %s", hex_der.c_str()); openssl_log_errors(); return SigVerifyResult::Failure; } // Load DER-encoded certificate ScopedX509 cert(d2i_X509_bio(bio_x509_cert.get(), nullptr), X509_free); if (!cert) { LOGE("Failed to load X509 certificate: %s", hex_der.c_str()); openssl_log_errors(); return SigVerifyResult::Failure; } // Get public key from certificate ScopedEVP_PKEY public_key(X509_get_pubkey(cert.get()), EVP_PKEY_free); if (!public_key) { LOGE("Failed to load public key from X509 certificate: %s", hex_der.c_str()); openssl_log_errors(); return SigVerifyResult::Failure; } SigVerifyResult result = verify_signature_with_key(path, sig_path, *public_key); if (result == SigVerifyResult::Invalid) { // Keep trying ... continue; } return result; } return SigVerifyResult::Invalid; }
byte_array dsa160_key::id() const { assert(type() != invalid); crypto::hash::value hash = sha256::hash(public_key()); byte_array id(hash); // Only use 160 bits of the hash to produce the ID, // because the cryptographic strength of the resulting ID // is limited anyway by the 160-bit digest size, below. // We're not using SHA-256 to get more than 160 bits of security, // but in hopes it will withstand the recent attacks against SHA-1. id.resize(160/8); return id; }
TEST(SignTest, TestLoadValidPemKeys) { ScopedEVP_PKEY private_key(nullptr, EVP_PKEY_free); ScopedEVP_PKEY public_key(nullptr, EVP_PKEY_free); ScopedBIO bio_private_key_enc(BIO_new(BIO_s_mem()), BIO_free); ASSERT_TRUE(!!bio_private_key_enc); ScopedBIO bio_private_key_noenc(BIO_new(BIO_s_mem()), BIO_free); ASSERT_TRUE(!!bio_private_key_noenc); ScopedBIO bio_public_key(BIO_new(BIO_s_mem()), BIO_free); ASSERT_TRUE(!!bio_public_key); // Generate keys ASSERT_TRUE(generate_keys(private_key, public_key)); // Write keys ASSERT_TRUE(PEM_write_bio_PrivateKey(bio_private_key_enc.get(), private_key.get(), EVP_des_ede3_cbc(), nullptr, 0, nullptr, const_cast<char *>("testing"))); ASSERT_TRUE(PEM_write_bio_PrivateKey(bio_private_key_noenc.get(), private_key.get(), nullptr, nullptr, 0, nullptr, nullptr)); ASSERT_TRUE(PEM_write_bio_PUBKEY(bio_public_key.get(), public_key.get())); // Read back the keys ScopedEVP_PKEY private_key_enc_read(mb::sign::load_private_key( bio_private_key_enc.get(), mb::sign::KEY_FORMAT_PEM, "testing"), EVP_PKEY_free); ASSERT_TRUE(!!private_key_enc_read); ScopedEVP_PKEY private_key_noenc_read(mb::sign::load_private_key( bio_private_key_noenc.get(), mb::sign::KEY_FORMAT_PEM, nullptr), EVP_PKEY_free); ASSERT_TRUE(!!private_key_noenc_read); ScopedEVP_PKEY public_key_read(mb::sign::load_public_key( bio_public_key.get(), mb::sign::KEY_FORMAT_PEM, "testing"), EVP_PKEY_free); ASSERT_TRUE(!!public_key_read); // Compare keys ASSERT_EQ(EVP_PKEY_cmp(private_key.get(), private_key_enc_read.get()), 1); ASSERT_EQ(EVP_PKEY_cmp(private_key.get(), private_key_noenc_read.get()), 1); ASSERT_EQ(EVP_PKEY_cmp(public_key.get(), public_key_read.get()), 1); }
TEST(SignTest, TestLoadValidPemKeysWithInvalidPassphrase) { ScopedEVP_PKEY private_key(nullptr, EVP_PKEY_free); ScopedEVP_PKEY public_key(nullptr, EVP_PKEY_free); ScopedBIO bio(BIO_new(BIO_s_mem()), BIO_free); ASSERT_TRUE(!!bio); // Generate keys ASSERT_TRUE(generate_keys(private_key, public_key)); // Write key ASSERT_TRUE(PEM_write_bio_PrivateKey(bio.get(), private_key.get(), EVP_des_ede3_cbc(), nullptr, 0, nullptr, const_cast<char *>("testing"))); // Read back the key using invalid password ScopedEVP_PKEY private_key_read(mb::sign::load_private_key( bio.get(), mb::sign::KEY_FORMAT_PEM, "gnitset"), EVP_PKEY_free); ASSERT_FALSE(private_key_read); }
TEST(SignTest, TestLoadInvalidPkcs12PrivateKey) { ScopedBIO bio_private_key(BIO_new(BIO_s_mem()), BIO_free); ASSERT_TRUE(!!bio_private_key); ScopedBIO bio_public_key(BIO_new(BIO_s_mem()), BIO_free); ASSERT_TRUE(!!bio_public_key); // Fill with garbage ASSERT_EQ(BIO_write(bio_private_key.get(), "abcdefghijklmnopqrstuvwxyz", 26), 26); ASSERT_EQ(BIO_write(bio_public_key.get(), "zyxwvutsrqponmlkjihgfedcba", 26), 26); ScopedEVP_PKEY private_key(mb::sign::load_private_key( bio_private_key.get(), mb::sign::KEY_FORMAT_PKCS12, nullptr), EVP_PKEY_free); ASSERT_FALSE(private_key); ScopedEVP_PKEY public_key(mb::sign::load_public_key( bio_public_key.get(), mb::sign::KEY_FORMAT_PKCS12, nullptr), EVP_PKEY_free); ASSERT_FALSE(public_key); }
PKCS11_EC_PrivateKey::PKCS11_EC_PrivateKey(Session& session, const std::vector<uint8_t>& ec_params, const EC_PrivateKeyGenerationProperties& props) : Object(session) { m_domain_params = EC_Group(ec_params); EC_PublicKeyGenerationProperties pub_key_props(ec_params); pub_key_props.set_verify(true); pub_key_props.set_private(false); pub_key_props.set_token(false); // don't create a persistent public key object ObjectHandle pub_key_handle = CK_INVALID_HANDLE; ObjectHandle priv_key_handle = CK_INVALID_HANDLE; Mechanism mechanism = { CKM_EC_KEY_PAIR_GEN, nullptr, 0 }; session.module()->C_GenerateKeyPair(session.handle(), &mechanism, pub_key_props.data(), pub_key_props.count(), props.data(), props.count(), &pub_key_handle, &priv_key_handle); this->reset_handle(priv_key_handle); Object public_key(session, pub_key_handle); m_public_key = decode_public_point(public_key.get_attribute_value(AttributeType::EcPoint), m_domain_params.get_curve()); }
int main() { /* encode using public key */ Big e,m,y,ke,mn,mx; ifstream public_key("public.key"); ifstream input_file; ofstream output_file; static char line[500]; static char buff[256]; static char ifname[13],ofname[13]; BOOL fli,last; int i,ipt,klen; miracl *mip=&precision; mip->IOBASE=60; public_key >> ke; mn=root(ke,3); mx=mn*mn*mn-mn*mn; /* find key length in characters */ klen=bits(mx)/7; cout << "file to be encoded = " ; cin.getline(ifname,13); fli=FALSE; if (strlen(ifname)>0) fli=TRUE; if (fli) { /* set up input file */ strcpy(ofname,ifname); strip(ofname); strcat(ofname,".rsa"); input_file.open(ifname,ios::in|ios::nocreate); if (!input_file) { cout << "Unable to open file " << ifname << "\n"; return 0; } cout << "encoding message\n"; } else { /* accept input from keyboard */ cout << "output filename = "; cin >> ofname; strip(ofname); strcat(ofname,".rsa"); cout << "input message - finish with cntrl z\n"; } output_file.open(ofname); ipt=0; last=FALSE; while (!last) { /* encode line by line */ if (fli) { input_file.getline(&line[ipt],132); if (input_file.eof() || input_file.fail()) last=TRUE; } else { cin.getline(&line[ipt],132); if (cin.eof() || cin.fail()) last=TRUE; } strcat(line,"\n"); ipt=strlen(line); if (ipt<klen && !last) continue; while (ipt>=klen) { /* chop up into klen-sized chunks and encode */ for (i=0;i<klen;i++) buff[i]=line[i]; buff[klen]='\0'; for (i=klen;i<=ipt;i++) line[i-klen]=line[i]; ipt-=klen; mip->IOBASE=128; m=buff; e=pow(m,3,ke); mip->IOBASE=60; output_file << e << endl; } if (last && ipt>0) { /* now deal with left overs */ mip->IOBASE=128; m=line; if (m<mn) { /* pad out with random number if necessary */ m+=mn*(mn*mn-rand(mn)); } e=pow(m,3,ke); mip->IOBASE=60; output_file << e << endl; } } return 0; }
RefPtr<DtlsIdentity> DtlsIdentity::Generate() { UniquePK11SlotInfo slot(PK11_GetInternalSlot()); if (!slot) { return nullptr; } uint8_t random_name[16]; SECStatus rv = PK11_GenerateRandomOnSlot(slot.get(), random_name, sizeof(random_name)); if (rv != SECSuccess) return nullptr; std::string name; char chunk[3]; for (size_t i = 0; i < sizeof(random_name); ++i) { SprintfLiteral(chunk, "%.2x", random_name[i]); name += chunk; } std::string subject_name_string = "CN=" + name; UniqueCERTName subject_name(CERT_AsciiToName(subject_name_string.c_str())); if (!subject_name) { return nullptr; } unsigned char paramBuf[12]; // OIDs are small SECItem ecdsaParams = { siBuffer, paramBuf, sizeof(paramBuf) }; SECOidData* oidData = SECOID_FindOIDByTag(SEC_OID_SECG_EC_SECP256R1); if (!oidData || (oidData->oid.len > (sizeof(paramBuf) - 2))) { return nullptr; } ecdsaParams.data[0] = SEC_ASN1_OBJECT_ID; ecdsaParams.data[1] = oidData->oid.len; memcpy(ecdsaParams.data + 2, oidData->oid.data, oidData->oid.len); ecdsaParams.len = oidData->oid.len + 2; SECKEYPublicKey *pubkey; UniqueSECKEYPrivateKey private_key( PK11_GenerateKeyPair(slot.get(), CKM_EC_KEY_PAIR_GEN, &ecdsaParams, &pubkey, PR_FALSE, PR_TRUE, nullptr)); if (private_key == nullptr) return nullptr; UniqueSECKEYPublicKey public_key(pubkey); pubkey = nullptr; UniqueCERTSubjectPublicKeyInfo spki( SECKEY_CreateSubjectPublicKeyInfo(public_key.get())); if (!spki) { return nullptr; } UniqueCERTCertificateRequest certreq( CERT_CreateCertificateRequest(subject_name.get(), spki.get(), nullptr)); if (!certreq) { return nullptr; } // From 1 day before todayto 30 days after. // This is a sort of arbitrary range designed to be valid // now with some slack in case the other side expects // some before expiry. // // Note: explicit casts necessary to avoid // warning C4307: '*' : integral constant overflow static const PRTime oneDay = PRTime(PR_USEC_PER_SEC) * PRTime(60) // sec * PRTime(60) // min * PRTime(24); // hours PRTime now = PR_Now(); PRTime notBefore = now - oneDay; PRTime notAfter = now + (PRTime(30) * oneDay); UniqueCERTValidity validity(CERT_CreateValidity(notBefore, notAfter)); if (!validity) { return nullptr; } unsigned long serial; // Note: This serial in principle could collide, but it's unlikely rv = PK11_GenerateRandomOnSlot(slot.get(), reinterpret_cast<unsigned char *>(&serial), sizeof(serial)); if (rv != SECSuccess) { return nullptr; } UniqueCERTCertificate certificate( CERT_CreateCertificate(serial, subject_name.get(), validity.get(), certreq.get())); if (!certificate) { return nullptr; } PLArenaPool *arena = certificate->arena; rv = SECOID_SetAlgorithmID(arena, &certificate->signature, SEC_OID_ANSIX962_ECDSA_SHA256_SIGNATURE, 0); if (rv != SECSuccess) return nullptr; // Set version to X509v3. *(certificate->version.data) = SEC_CERTIFICATE_VERSION_3; certificate->version.len = 1; SECItem innerDER; innerDER.len = 0; innerDER.data = nullptr; if (!SEC_ASN1EncodeItem(arena, &innerDER, certificate.get(), SEC_ASN1_GET(CERT_CertificateTemplate))) { return nullptr; } SECItem *signedCert = PORT_ArenaZNew(arena, SECItem); if (!signedCert) { return nullptr; } rv = SEC_DerSignData(arena, signedCert, innerDER.data, innerDER.len, private_key.get(), SEC_OID_ANSIX962_ECDSA_SHA256_SIGNATURE); if (rv != SECSuccess) { return nullptr; } certificate->derCert = *signedCert; RefPtr<DtlsIdentity> identity = new DtlsIdentity(Move(private_key), Move(certificate), ssl_kea_ecdh); return identity.forget(); }
/** decodes the big int as base64 string, or a number */ void from_variant( const variant& v, public_key& bi, uint32_t max_depth ) { bi = public_key( v.as<std::vector<char> >(max_depth) ); }
int main() { // Timer auto start = std::chrono::steady_clock::now(); auto end = std::chrono::steady_clock::now(); std::cout << "Timings:" << std::endl; // Precomputation in the clear ECPrecomputation<FV::mess_t> precomputation; // Point G and variable for G+G ECPoint<FV::mess_t> G(G_x, G_y, G_z, G_t), GpG; // Compute 4G = (G+G)+(G+G) with 2 EC additions start = std::chrono::steady_clock::now(); ec_addition(GpG, G, G, precomputation); ec_addition(GpG, GpG, GpG, precomputation); end = std::chrono::steady_clock::now(); std::cout << "\tEC Addition in clear: \t\t" << get_time_us(start, end, 2) << " us" << std::endl; FV::mess_t result_x = GpG.X + FV::params::plaintextModulus<mpz_class>::value(); FV::mess_t result_y = GpG.Y + FV::params::plaintextModulus<mpz_class>::value(); // Multiply by the inverse of Z FV::mess_t iZ = GpG.Z.invert(); GpG.X *= iZ; GpG.Y *= iZ; /** * Let's do it homomorphically */ // Keygen start = std::chrono::steady_clock::now(); FV::sk_t secret_key; end = std::chrono::steady_clock::now(); std::cout << "\tSecret key generation: \t\t" << get_time_us(start, end, 1) << " us" << std::endl; start = std::chrono::steady_clock::now(); FV::evk_t evaluation_key(secret_key, 32); end = std::chrono::steady_clock::now(); std::cout << "\tEvaluation key generation: \t" << get_time_us(start, end, 1) << " us" << std::endl; start = std::chrono::steady_clock::now(); FV::pk_t public_key(secret_key, evaluation_key); end = std::chrono::steady_clock::now(); std::cout << "\tPublic key generation: \t\t" << get_time_us(start, end, 1) << " us" << std::endl; // Precomputation ECPrecomputation<FV::ciphertext_t> precomputation_encrypted; // Point G and variable for G+G FV::ciphertext_t eG_x, eG_y, eG_z, eG_t; FV::mess_t mG_x(G_x), mG_y(G_y), mG_z(G_z), mG_t(G_t); start = std::chrono::steady_clock::now(); FV::encrypt(eG_x, public_key, mG_x); FV::encrypt(eG_y, public_key, mG_y); FV::encrypt(eG_z, public_key, mG_z); FV::encrypt(eG_t, public_key, mG_t); end = std::chrono::steady_clock::now(); std::cout << "\tPoint Encryption: \t\t" << get_time_us(start, end, 1) << " us" << std::endl; ECPoint<FV::ciphertext_t> eG(eG_x, eG_y, eG_z, eG_t), eGpG; // Compute 4G = (G+G)+(G+G) with 2 EC additions start = std::chrono::steady_clock::now(); ec_addition<FV::ciphertext_t>(eGpG, eG, eG, precomputation_encrypted); ec_addition<FV::ciphertext_t>(eGpG, eGpG, eGpG, precomputation_encrypted); end = std::chrono::steady_clock::now(); std::cout << "\tHomom. EC Addition: \t\t" << get_time_us(start, end, 2) / 1000 << " ms" << std::endl; start = std::chrono::steady_clock::now(); FV::decrypt(mG_x, secret_key, public_key, eGpG.X); FV::decrypt(mG_y, secret_key, public_key, eGpG.Y); FV::decrypt(mG_z, secret_key, public_key, eGpG.Z); FV::decrypt(mG_t, secret_key, public_key, eGpG.T); end = std::chrono::steady_clock::now(); std::cout << "\tEC Point Decryption: \t\t" << get_time_us(start, end, 1) << " us" << std::endl; // Noise unsigned noise_x = noise(mG_x, secret_key, public_key, eGpG.X); std::cout << "noise in ciphertext: \t" << noise_x << "/" << public_key.noise_max << std::endl; // Multiply by the inverse of Z FV::mess_t invZ = mG_z.invert(); mG_x *= invZ; mG_y *= invZ; // Results std::cout << "4*G (clear): \t\t(" << GpG.X << "," << GpG.Y << ")" << std::endl; std::cout << "4*G (enc.): \t\t(" << mG_x << "," << mG_y << ")" << std::endl; return 0; }
/* * Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ block_type step(const block_point& root, const block_point& head, size_t n) { std::cout << "Stepping " << n << std::endl; transaction_type coinbase_tx = create_coinbase(public_key()); const block_type* prev_blk = &head.blk; static hash_digest txh6 = null_hash; if (n == 4) { prev_blk = lookup(root, {0, 0, 0}); output_point prevout{ hash_transaction(root.prefix_chain[2].transactions[0]), 0}; transaction_type tx = construct_transaction(prevout); txh6 = hash_transaction(tx); return mine_next(*prev_blk, {coinbase_tx, tx}); } else if (n == 5) { prev_blk = lookup(root, {0, 0, 0, 0}); } else if (n == 6) { output_point prevout{ hash_transaction(root.prefix_chain[1].transactions[0]), 0}; transaction_type tx = construct_transaction(prevout); txh6 = hash_transaction(tx); return mine_next(*prev_blk, {coinbase_tx, tx}); } else if (n == 7) { BITCOIN_ASSERT(txh6 != null_hash); output_point prevout{txh6, 0}; transaction_type tx = construct_transaction(prevout); return mine_next(*prev_blk, {coinbase_tx, tx}); } else if (n == 8) { prev_blk = lookup(root, {0, 0, 0}); } else if (n == 9) { BITCOIN_ASSERT(txh6 != null_hash); output_point prevout{txh6, 0}; transaction_type tx = construct_transaction(prevout); return mine_next(*prev_blk, {coinbase_tx, tx}); } else if (n == 11) { prev_blk = lookup(root, {0, 0, 0, 1}); } else if (n == 15) { // Attempt double spend. output_point prevout{ hash_transaction(root.prefix_chain[2].transactions[0]), 0}; transaction_type tx = construct_transaction(prevout); txh6 = hash_transaction(tx); return mine_next(*prev_blk, {coinbase_tx, tx}); } else if (n == 16) { prev_blk = lookup(root, {0, 0, 0, 2, 0}); } else if (n == 20) { BITCOIN_ASSERT(txh6 != null_hash); output_point prevout{txh6, 0}; transaction_type tx = construct_transaction(prevout); return mine_next(*prev_blk, {coinbase_tx, tx}); } return mine_next(*prev_blk, {coinbase_tx}); }
public_key public_key::from_key_data( const public_key_data &data ) { return public_key(data); }
/** decodes the big int as base64 string, or a number */ void from_variant( const variant& v, public_key& bi ) { bi = public_key( v.as<std::vector<char> >() ); }