GDomNode* GKeyPair::serialize(GDom* pDoc, bool bIncludePrivateKey) { GDomNode* pNode = pDoc->newObj(); if(!n() || !publicKey()) throw Ex("No key has been made yet"); if(bIncludePrivateKey && !privateKey()) throw Ex("This key-pair doesn't include the private key"); pNode->addField(pDoc, "n", n()->serialize(pDoc)); pNode->addField(pDoc, "public", publicKey()->serialize(pDoc)); if(bIncludePrivateKey) pNode->addField(pDoc, "private", privateKey()->serialize(pDoc)); return pNode; }
Scope& Scope::operator=(const Scope& rightSide) { if (&rightSide != this) { if (publicKey() == NULL || strcmp(publicKey(), rightSide.publicKey()) != 0) { clean(); assign(rightSide.ttl(), rightSide.publicKey()); } else { // need to assign TTL only fTTL = rightSide.ttl(); } } return *this; }
void cTWUtil::WriteConfigText(const TCHAR* filename, const TSTRING configText, bool bEncrypt, const cElGamalSigPrivateKey* pPrivateKey) { cSerializableNString nstring; nstring.mString = CONFIG_FILE_MAGIC_8BYTE; std::string ns; cStringUtil::Convert(ns, configText); nstring.mString += ns; cFileHeader fileHeader; fileHeader.SetID(cConfigFile::GetFileHeaderID()); fileHeader.SetVersion(CURRENT_FIXED_VERSION); if (bEncrypt) { ASSERT(pPrivateKey != 0); cElGamalSigPublicKey publicKey(*pPrivateKey); fileHeader.GetBaggage().MapArchive(0, publicKey.GetWriteLen()); publicKey.Write(fileHeader.GetBaggage().GetMap()); } WriteObject(filename, NULL, nstring, fileHeader, bEncrypt, pPrivateKey); iUserNotify::GetInstance()->Notify(iUserNotify::V_NORMAL, _T("%s%s\n"), TSS_GetString(cTW, tw::STR_WRITE_CONFIG_FILE).c_str(), cDisplayEncoder::EncodeInline(filename).c_str()); }
IdentityKeyPair KeyHelper::generateIdentityKeyPair() { ECKeyPair keyPair = Curve::generateKeyPair(); IdentityKey publicKey(keyPair.getPublicKey()); IdentityKeyPair identityKeyPair(publicKey, keyPair.getPrivateKey()); return identityKeyPair; }
/** * @given transaction field values and sample command values, reference tx * @when create transaction with sample command using transaction builder * @then transaction is built correctly */ TEST(ProtoTransaction, Builder) { iroha::protocol::Transaction proto_tx = generateEmptyTransaction(); std::string account_id = "admin@test", asset_id = "coin#test", amount = "10.00"; auto command = proto_tx.mutable_payload()->add_commands()->mutable_add_asset_quantity(); command->CopyFrom(generateAddAssetQuantity(account_id, asset_id)); auto keypair = shared_model::crypto::CryptoProviderEd25519Sha3::generateKeypair(); auto signedProto = shared_model::crypto::CryptoSigner<>::sign( shared_model::crypto::Blob(proto_tx.payload().SerializeAsString()), keypair); auto sig = proto_tx.add_signatures(); sig->set_pubkey(shared_model::crypto::toBinaryString(keypair.publicKey())); sig->set_signature(shared_model::crypto::toBinaryString(signedProto)); auto tx = shared_model::proto::TransactionBuilder() .creatorAccountId(creator_account_id) .addAssetQuantity(account_id, asset_id, amount) .createdTime(created_time) .quorum(1) .build(); auto signedTx = tx.signAndAddSignature(keypair).finish(); auto &proto = signedTx.getTransport(); ASSERT_EQ(proto_tx.SerializeAsString(), proto.SerializeAsString()); }
unsigned char* GKeyPair::powerMod(const unsigned char* pInput, int nInputSize, bool bPublicKey, int* pnOutputSize) { GBigInt input; input.fromByteBuffer(pInput, nInputSize); GBigInt results; results.powerMod(&input, bPublicKey ? publicKey() : privateKey(), n()); *pnOutputSize = results.getUIntCount() * sizeof(unsigned int); unsigned char* pOutput = (unsigned char*)results.toBufferGiveOwnership(); while(pOutput[(*pnOutputSize) - 1] == 0) (*pnOutputSize)--; return pOutput; }
void ABEDemo() { std::cout << "ABE" << std::endl; const size_t Q = size_t(1) << K; std::cout << "generating samples ..." << std::endl; long* samples = gring::readOrBuildSamples<N,Q,K>( "samples", SS ); std::cout << "creating master secret ..." << std::endl; auto msk = new gring::ABEMasterSecret<N,Q,K>{L, samples}; std::cout << "creating public..." << std::endl; auto pk = msk->publicKey(); std::vector< size_t > addWeights{1, 2, 3, 4, 5}; auto gAdd = new gring::ABEAddGate<N,Q,K>{addWeights}; gAdd->print(); std::vector< size_t > mulWeights{1}; auto gMul = new gring::ABEMulGate<N,Q,K>{mulWeights}; gMul->print(); std::vector< size_t > badWeights{5, 4, 3, 2, 1}; auto gBad = new gring::ABEAddGate<N,Q,K>{badWeights}; gBad->print(); std::cout << "creating secret keys ..." << std::endl; auto skAdd = msk->keyGen( gAdd ); auto skMul = msk->keyGen( gMul ); auto skBad = msk->keyGen( gBad ); std::vector< size_t > ident{0, Q-1, Q-1, 0, 1}; auto abeId = gring::ABEId{ident}; abeId.print(); std::cout << "encrypting ..." << std::endl; auto ctxt = pk->encrypt( abeId, msg ); std::cout << "decrypting with skAdd ..." << std::endl; std::string msgPrimeAdd = skAdd->decrypt( ctxt ); std::cout << "msgPrimeAdd: " << msgPrimeAdd << std::endl; std::cout << std::endl; std::cout << "decrypting with skMul ..." << std::endl; std::string msgPrimeMul = skMul->decrypt( ctxt ); std::cout << "msgPrimeMul: " << msgPrimeMul << std::endl; std::cout << std::endl; std::cout << "decrypting with skBad ..." << std::endl; std::string msgPrimeBad = skBad->decrypt( ctxt ); std::cout << "msgPrimeBad: " << msgPrimeBad << std::endl; delete [] samples; }
VncServerClient::AuthState ServerAuthenticationManager::performKeyAuthentication( VncServerClient* client, VariantArrayMessage& message ) { switch( client->authState() ) { case VncServerClient::AuthInit: client->setChallenge( CryptoCore::generateChallenge() ); if( VariantArrayMessage( message.ioDevice() ).write( client->challenge() ).send() ) { return VncServerClient::AuthChallenge; } else { qDebug( "ServerAuthenticationManager::performKeyAuthentication(): failed to send challenge" ); return VncServerClient::AuthFinishedFail; } break; case VncServerClient::AuthChallenge: { // get user role const ItalcCore::UserRoles urole = static_cast<ItalcCore::UserRoles>( message.read().toInt() ); // now try to verify received signed data using public key of the user // under which the client claims to run const QByteArray signature = message.read().toByteArray(); qDebug() << "Loading public key" << LocalSystem::Path::publicKeyPath( urole ) << "for role" << urole; // (publicKeyPath does range-checking of urole) CryptoCore::PublicKey publicKey( LocalSystem::Path::publicKeyPath( urole ) ); if( publicKey.verifyMessage( client->challenge(), signature, CryptoCore::DefaultSignatureAlgorithm ) ) { qDebug( "ServerAuthenticationManager::performKeyAuthentication(): SUCCESS" ); return VncServerClient::AuthFinishedSuccess; } else { qDebug( "ServerAuthenticationManager::performKeyAuthentication(): FAIL" ); return VncServerClient::AuthFinishedFail; } break; } default: break; } return VncServerClient::AuthFinishedFail; }
/* Generates a public/private key-pair. The keys are retured in a * KeyPair. The generated keys are * 2 * "digitCount" or 2 * "digitCount - 1 digits long, * and have the probability of at least 1 - 4^(-k) of being prime. * For k = 3, that probability is 98.4375%, * and for k = 4 it is 99.609375%. * * k = 3 is recommended by Introduction to Algorithms, Second Edition; * by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and * Clifford Stein for prime number generation. * */ KeyPair RSA::GenerateKeyPair( unsigned long int digitCount, unsigned long int k) { //generate two random numbers p and q, each "digitCount" digits long BigInt p(PrimeGenerator::Generate(digitCount, k)); BigInt q(PrimeGenerator::Generate(digitCount, k)); //make sure they are different while (p == q) { p = PrimeGenerator::Generate(digitCount, k); } //calculate the modulus of both the public and private keys, n BigInt n(p * q); //calculate the totient phi BigInt phi((p - 1) * (q - 1)); //we don't want the keys to be less than 20 bits long if (phi < "1048576") throw "Insufficient key strength!"; //select a small odd integer e that is coprime with phi and e < phi //usually 65537 is used, and we will use it too if it fits //it is recommended that this be the least possible value for e BigInt e("65537"); //make sure the requirements are met while (RSA::GCD(phi, e) != BigIntOne || e < "65537") { PrimeGenerator::makeRandom(e, 5); } //now we have enough information to create the public key //e is the public key exponent, n is the modulus Key publicKey(n, e); //calculate d, de = 1 (mod phi) BigInt d(RSA::solveModularLinearEquation(e, BigIntOne, phi)); //we can create the private key //d is the private key exponent, n is the modulus Key privateKey(n, d); //finally, the keypair is created and returned KeyPair newKeyPair(privateKey, publicKey); return newKeyPair; }
int SshConnection::connectHostBased() { qDebug() << "WARNING connectHostBased() not wired correctly"; QString passphrase; QLOG_TRACE() << "SshConnection::connectHostBased"; QString privateKey(getPrivateKeyFile()); QString publicKey(getPublicKeyFile()); int rc; while ((rc = libssh2_userauth_hostbased_fromfile(m_session, m_username.toLatin1().data(), publicKey.toLatin1().data(), privateKey.toLatin1().data(), passphrase.toLatin1().data(), m_hostname.toLatin1().data())) == LIBSSH2_ERROR_EAGAIN); return rc; }
int SshConnection::connectPublicKey() { QLOG_TRACE() << "SshConnection::connectPublicKey"; QString privateKey(getPrivateKeyFile()); QString publicKey(getPublicKeyFile()); qDebug() << "WARNING connectHostBased() not wired correctly"; QString passphrase; int rc; while ((rc = libssh2_userauth_publickey_fromfile(m_session, m_username.toLatin1().data(), publicKey.toLatin1().data(), privateKey.toLatin1().data(), passphrase.toLatin1().data())) == LIBSSH2_ERROR_EAGAIN); if (rc == LIBSSH2_ERROR_AUTHENTICATION_FAILED) rc = LIBSSH2_ERROR_PUBLICKEY_NOT_FOUND; return rc; }
Name IdentityManager::createIdentityCertificate(const Name& certificatePrefix, const Name& signerCertificateName, const MillisecondsSince1970& notBefore, const MillisecondsSince1970& notAfter) { Name keyName = getKeyNameFromCertificatePrefix(certificatePrefix); Blob keyBlob = identityStorage_->getKey(keyName); ptr_lib::shared_ptr<PublicKey> publicKey(new PublicKey(keyBlob)); ptr_lib::shared_ptr<IdentityCertificate> certificate = createIdentityCertificate (certificatePrefix, *publicKey, signerCertificateName, notBefore, notAfter); identityStorage_->addCertificate(*certificate); return certificate->getName(); }
// ----------------------------------------------------------------------------- // RoapStorageClient::GetDevicePublicKeyDerL // ----------------------------------------------------------------------------- // EXPORT_C TInt Roap::RRoapStorageClient::GetDevicePublicKeyDerL( HBufC8*& aPublicKey ) { TInt size = 0; TInt error = KErrNone; TPckg<TInt> package( size ); error = SendReceive( Roap::EGetPublicKey, TIpcArgs( &package ) ); User::LeaveIfError( error ); HBufC8* publicKey( HBufC8::NewMaxLC( size ) ); TPtr8 objectPkg( const_cast<TUint8*> ( publicKey->Ptr() ), size, size ); User::LeaveIfError( SendReceive( Roap::EGetData, TIpcArgs( &objectPkg ) ) ); CleanupStack::Pop( publicKey ); aPublicKey = publicKey; return KErrNone; }
bool Cryptography::GenerateKeyPair() { QDir dir; dir.mkdir("cryptography"); CryptoPP::AutoSeededRandomPool prng; CryptoPP::InvertibleRSAFunction privateKey; privateKey.Initialize(prng, 1024); CryptoPP::RSAFunction publicKey(privateKey); CryptoPP::FileSink privKeyFile("cryptography/wakbox.ppk"); CryptoPP::FileSink pubKeyFile("cryptography/wakbox.pub"); privateKey.Save(privKeyFile); publicKey.Save(pubKeyFile); return LoadKeyPair(); }
// ----------------------------------------------------------------------------- // RoapStorageClient::VerifyL // ----------------------------------------------------------------------------- // EXPORT_C TBool Roap::RRoapStorageClient::VerifyL( const TDesC8& aSignature, const TDesC8& aHash, const RPointerArray<HBufC8>& aCertificateChain ) { CRSAPublicKey* publicKey( NULL ); TBool r( ETrue ); CX509Certificate* cert( NULL ); TX509KeyFactory factory; if ( aCertificateChain.Count() <= 0 ) { User::Leave( KErrArgument ); } cert = CX509Certificate::NewLC( *aCertificateChain[0] ); publicKey = factory.RSAPublicKeyL( cert->PublicKey().KeyData() ); CleanupStack::PushL( publicKey ); r = OmaCrypto::RsaPssVerifyHashL( publicKey, aSignature, aHash ); CleanupStack::PopAndDestroy( publicKey ); CleanupStack::PopAndDestroy( cert ); return r; }
ptr_lib::shared_ptr<IdentityCertificate> IdentityManager::selfSign(const Name& keyName) { ptr_lib::shared_ptr<IdentityCertificate> certificate(new IdentityCertificate()); Blob keyBlob = identityStorage_->getKey(keyName); ptr_lib::shared_ptr<PublicKey> publicKey(new PublicKey(keyBlob)); #if NDN_CPP_HAVE_GMTIME_SUPPORT time_t nowSeconds = time(NULL); struct tm current = *gmtime(&nowSeconds); current.tm_hour = 0; current.tm_min = 0; current.tm_sec = 0; MillisecondsSince1970 notBefore = timegm(¤t) * 1000.0; current.tm_year = current.tm_year + 2; MillisecondsSince1970 notAfter = timegm(¤t) * 1000.0; certificate->setNotBefore(notBefore); certificate->setNotAfter(notAfter); #else // Don't really expect this to happen. throw SecurityException("selfSign: Can't set certificate validity because time functions are not supported by the standard library."); #endif Name certificateName = keyName.getPrefix(-1).append("KEY").append (keyName.get(-1)).append("ID-CERT").append (Name::Component::fromNumber((uint64_t)ndn_getNowMilliseconds())); certificate->setName(certificateName); certificate->setPublicKeyInfo(*publicKey); certificate->addSubjectDescription(CertificateSubjectDescription("2.5.4.41", keyName.toUri())); certificate->encode(); signByCertificate(*certificate, certificate->getName()); return certificate; }
void DL_PrivateKey_EC<EC>::BERDecodeKey2(BufferedTransformation &bt, bool parametersPresent, unsigned int size) { BERSequenceDecoder seq(bt); word32 version; BERDecodeUnsigned<word32>(seq, version, INTEGER, 1, 1); // check version BERGeneralDecoder dec(seq, OCTET_STRING); if (!dec.IsDefiniteLength()) BERDecodeError(); Integer x; x.Decode(dec, dec.RemainingLength()); dec.MessageEnd(); if (!parametersPresent && seq.PeekByte() != (CONTEXT_SPECIFIC | CONSTRUCTED | 0)) BERDecodeError(); if (!seq.EndReached() && seq.PeekByte() == (CONTEXT_SPECIFIC | CONSTRUCTED | 0)) { BERGeneralDecoder parameters(seq, CONTEXT_SPECIFIC | CONSTRUCTED | 0); AccessGroupParameters().BERDecode(parameters); parameters.MessageEnd(); } if (!seq.EndReached()) { // skip over the public element SecByteBlock subjectPublicKey; unsigned int unusedBits; BERGeneralDecoder publicKey(seq, CONTEXT_SPECIFIC | CONSTRUCTED | 1); BERDecodeBitString(publicKey, subjectPublicKey, unusedBits); publicKey.MessageEnd(); Element Q; if (!(unusedBits == 0 && GetGroupParameters().GetCurve().DecodePoint(Q, subjectPublicKey, subjectPublicKey.size()))) BERDecodeError(); } seq.MessageEnd(); SetPrivateExponent(x); }
void dialog_createavatar::InitElements() { stringw title = stringw(lang_[L"CreateAvatar_WindowTitle"].c_str()); window_ = new CGUIDecentralisedDialog(env_, env_->getRootGUIElement(), e_gui_elements::WindowCreateAvatar, rect<s32>(80, 40, 400, 250), true); window_->setDialogSkin(elems_.TxDialogBack, elems_.TxDialogFore); window_->setVisible(true); window_->setText(title.c_str()); env_->setFocus(window_); window_->drop(); s32 posy = 40; elems_.CreateAvPublicKeyLabel = env_->addStaticText(lang_[L"CreateAvatar_PublicKeyLabel"].c_str(), rect<s32>(20, posy, 260, posy + 22), false, true, window_, 0); posy += 22; elems_.CreateAvPublicKeyBox = new CGUIDecentralisedTextbox(L"", true, env_, window_, e_gui_elements::CreateAvPasswordBox, rect<s32>(20, posy, 295, posy + 22)); elems_.CreateAvPublicKeyBox->setEnabled(false); elems_.CreateAvPublicKeyBox->setOverrideColor(SColor(255, 0, 0, 0)); posy += 32; elems_.CreateAvFirstNameLabel = env_->addStaticText(lang_[L"CreateAvatar_FirstnameLabel"].c_str(), rect<s32>(20, posy, 140, posy + 22), false, true, window_, 0); elems_.CreateAvLastNameLabel = env_->addStaticText(lang_[L"CreateAvatar_LastnameLabel"].c_str(), rect<s32>(160, posy, 310, posy + 22), false, true, window_, 0); posy += 22; elems_.CreateAvFirstNameTextBox = new CGUIDecentralisedTextbox(L"", true, env_, window_, e_gui_elements::CreateAvFirstnameBox, rect<s32>(20, posy, 155, posy + 22)); elems_.CreateAvFirstNameTextBox->setEnabled(true); elems_.CreateAvFirstNameTextBox->setOverrideColor(SColor(255, 0, 0, 0)); elems_.CreateAvFirstNameTextBox->drop(); elems_.CreateAvLastNameTextBox = new CGUIDecentralisedTextbox(L"", true, env_, window_, e_gui_elements::CreateAvLastnameBox, rect<s32>(160, posy, 295, posy + 22)); elems_.CreateAvLastNameTextBox->setEnabled(true); elems_.CreateAvLastNameTextBox->setOverrideColor(SColor(255, 0, 0, 0)); elems_.CreateAvLastNameTextBox->drop(); posy += 40; elems_.CreateAvCreateButton = new CGUIDecentralisedButton(env_, window_, e_gui_elements::CreateAvCreateButton, rect<s32>(20, posy, 180, posy + 25)); elems_.CreateAvCreateButton->setImages(elems_.TxButtonLeft, elems_.TxButtonMiddle, elems_.TxButtonRight, elems_.TxButtonPressedLeft, elems_.TxButtonPressedMiddle, elems_.TxButtonPressedRight); elems_.CreateAvCreateButton->setText(lang_[L"CreateAvatar_CreateButtonText"].c_str()); elems_.CreateAvCreateButton->drop(); if (elems_.LoginButton) elems_.LoginButton->setEnabled(true); data_chunk publicKeyChunk = keyPair_.public_key(); payment_address address; set_public_key(address, keyPair_.public_key()); std::string encoded = address.encoded(); std::wstring publicKey(encoded.begin(), encoded.end()); elems_.CreateAvPublicKeyBox->setText(publicKey.c_str()); }
nsresult Generate() { nsresult rv; // Get the key slot for generation later UniquePK11SlotInfo slot(PK11_GetInternalKeySlot()); if (!slot) { return mozilla::psm::GetXPCOMFromNSSError(PR_GetError()); } // Remove existing certs with this name (if any) rv = RemoveExisting(); if (NS_FAILED(rv)) { return rv; } // Generate a new cert NS_NAMED_LITERAL_CSTRING(commonNamePrefix, "CN="); nsAutoCString subjectNameStr(commonNamePrefix + mNickname); UniqueCERTName subjectName(CERT_AsciiToName(subjectNameStr.get())); if (!subjectName) { return mozilla::psm::GetXPCOMFromNSSError(PR_GetError()); } // Use the well-known NIST P-256 curve SECOidData* curveOidData = SECOID_FindOIDByTag(SEC_OID_SECG_EC_SECP256R1); if (!curveOidData) { return mozilla::psm::GetXPCOMFromNSSError(PR_GetError()); } // Get key params from the curve ScopedAutoSECItem keyParams(2 + curveOidData->oid.len); keyParams.data[0] = SEC_ASN1_OBJECT_ID; keyParams.data[1] = curveOidData->oid.len; memcpy(keyParams.data + 2, curveOidData->oid.data, curveOidData->oid.len); // Generate cert key pair SECKEYPublicKey* tempPublicKey; UniqueSECKEYPrivateKey privateKey( PK11_GenerateKeyPair(slot.get(), CKM_EC_KEY_PAIR_GEN, &keyParams, &tempPublicKey, true /* token */, true /* sensitive */, nullptr)); UniqueSECKEYPublicKey publicKey(tempPublicKey); tempPublicKey = nullptr; if (!privateKey || !publicKey) { return mozilla::psm::GetXPCOMFromNSSError(PR_GetError()); } // Create subject public key info and cert request UniqueCERTSubjectPublicKeyInfo spki( SECKEY_CreateSubjectPublicKeyInfo(publicKey.get())); if (!spki) { return mozilla::psm::GetXPCOMFromNSSError(PR_GetError()); } UniqueCERTCertificateRequest certRequest( CERT_CreateCertificateRequest(subjectName.get(), spki.get(), nullptr)); if (!certRequest) { return mozilla::psm::GetXPCOMFromNSSError(PR_GetError()); } // Valid from one day before to 1 year after 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(365) * oneDay); UniqueCERTValidity validity(CERT_CreateValidity(notBefore, notAfter)); if (!validity) { return mozilla::psm::GetXPCOMFromNSSError(PR_GetError()); } // Generate random serial unsigned long serial; // This serial in principle could collide, but it's unlikely rv = MapSECStatus(PK11_GenerateRandomOnSlot( slot.get(), BitwiseCast<unsigned char*, unsigned long*>(&serial), sizeof(serial))); if (NS_FAILED(rv)) { return rv; } // Create the cert from these pieces UniqueCERTCertificate cert( CERT_CreateCertificate(serial, subjectName.get(), validity.get(), certRequest.get())); if (!cert) { return mozilla::psm::GetXPCOMFromNSSError(PR_GetError()); } // Update the cert version to X509v3 if (!cert->version.data) { return NS_ERROR_INVALID_POINTER; } *(cert->version.data) = SEC_CERTIFICATE_VERSION_3; cert->version.len = 1; // Set cert signature algorithm PLArenaPool* arena = cert->arena; if (!arena) { return NS_ERROR_INVALID_POINTER; } rv = MapSECStatus( SECOID_SetAlgorithmID(arena, &cert->signature, SEC_OID_ANSIX962_ECDSA_SHA256_SIGNATURE, 0)); if (NS_FAILED(rv)) { return rv; } // Encode and self-sign the cert UniqueSECItem certDER( SEC_ASN1EncodeItem(nullptr, nullptr, cert.get(), SEC_ASN1_GET(CERT_CertificateTemplate))); if (!certDER) { return mozilla::psm::GetXPCOMFromNSSError(PR_GetError()); } rv = MapSECStatus( SEC_DerSignData(arena, &cert->derCert, certDER->data, certDER->len, privateKey.get(), SEC_OID_ANSIX962_ECDSA_SHA256_SIGNATURE)); if (NS_FAILED(rv)) { return rv; } // Create a CERTCertificate from the signed data UniqueCERTCertificate certFromDER( CERT_NewTempCertificate(CERT_GetDefaultCertDB(), &cert->derCert, nullptr, true /* perm */, true /* copyDER */)); if (!certFromDER) { return mozilla::psm::GetXPCOMFromNSSError(PR_GetError()); } // Save the cert in the DB rv = MapSECStatus(PK11_ImportCert(slot.get(), certFromDER.get(), CK_INVALID_HANDLE, mNickname.get(), false /* unused */)); if (NS_FAILED(rv)) { return rv; } // We should now have cert in the DB, read it back in nsIX509Cert form return GetFromDB(); }
void run() { testBase58(RippleAddress::VER_NODE_PUBLIC, 'n'); testBase58(RippleAddress::VER_NODE_PRIVATE, 'h'); testBase58(RippleAddress::VER_ACCOUNT_PUBLIC, 'p'); testBase58(RippleAddress::VER_ACCOUNT_PRIVATE, 'h'); testBase58(RippleAddress::VER_SEED, 's'); // check pass phrase std::string strPass("paysharesmaster"); std::string strBase58Seed("s3q5ZGX2ScQK2rJ4JATp7rND6X5npG3De8jMbB7tuvm2HAVHcCN"); std::string strBase58NodePublic("nfbbWHgJqzqfH1cfRpMdPRkJ19cxTsdHkBtz1SLJJQfyf9Ax6vd"); std::string strBase58AccountPublic("pGreoXKYybde1keKZwDCv8m5V1kT6JH37pgnTUVzdMkdygTixG8"); AccountPrivateKey accountPrivateKey; NodePrivateKey nodePrivateKey; accountPrivateKey.fromPassPhrase(strPass); nodePrivateKey.fromPassPhrase(strPass); expect(accountPrivateKey.base58Seed() == "s3q5ZGX2ScQK2rJ4JATp7rND6X5npG3De8jMbB7tuvm2HAVHcCN", accountPrivateKey.base58Seed()); expect(accountPrivateKey.base58AccountID() == "ganVp9o5emfzpwrG5QVUXqMv8AgLcdvySb", accountPrivateKey.base58AccountID()); expect(accountPrivateKey.base58PublicKey() == strBase58AccountPublic, accountPrivateKey.base58PublicKey()); expect(nodePrivateKey.base58PublicKey() == strBase58NodePublic, nodePrivateKey.base58PublicKey()); Blob sig; uint256 message; accountPrivateKey.sign(message, sig); PaysharesPublicKey publicKey(accountPrivateKey.getPublicKey(), RippleAddress::VER_NODE_PUBLIC); expect(publicKey.verifySignature(message, sig), "Signature didn't verify"); expect(publicKey.getAccountID() == accountPrivateKey.getAccountID(), "Account Id's mis match"); expect(publicKey.base58AccountID() == accountPrivateKey.base58AccountID(), "Account Id's mis match"); Blob nonCanonicalSig(sig); add_l(nonCanonicalSig.data() + 32); expect(sig != nonCanonicalSig, "Non-canonical signature equal to canonical signature"); expect(crypto_sign_verify_detached(nonCanonicalSig.data(), message.data(), message.bytes, publicKey.vchData.data()) == 0, "Non-canonical signature didn't verify (ignoring canonical-ness)"); expect(!publicKey.verifySignature(message, nonCanonicalSig), "Non-canonical signature verified"); AccountPrivateKey privateKey2; privateKey2.fromString(strBase58Seed); // key from base58seed expect(privateKey2.base58Seed() == "s3q5ZGX2ScQK2rJ4JATp7rND6X5npG3De8jMbB7tuvm2HAVHcCN", privateKey2.base58Seed()); expect(privateKey2.base58AccountID() == "ganVp9o5emfzpwrG5QVUXqMv8AgLcdvySb", privateKey2.base58AccountID()); expect(privateKey2.base58PublicKey() == strBase58AccountPublic, privateKey2.base58PublicKey()); privateKey2.sign(message, sig); expect(publicKey.verifySignature(message, sig), "Signature didn't verify"); // check with the previous pubkey // check random /// ======= OLD ==== // Construct a seed. RippleAddress naSeed; expect(naSeed.setSeedGeneric("masterpassphrase")); expect(naSeed.humanSeed() == "s3q5ZGX2ScQK2rJ4JATp7rND6X5npG3De8jMbB7tuvm2HAVHcCN", naSeed.humanSeed()); // Create node public/private key pair RippleAddress naNodePublic = RippleAddress::createNodePublic(naSeed); expect(naNodePublic.verifySignature(message, sig), "Signature didn't verify"); expect(naNodePublic.humanNodePublic() == strBase58NodePublic, naNodePublic.humanNodePublic()); naNodePublic.setNodePublic(strBase58NodePublic); expect(naNodePublic.verifySignature(message, sig), "Signature didn't verify"); expect(naNodePublic.humanNodePublic() == strBase58NodePublic, naNodePublic.humanNodePublic()); RippleAddress naAccountPublic = RippleAddress::createAccountPublic(naSeed); expect(naAccountPublic.humanAccountID() == "ganVp9o5emfzpwrG5QVUXqMv8AgLcdvySb", naAccountPublic.humanAccountID()); expect(naAccountPublic.verifySignature(message, sig), "Signature didn't verify"); expect(naAccountPublic.humanAccountPublic() == strBase58AccountPublic, naAccountPublic.humanAccountPublic()); naAccountPublic.setAccountPublic(strBase58AccountPublic); expect(naAccountPublic.humanAccountID() == "ganVp9o5emfzpwrG5QVUXqMv8AgLcdvySb", naAccountPublic.humanAccountID()); expect(naAccountPublic.verifySignature(message, sig), "Signature didn't verify"); expect(naAccountPublic.humanAccountPublic() == strBase58AccountPublic, naAccountPublic.humanAccountPublic()); Blob rippleSig; RippleAddress naAccountPrivate = RippleAddress::createAccountPrivate(naSeed); naAccountPrivate.sign(message, rippleSig); expect(rippleSig==sig, "Signature don't match"); RippleAddress naNodePrivate = RippleAddress::createNodePrivate(naSeed); naNodePrivate.sign(message, rippleSig); expect(rippleSig == sig, "Signature don't match"); std::string strPrivateKey("ssQMHypYAPSPgniSyvJQccuL1dJUbXJWVgAPV5QcAuBVEWsZTVQwffsnwTY6Mivoy3NRSVR28ZaCW74F67VSq4VRC4zY1XR"); expect(naNodePrivate.humanNodePrivate() == strPrivateKey, naNodePrivate.humanNodePrivate()); expect(naNodePrivate.setNodePrivate(strPrivateKey),"couldn't create private node"); expect(naNodePrivate.humanNodePrivate() == strPrivateKey, naNodePrivate.humanNodePrivate()); naNodePrivate.sign(message, rippleSig); expect(rippleSig == sig, "Signature don't match"); /* RippleAddress naNodePrivate = RippleAddress::createNodePrivate(naSeed); expect(naNodePrivate.humanNodePrivate() == "pnen77YEeUd4fFKG7iycBWcwKpTaeFRkW2WFostaATy1DSupwXe", naNodePrivate.humanNodePrivate()); // Check node signing. Blob vucTextSrc = strCopy("Hello, nurse!"); uint256 uHash = Serializer::getSHA512Half(vucTextSrc); Blob vucTextSig; naNodePrivate.signNodePrivate(uHash, vucTextSig); expect(naNodePublic.verifyNodePublic(uHash, vucTextSig, ECDSA::strict), "Verify failed."); */ }
void cTWUtil::ReadConfigText(const TCHAR* filename, TSTRING& configText, cArchive* pBaggage) { // TODO -- neat up this function; try to use LoadObject() above... cSerializableNString nstring; // This was coppied from ReadObject(). We need to use the baggage of the // file header to obtain the public key, thus the special casing. cDebug d("ReadConfigText"); d.TraceDebug(_T("Reading %s from file %s\n"), nstring.GetType().AsString(), filename); iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, _T("%s%s\n"), TSS_GetString(cTW, tw::STR_OPEN_CONFIG_FILE).c_str(), cDisplayEncoder::EncodeInline(filename).c_str()); cFileArchive arch; arch.OpenRead(filename); cFileHeader fileHeader; try { cSerializerImpl fhSer(arch, cSerializerImpl::S_READ); fileHeader.Read(&fhSer); } catch (eError&) { throw eSerializerInputStreamFmt(_T(""), filename, eSerializer::TY_FILE); } #if 0 // XXX: This is broken, what the h*ll are they trying to write here? -PH d.TraceDebug("Found a file header of type %d.\n", fileHeader.GetEncoding()); #endif // check for a mismatched header if (fileHeader.GetID() != cConfigFile::GetFileHeaderID()) throw eSerializerInputStreamFmt(_T(""), filename, eSerializer::TY_FILE); // check the version if (fileHeader.GetVersion() != CURRENT_FIXED_VERSION) throw eSerializerVersionMismatch(_T(""), filename, eSerializer::TY_FILE); // switch on the type of encoding... if (fileHeader.GetEncoding() == cFileHeader::ASYM_ENCRYPTION) { d.TraceDebug("Config file is compressed, public key len %d.\n", fileHeader.GetBaggage().Length()); // tell the user the db is encrypted iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, TSS_GetString(cTW, tw::STR_FILE_ENCRYPTED).c_str()); iUserNotify::GetInstance()->Notify(iUserNotify::V_VERBOSE, TSS_GetString(cTW, tw::STR_NEWLINE).c_str()); ASSERT(fileHeader.GetBaggage().Length() > 0); if (fileHeader.GetBaggage().Length() <= 0) ThrowAndAssert(eSerializerInputStreamFmt(_T(""), filename, eSerializer::TY_FILE)); fileHeader.GetBaggage().MapArchive(0, fileHeader.GetBaggage().Length()); cElGamalSigPublicKey publicKey(fileHeader.GetBaggage().GetMap()); cElGamalSigArchive cryptoArchive; cryptoArchive.SetRead(&arch, &publicKey); cSerializerImpl ser(cryptoArchive, cSerializerImpl::S_READ); ser.Init(); ser.ReadObject(&nstring); ser.Finit(); // copy the baggage into the archive, if it was passed in // Note: We rely in VerifySiteKey that we only fill out pBaggage if // the config file is encrypted. // if (pBaggage) { fileHeader.GetBaggage().Seek(0, cBidirArchive::BEGINNING); pBaggage->Copy(&fileHeader.GetBaggage(), fileHeader.GetBaggage().Length()); } } else if (fileHeader.GetEncoding() == cFileHeader::COMPRESSED) { d.TraceDebug("Config file is not compressed.\n"); //not encrypted db... cNullCryptoArchive cryptoArchive; cryptoArchive.Start(&arch); cSerializerImpl ser(cryptoArchive, cSerializerImpl::S_READ); ser.Init(); ser.ReadObject(&nstring); ser.Finit(); } else // unknown encoding... throw eSerializerInputStreamFmt(_T(""), filename, eSerializer::TY_FILE); // check 8 byte header if (nstring.mString.compare(0, 8 * sizeof(byte), CONFIG_FILE_MAGIC_8BYTE) != 0) ThrowAndAssert(eSerializerInputStreamFmt(_T(""), filename, eSerializer::TY_FILE)); // remove 8 byte header nstring.mString.assign(nstring.mString.substr(8)); cStringUtil::Convert(configText, nstring.mString); }