Exemple #1
0
void GenerateKeyPair(std::string& public_key, std::string & private_key)
{
    std::string strprivkey, strpubkey;    
    AutoSeededRandomPool rng;
    InvertibleRSAFunction privkey;
    
    privkey.Initialize(rng, 1024);
    
    Base64Encoder privkeysink(new StringSink(strprivkey), false);
    privkey.DEREncode(privkeysink);
    privkeysink.MessageEnd();
        
    RSAFunction pubkey(privkey);
    
    Base64Encoder pubkeysink(new StringSink(strpubkey), false);
    pubkey.DEREncode(pubkeysink);
    pubkeysink.MessageEnd();
    
    public_key = strpubkey;
    
    private_key = strprivkey;	
}
bool CClientCreditsList::CreateKeyPair()
{
	try{
		AutoSeededRandomPool rng;
		InvertibleRSAFunction privkey;
		privkey.Initialize(rng,RSAKEYSIZE);

		Base64Encoder privkeysink(new FileSink(CStringA(thePrefs.GetConfigDir() + _T("cryptkey.dat"))));
		privkey.DEREncode(privkeysink);
		privkeysink.MessageEnd();

		if (thePrefs.GetLogSecureIdent())
			AddDebugLogLine(false, _T("Created new RSA keypair"));
	}
	catch(...)
	{
		if (thePrefs.GetVerbose())
			AddDebugLogLine(false, _T("Failed to create new RSA keypair"));
		ASSERT ( false );
		return false;
	}
	return true;
}
void SharedKey_Init(){
  
  // InvertibleRSAFunction is used directly only because the private key
  // won't actually be used to perform any cryptographic operation;
  // otherwise, an appropriate typedef'ed type from rsa.h would have been used.
  AutoSeededRandomPool rng;
  InvertibleRSAFunction privkey;
  privkey.Initialize(rng, 1024);
  
  // With the current version of Crypto++, MessageEnd() needs to be called
  // explicitly because Base64Encoder doesn't flush its buffer on destruction.
  Base64Encoder privkeysink(new FileSink("privkey.txt"));
  privkey.DEREncode(privkeysink);
  privkeysink.MessageEnd();
  
  // Suppose we want to store the public key separately,
  // possibly because we will be sending the public key to a third party.
  RSAFunction pubkey(privkey);
  Base64Encoder pubkeysink(new FileSink("pubkey.txt"));
  pubkey.DEREncode(pubkeysink);
  pubkeysink.MessageEnd();

}
void CCollectionCreateDialog::OnBnClickedOk()
{
	//Some users have noted that the collection can at times
	//save a collection with a invalid name...
	OnEnKillFocusCollectionName();

	CString sFileName;
	m_CollectionNameEdit.GetWindowText(sFileName);
	if (!sFileName.IsEmpty())
	{
		m_pCollection->m_sCollectionAuthorName.Empty();
		m_pCollection->SetCollectionAuthorKey(NULL, 0);
		m_pCollection->m_sCollectionName = sFileName;
		m_pCollection->m_bTextFormat = (m_CollectionCreateFormatCheck.GetCheck() == BST_CHECKED);

		CString sFilePath;
		sFilePath.Format(_T("%s\\%s.emulecollection"), thePrefs.GetMuleDirectory(EMULE_INCOMINGDIR), m_pCollection->m_sCollectionName);

		using namespace CryptoPP;
		RSASSA_PKCS1v15_SHA_Signer* pSignkey = NULL;
		if (m_CollectionCreateSignNameKeyCheck.GetCheck())
		{
			bool bCreateNewKey = false;
			HANDLE hKeyFile = ::CreateFile(thePrefs.GetMuleDirectory(EMULE_CONFIGDIR) + _T("collectioncryptkey.dat"), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
			if (hKeyFile != INVALID_HANDLE_VALUE)
			{
				if (::GetFileSize(hKeyFile, NULL) == 0)
					bCreateNewKey = true;
				::CloseHandle(hKeyFile);
			}
			else
				bCreateNewKey = true;

			if (bCreateNewKey)
			{
				try
				{
					AutoSeededRandomPool rng;
					InvertibleRSAFunction privkey;
					privkey.Initialize(rng, 1024);
					Base64Encoder privkeysink(new FileSink(CStringA(thePrefs.GetMuleDirectory(EMULE_CONFIGDIR) + _T("collectioncryptkey.dat"))));
					privkey.DEREncode(privkeysink);
					privkeysink.MessageEnd();
				}
				catch(...)
				{
					ASSERT(0);
				}
			}

			try
			{
				FileSource filesource(CStringA(thePrefs.GetMuleDirectory(EMULE_CONFIGDIR) + _T("collectioncryptkey.dat")), true,new Base64Decoder);
				pSignkey = new RSASSA_PKCS1v15_SHA_Signer(filesource);
				RSASSA_PKCS1v15_SHA_Verifier pubkey(*pSignkey);
				byte abyMyPublicKey[1000];
				ArraySink asink(abyMyPublicKey, 1000);
				pubkey.DEREncode(asink);
				int nLen = asink.TotalPutLength();
				asink.MessageEnd();
				m_pCollection->SetCollectionAuthorKey(abyMyPublicKey, nLen);
			}
			catch(...)
			{
				ASSERT(0);
			}

			m_pCollection->m_sCollectionAuthorName = thePrefs.GetUserNick();
		}

		if (!PathFileExists(sFilePath))
		{
			m_pCollection->WriteToFileAddShared(pSignkey);
		}
		else
		{
			if (AfxMessageBox(GetResString(IDS_COLL_REPLACEEXISTING), MB_ICONWARNING | MB_ICONQUESTION | MB_DEFBUTTON2 | MB_YESNO) == IDNO)
				return;

			bool bDeleteSuccessful = ShellDeleteFile(sFilePath);
			if (bDeleteSuccessful)
			{
				CKnownFile* pKnownFile = theApp.knownfiles->FindKnownFileByPath(sFilePath);
				if (pKnownFile)
				{
					theApp.sharedfiles->RemoveFile(pKnownFile, true);
					if (pKnownFile->IsKindOf(RUNTIME_CLASS(CPartFile)))
						theApp.emuledlg->transferwnd->GetDownloadList()->ClearCompleted(static_cast<CPartFile*>(pKnownFile));
				}
				m_pCollection->WriteToFileAddShared(pSignkey);
			}
			else
			{
				AfxMessageBox(GetResString(IDS_COLL_ERR_DELETING),MB_ICONWARNING | MB_ICONQUESTION | MB_DEFBUTTON2 | MB_YESNO);
			}
		}
		
		delete pSignkey;
		pSignkey = NULL;

		OnOK();
	}
}
void
SecTpmFile::generateKeyPairInTpm(const Name& keyName, const KeyParams& params)
{
  string keyURI = keyName.toUri();

  if (doesKeyExistInTpm(keyName, KeyClass::PUBLIC))
    BOOST_THROW_EXCEPTION(Error("public key exists"));
  if (doesKeyExistInTpm(keyName, KeyClass::PRIVATE))
    BOOST_THROW_EXCEPTION(Error("private key exists"));

  string keyFileName = m_impl->maintainMapping(keyURI);

  try {
    switch (params.getKeyType()) {
      case KeyType::RSA: {
        using namespace CryptoPP;

        const RsaKeyParams& rsaParams = static_cast<const RsaKeyParams&>(params);
        AutoSeededRandomPool rng;
        InvertibleRSAFunction privateKey;
        privateKey.Initialize(rng, rsaParams.getKeySize());

        string privateKeyFileName = keyFileName + ".pri";
        Base64Encoder privateKeySink(new FileSink(privateKeyFileName.c_str()));
        privateKey.DEREncode(privateKeySink);
        privateKeySink.MessageEnd();

        RSAFunction publicKey(privateKey);
        string publicKeyFileName = keyFileName + ".pub";
        Base64Encoder publicKeySink(new FileSink(publicKeyFileName.c_str()));
        publicKey.DEREncode(publicKeySink);
        publicKeySink.MessageEnd();

        // set file permission
        chmod(privateKeyFileName.c_str(), 0000400);
        chmod(publicKeyFileName.c_str(), 0000444);
        return;
      }

      case KeyType::EC: {
        using namespace CryptoPP;

        const EcdsaKeyParams& ecdsaParams = static_cast<const EcdsaKeyParams&>(params);

        CryptoPP::OID curveName;
        switch (ecdsaParams.getKeySize()) {
        case 256:
          curveName = ASN1::secp256r1();
          break;
        case 384:
          curveName = ASN1::secp384r1();
          break;
        default:
          curveName = ASN1::secp256r1();
          break;
        }

        AutoSeededRandomPool rng;

        ECDSA<ECP, SHA256>::PrivateKey privateKey;
        DL_GroupParameters_EC<ECP> cryptoParams(curveName);
        cryptoParams.SetEncodeAsOID(true);
        privateKey.Initialize(rng, cryptoParams);

        ECDSA<ECP, SHA256>::PublicKey publicKey;
        privateKey.MakePublicKey(publicKey);
        publicKey.AccessGroupParameters().SetEncodeAsOID(true);

        string privateKeyFileName = keyFileName + ".pri";
        Base64Encoder privateKeySink(new FileSink(privateKeyFileName.c_str()));
        privateKey.DEREncode(privateKeySink);
        privateKeySink.MessageEnd();

        string publicKeyFileName = keyFileName + ".pub";
        Base64Encoder publicKeySink(new FileSink(publicKeyFileName.c_str()));
        publicKey.Save(publicKeySink);
        publicKeySink.MessageEnd();

        // set file permission
        chmod(privateKeyFileName.c_str(), 0000400);
        chmod(publicKeyFileName.c_str(), 0000444);
        return;
      }

      default:
        BOOST_THROW_EXCEPTION(Error("Unsupported key type"));
    }
  }
  catch (const KeyParams::Error& e) {
    BOOST_THROW_EXCEPTION(Error(e.what()));
  }
  catch (const CryptoPP::Exception& e) {
    BOOST_THROW_EXCEPTION(Error(e.what()));
  }
}