DebugReportSection DebugReporter::getDotGraphSection(
        const std::string& id, std::string title, const std::string& dotSpec) {
    std::stringstream cmd;
    cmd << "dot -Tsvg <<END_DOT_FILE\n";
    cmd << dotSpec << "\n";
    cmd << "END_DOT_FILE\n";
    FILE* in = popen(cmd.str().c_str(), "r");
    std::stringstream data;
    while (true) {
        char c = fgetc(in);
        if (feof(in)) {
            break;
        }
        data << c;
    }
    pclose(in);
    std::stringstream graphHTML;
    if (data.str().find("<svg") != std::string::npos) {
        graphHTML << "<img alt='graph image' src='data:image/svg+xml;base64," << toBase64(data.str())
                  << "'><br/>\n";
    } else {
        graphHTML << "<p>(error: unable to generate dot graph image)</p>";
    }
    graphHTML << "<a href=\"javascript:toggleVisibility('" << id << "-source"
              << "')\">(show dot source)</a>\n";
    graphHTML << "<div id='" << id << "-source"
              << "' style='display:none'>\n";
    graphHTML << "<pre>" << dotSpec << "</pre>\n";
    graphHTML << "</div>\n";
    return DebugReportSection(id, std::move(title), {}, graphHTML.str());
}
int main(int argc, char *argv[])
{
    if (argc != 3) {
        return -1;
    }

    try {
        std::vector<uint8_t> imageData;
        std::stringstream stream(argv[1]);
        std::string path(argv[2]);

        int size;

        stream >> size;

        ffmpegthumbnailer::VideoThumbnailer vt(size, false, true, 20, false);
        vt.generateThumbnail(path, ThumbnailerImageTypeEnum::Png, imageData);

        char *base64_data = toBase64(imageData.data(), imageData.size(), Base64Encoding);

        printf("%s", base64_data);
        fflush(stdout);
    } catch (std::logic_error e) {
        std::cerr << e.what();
        return -1;
    }

    return 0;
}
Exemple #3
0
bool Wallet::walletIsAuthenticatedWithPassphrase() {
    // try to read existing keys if they exist...

    // FIXME: initialize OpenSSL elsewhere soon
    initialize();

    // this should always be false if we don't have a passphrase
    // cached yet
    if (!_passphrase || _passphrase->isEmpty()) {
        return false;
    }
    if (_publicKeys.count() > 0) {
        // we _must_ be authenticated if the publicKeys are there
        DependencyManager::get<WalletScriptingInterface>()->setWalletStatus((uint)WalletStatus::WALLET_STATUS_READY);
        return true;
    }

    // otherwise, we have a passphrase but no keys, so we have to check
    auto publicKey = readPublicKey(keyFilePath().toStdString().c_str());

    if (publicKey.size() > 0) {
        if (auto key = readPrivateKey(keyFilePath().toStdString().c_str())) {
            EC_KEY_free(key);

            // be sure to add the public key so we don't do this over and over
            _publicKeys.push_back(publicKey.toBase64());
            DependencyManager::get<WalletScriptingInterface>()->setWalletStatus((uint)WalletStatus::WALLET_STATUS_READY);
            return true;
        }
    }

    return false;
}
Exemple #4
0
string
FilePrivateKeyStorage::nameTransform
  (const string& keyName, const string& extension)
{
  uint8_t hash[SHA256_DIGEST_LENGTH];
  ndn_digestSha256((uint8_t*)&keyName[0], keyName.size(), hash);

  string digest = toBase64(hash, sizeof(hash));
  trim(digest);
  std::replace(digest.begin(), digest.end(), '/', '%');

  return keyStorePath_ + "/" + digest + extension;
}
Exemple #5
0
bool Wallet::walletIsAuthenticatedWithPassphrase() {
    // try to read existing keys if they exist...

    // FIXME: initialize OpenSSL elsewhere soon
    initialize();
    qCDebug(commerce) << "walletIsAuthenticatedWithPassphrase: checking" << (!_passphrase || !_passphrase->isEmpty());

    // this should always be false if we don't have a passphrase
    // cached yet
    if (!_passphrase || _passphrase->isEmpty()) {
        if (!getKeyFilePath().isEmpty()) { // If file exists, then it is an old school file that has not been lockered. Must get user's passphrase.
            qCDebug(commerce) << "walletIsAuthenticatedWithPassphrase: No passphrase, but there is an existing wallet.";
            return false;
        } else {
            qCDebug(commerce) << "walletIsAuthenticatedWithPassphrase: New setup.";
            setPassphrase("ACCOUNT"); // Going forward, consider this an account-based client.
        }
    }
    if (_publicKeys.count() > 0) {
        // we _must_ be authenticated if the publicKeys are there
        DependencyManager::get<WalletScriptingInterface>()->setWalletStatus((uint)WalletStatus::WALLET_STATUS_READY);
        qCDebug(commerce) << "walletIsAuthenticatedWithPassphrase: wallet was ready";
        return true;
    }

    // otherwise, we have a passphrase but no keys, so we have to check
    auto publicKey = readPublicKey(keyFilePath());

    if (publicKey.size() > 0) {
        if (auto key = readPrivateKey(keyFilePath())) {
            EC_KEY_free(key);

            // be sure to add the public key so we don't do this over and over
            _publicKeys.push_back(publicKey.toBase64());

            if (*_passphrase != "ACCOUNT") {
                changePassphrase("ACCOUNT"); // Rewrites with salt and constant, and will be lockered that way.
            }
            qCDebug(commerce) << "walletIsAuthenticatedWithPassphrase: wallet now ready";
            return true;
        }
    }
    qCDebug(commerce) << "walletIsAuthenticatedWithPassphrase: wallet not ready";
    return false;
}
int main(int argc, char** args){
  int challenge_status = FAIL;

  printf("=== Challenge-1: hex decoding & base64 encoding ===\n");
  ERROR status = OK;

  char* hex = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";
  char* expected = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t";

  bytes raw = calloc(256, 1);
  int raw_limit = 256;
  int raw_length = 0;

  if( OK != (status = fromHex((const bytes) hex, strlen(hex), raw, raw_limit, &raw_length))){
    log_error(status); exit(1);
  };

  bytes base64 = calloc(256,1);
  int base64_limit = 256;
  int base64_length = 0;

  // print_hex(raw);printf(" (hex:%lu, raw:%lu)\n", strlen(hex), strlen(raw));

  if( OK != (status = toBase64(raw, raw_length, base64, base64_limit, &base64_length))){
    log_error(status); exit(1);
  };

  printf("Expected: %s (%lu)\n", expected, strlen(expected));
  printf("Actual:   %s (%i)\n", base64, base64_length);

  if(strcmp(expected, base64) == 0){
    challenge_status = SUCCESS;
  }
  free(raw);
  free(base64);

  return challenge_status;
}
Exemple #7
0
char* Crypto::cryptAndSignMessage(const char* message, rsa* crypter, rsa* signer) {
    size_t messageLen = strlen(message);
    size_t cipherTextLen = messageLen + 257;
    u_char* cipherText = (u_char*)malloc(cipherTextLen);
    if(cipherText == NULL) {
        if(CRYPTO_DEBUG) printf("cannot allocate memory for aes cipher text\n");
        return NULL;
    }
    // Generate session key
    aes aes;
    aes.generateKey();
    aes.dumpKey();
    aes.dumpNonce();
    
    //Encrypt message with session key
    size_t messageSize = aes.encrypt((u_char*)message, strlen(message), cipherText, cipherTextLen);
    char* messageBase64 = toBase64(cipherText, messageSize);
    free(cipherText);
    if(messageBase64 == NULL) {
        return NULL;
    }
    
    
    //Encrypt session key
    u_char buffer[512];
    size_t size = crypter->encrypt(aes.getKey(), aes.getKeyLen(), buffer, 512);
    char* cipherKeyBase64 = toBase64(buffer, size);
    if(cipherKeyBase64 == NULL) {
        return NULL;
    }
    
    //Encrypt nonce
    size = crypter->encrypt(aes.getIV(), aes.getNonceLen(), buffer, 512);
    char* cipherNonceBase64 = toBase64(buffer, size);
    if(cipherNonceBase64 == NULL) {
        return NULL;
    }

    //Sign message
    char* signatureBase64 = signer->sign(messageBase64);
    if(signatureBase64 == NULL) {
        return NULL;
    }
    
    //Generate the whole thing
    char* whole = (char*)malloc(strlen(messageBase64) + strlen(cipherKeyBase64) + strlen(cipherNonceBase64) + strlen(signatureBase64) + 4);
    if(whole) {
        sprintf(whole, "%s\n%s\n%s\n%s\n", cipherNonceBase64, cipherKeyBase64, messageBase64, signatureBase64);
        free(cipherKeyBase64);
        free(cipherNonceBase64);
        free(messageBase64);
        free(signatureBase64);
        return whole;
    } else {
        free(cipherKeyBase64);
        free(cipherNonceBase64);
        free(messageBase64);
        free(signatureBase64);
        if(CRYPTO_DEBUG) printf("Cannot allocate memory for concatenation/n");
        return NULL;
    }
}
Exemple #8
0
/** 
 * \brief Saves the ChanServ database to disk
 */
void saveChanData(RegChanList * first)
{
	RegChanList *cl = first;
	cAccessList *accitem;
	cAkickList *akitem;
	const char *tmpFounderNick;
	int x = 0;

	saveChanUrls(first);
	db.cs = NULL;
	db.cs = fopen(CS_DIR "chanserv.db", "w");
	if (db.cs == NULL) {
		sSend(":%s GOPER :ERROR: Unable to save Channel database fopen failed: %s", myname, strerror(errno));
		logDump(corelog, "Unable to save Channel database: fopen: %s", strerror(errno));
		return;
	}

	fprintf(db.cs, "version 2\n");

	while (cl) {
		tmpFounderNick = cl->founderId.getNick();

		if (tmpFounderNick == NULL)
			tmpFounderNick = "-";

		/* New chan insertion point */
		fprintf(db.cs, "channel ");
		fprintf(db.cs, "%s %s ", cl->name, tmpFounderNick);
		fprintf(db.cs, "%lu %lu ", cl->mlock, cl->flags);

		if (!(cl->flags & CENCRYPT)) {
			strcpy(cryptstr, (char *)cl->password);
			xorit(cryptstr);
			fprintf(db.cs, "@%s ", cryptstr);
		}
		else {
			u_char *tmpup = toBase64(cl->password, 16);
			if (!tmpup)
				abort();
			fprintf(db.cs, "$%s ", tmpup);
			FREE(tmpup);
		}

		fprintf(db.cs, "%lu ", (unsigned long)cl->timereg);
		fprintf(db.cs, "%lu ", (unsigned long)cl->timestamp);
		fprintf(db.cs, "%s %lu %i ", cl->key, cl->limit, cl->memolevel);
		fprintf(db.cs, "%i %i :%s\n", cl->tlocklevel, cl->restrictlevel,
				cl->desc);
		if (cl->topic)
			fprintf(db.cs, "topic %s %s %lu :%s\n", cl->name, cl->tsetby,
					cl->ttimestamp, cl->topic);
		if (cl->url)
			fprintf(db.cs, "url %s :%s\n", cl->name, cl->url);
		if (cl->autogreet != NULL)
			fprintf(db.cs, "autogreet %s :%s\n", cl->name, cl->autogreet);
		if ((cl->flags & CMARK) && cl->markby)
			fprintf(db.cs, "markby %s %s\n", cl->name, cl->markby);
		if (cl->chpw_key)
			fprintf(db.cs, "chkey %X\n", cl->chpw_key);
		if (cl->firstOp) {
			const char *tmpName;

			for (accitem = cl->firstOp; accitem; accitem = accitem->next) {
				tmpName = (accitem->nickId).getNick();

				if (tmpName == NULL)
				    continue;
				fprintf(db.cs, "op %s %s ", cl->name, tmpName);
				fprintf(db.cs, "%i\n", accitem->uflags);
			}
		}

		if (cl->firstAkick) {
			for (akitem = cl->firstAkick; akitem; akitem = akitem->next) {
				fprintf(db.cs, "akick %s %s ", cl->name, akitem->mask);
				fprintf(db.cs, "%lu :%s\n", (u_long) akitem->added,
						akitem->reason);
			}
		}
		x++;
		fflush(db.cs);
#ifdef DBDEBUG
		sSend(":%s PRIVMSG " DEBUGCHAN " :Saved chan data (%s)", ChanServ,
			  cl->name);
#endif
		cl = cl->next;
	}
	fprintf(db.cs, "done\n");
	fflush(db.cs);
	fclose(db.cs);
#ifdef GLOBOPS_TIMED_MSGS
	sSend(":%s GLOBOPS :Completed save(%i)", ChanServ, x);
#else
	sSend(":%s PRIVMSG " LOGCHAN " :Completed save(%i)", ChanServ, x);
#endif
}
Exemple #9
0
/** 
 * \brief Saves the NickServ database to disk
 */
void saveNickData(void)
{
	RegNickList *nl;
	nAccessList *accitem;
	int x = 0, bucket;

	db.ns = fopen(NS_DB, "w");

	if (db.ns == NULL) {
		sSend(":%s GOPER :ERROR: Unable to save NickServ database fopen failed: %s", myname, strerror(errno));
		logDump(corelog, "Unable to save NickServ database: fopen: %s", strerror(errno));
		return;
	}

	fprintf(db.ns, "version 3\n");

	for (bucket = 0; bucket < NICKHASHSIZE; bucket++) {
		nl = LIST_FIRST(&RegNickHash[bucket]);
		while (nl != NULL) {
			/* New nick insertion point */
			fprintf(db.ns, "nick ");
			if (nl->user[0] == '\0')
				fprintf(db.ns, "%s . %s ", nl->nick, nl->host);
			else
				fprintf(db.ns, "%s %s %s ", nl->nick, nl->user, nl->host);

			if (!(nl->flags & NENCRYPT))
			{
				strcpy(cryptstr, (char *)nl->password);
				xorit(cryptstr);
				fprintf(db.ns, "@%s ", cryptstr);
			}
			else {
				unsigned char *p;

				// XXX Put note that PASSLEN must be at least 15
				p = toBase64(nl->password, 16);
				fprintf(db.ns, "$%s ", p);
				FREE(p);
			}

			fprintf(db.ns, "%lu ", (unsigned long)nl->timestamp);
			fprintf(db.ns, "%lu ", (unsigned long)nl->timereg);
			fprintf(db.ns, "%i %X*%X\n", nl->flags, nl->regnum.a, nl->regnum.b);

			/* Infoserv data */
			fprintf(db.ns, "is %ld\n", nl->is_readtime);

#ifdef REQ_EMAIL
			if (!(nl->flags & NACTIVE) || (nl->flags & NDEACC))
				fprintf(db.ns, "akey %lu\n", nl->email_key);
#endif
			if (nl->chpw_key)
				fprintf(db.ns, "chkey %X\n", nl->chpw_key);
			if (nl->url != NULL)
				fprintf(db.ns, "url %s %s\n", nl->nick, nl->url);
#ifdef TRACK_GECOS
			if (nl->gecos != NULL)
				fprintf(db.ns, "gecos :%s\n", nl->gecos);
#endif

			if (nl->email[0] && strcmp(nl->email, "(none)"))
				fprintf(db.ns, "email %s %s\n", nl->nick, nl->email);

			if ((nl->opflags & ~(OROOT | OSERVOP)))
				fprintf(db.ns, "oper %s %lu 0 0\n", nl->nick, nl->opflags);

			if ((nl->flags & NMARK) && nl->markby)
				fprintf(db.ns, "markby %s %s\n", nl->nick, nl->markby);

			if (nl->idtime != DEF_NDELAY)
				fprintf(db.ns, "idtime %s %i\n", nl->nick, nl->idtime);

			for (accitem = LIST_FIRST(&nl->acl); accitem;
				 accitem = LIST_NEXT(accitem, al_lst))
				fprintf(db.ns, "access %s %s\n", nl->nick, accitem->mask);
			x++;
			fflush(db.ns);
#ifdef DBDEBUG
			sSend(":%s PRIVMSG " DEBUGCHAN " :Saved nick data (%s)",
				  NickServ, nl->nick);
#endif
			nl = LIST_NEXT(nl, rn_lst);
		}
	}
	fprintf(db.ns, "done\n");
	fflush(db.ns);
	fclose(db.ns);
#ifdef GLOBOPS_TIMED_MSGS
	sSend(":%s GLOBOPS :Completed save(%i)", NickServ, x);
#else
	sSend(":%s PRIVMSG " LOGCHAN " :Completed save(%i)", NickServ, x);
#endif
}
int main(int argc,char** argv)
{
	if(argc < 3)
	{
		fprintf(stderr,"error: no input programs\nusage:\nothello PROG1 PROG2\n");
		fflush(stderr);
		exit(EXIT_FAILURE);
	}
	else
	{
		Board board(DefaultBoard);
		state_t state = BLACK;
		bool flag = false;
		state_t fault = NONE;
		const char * const PIPENAME = "othello.pipe";
		int e = mkfifo(PIPENAME,0666);
		std::string fault_detail = "";
		std::string record;
		char buf[1024];
		char* ret = getcwd(buf,1024);
		if(ret == nullptr)
		{
			std::cout<<"too long path name"<<std::endl;
			exit(EXIT_FAILURE);
		}
		while(1)
		{
			auto v = getPuttable(board,state);
			if(v.empty())
			{
				if(flag)
					break;
				else
				{
					flag = true;
					state = invertState(state);
					continue;
				}
			}
			char* str = (char*)malloc(strlen(argv[state])+11);
			sprintf(str,"%s > %s",argv[state],PIPENAME);
			FILE * pp = popen(str,"w");
			timeval s,e,d;
			gettimeofday(&s,NULL);
			std::string bstr = toStr(board);
			fprintf(pp,"%c\n%s",(state==BLACK)?'x':'o',bstr.c_str());
			printf("%c\n%s\n",(state==BLACK)?'x':'o',bstr.c_str());
			FILE * fp = fopen(PIPENAME,"r");
			pclose(pp);
			gettimeofday(&e,NULL);
			timersub(&e,&s,&d);
			if(timercmp(&d,&timelimit,>))
			{
				fault = state;
				fault_detail = "Time Limit Exceeded";
				break;
			}
			printf("%ldus\n",d.tv_usec);
			int x,y;
			fscanf(fp,"%d%d",&x,&y);
			fclose(fp);
			if(std::find(v.begin(),v.end(),xyToPos(x,y)) == v.end())
			{
				fault = state;
				fault_detail = "Wrong Output";
				break;
			}
			board = put(board,xyToPos(x,y),state);
			record.append(1,toBase64(x*8+y));
			state = invertState(state);
			flag = false;
		}
		printf("--<Game  Set>--\n%s\n",toStr(board).c_str());
		std::pair<int,int> p;
		switch(fault)
		{
			case NONE:
				p = countBoard(board);
				if(p.first > p.second)
					puts("Winner: Black");
				else if(p.first < p.second)
					puts("Winner: White");
				else
					puts("Draw");
				printf("Black: %2d White: %2d\n",p.first,p.second);
				printf("game record:%s\n",record.c_str());
				break;
			case BLACK:
				puts("Winner: White");
				puts("Black: Foul");
				puts(fault_detail.c_str());
				break;
			case WHITE:
				puts("Winner: Black");
				puts("White: Foul");
				puts(fault_detail.c_str());
				break;
			default:;
		}
		remove(PIPENAME);
	}
	return 0;
}
Exemple #11
0
/**
 * Return the base64 representation of the bytes in array.
 * @param array The array of bytes.
 * @param addNewlines (optional) If true, add newlines to the output (good for
 * writing to a file).  If omitted, do not add newlines.
 * @return The base64 string.
 */
static inline std::string
toBase64(const std::vector<uint8_t>& array, bool addNewlines = false)
{
  return toBase64(&array[0], array.size(), addNewlines);
}
std::string GraphDog::getDeviceID() {
    string _id;
    
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
//    char* macAddress=(char*)malloc(18);
//	std::string ifName="en0";
//	int  success;
//	struct ifaddrs * addrs;
//	struct ifaddrs * cursor;
//	const struct sockaddr_dl * dlAddr;
//	const unsigned char* base;
//	int i;
//    
//	success = getifaddrs(&addrs) == 0;
//	if (success) {
//		cursor = addrs;
//		while (cursor != 0) {
//			if ( (cursor->ifa_addr->sa_family == AF_LINK)
//				&& (((const struct sockaddr_dl *) cursor->ifa_addr)->sdl_type == 0x06) && strcmp(ifName.c_str(),  cursor->ifa_name)==0 ) {
//				dlAddr = (const struct sockaddr_dl *) cursor->ifa_addr;
//				base = (const unsigned char*) &dlAddr->sdl_data[dlAddr->sdl_nlen];
//				strcpy(macAddress, "");
//				for (i = 0; i < dlAddr->sdl_alen; i++) {
//					if (i != 0) {
//						strcat(macAddress, ":");
//					}
//					char partialAddr[3];
//					sprintf(partialAddr, "%02X", base[i]);
//					strcat(macAddress, partialAddr);
//					
//				}
//			}
//			cursor = cursor->ifa_next;
//		}
//		
//		freeifaddrs(addrs);
//	}
//    _id = macAddress;
    _id = [[OpenUDID value] UTF8String];

#elif CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
	//_id = JNIKelper::getInstance()->callJava_getUDID();
	JniMethodInfo minfo;
	jobject jobj;
	
	if(JniHelper::getStaticMethodInfo(minfo, (packageName + ".KSAWrap").c_str(), "getActivity", "()Ljava/lang/Object;"))
	{
		jobj = minfo.env->NewGlobalRef(minfo.env->CallStaticObjectMethod(minfo.classID, minfo.methodID));
		JniMethodInfo __minfo;
		__minfo.classID = 0;
		__minfo.env = 0;
		__minfo.methodID = 0;
		CCLog("qqq");
		if(JniHelper::getMethodInfo(__minfo, (packageName + ".KSActivityBase").c_str(), "getUDID", "()Ljava/lang/String;"))
		{
			jstring jstrTitle = (jstring) __minfo.env->CallObjectMethod(jobj, __minfo.methodID);
			
			if(jstrTitle)
			{
				char* pszTitle = (char*)__minfo.env->GetStringUTFChars(jstrTitle, JNI_FALSE);
				
				_id = pszTitle;
				__minfo.env->ReleaseStringUTFChars(jstrTitle, pszTitle);
				__minfo.env->DeleteLocalRef(jstrTitle);
				
			}
			__minfo.env->DeleteLocalRef(__minfo.classID);
		}
		
		minfo.env->DeleteGlobalRef(jobj);
		minfo.env->DeleteLocalRef(minfo.classID);
	}
	
#endif
    //string _id = base64_decode(macAddress);
	return toBase64(_id);
}
Exemple #13
0
{
    QtConcurrent::run([this, receipt, strTransationID]() {
        QString strPlat;
    #ifdef Q_OS_MAC
        strPlat = "macosx";
    #else
        strPlat = "linux";
    #endif
        QString asServerUrl = WizService::CommonApiEntry::asServerUrl();
        QString checkUrl = asServerUrl + "/a/pay2/ios";
    //    QString checkUrl = "https://sandbox.itunes.apple.com/verifyReceipt";
    //    QString checkUrl = "https://buy.itunes.apple.com/verifyReceipt";
        CWizDatabase& db = CWizDatabaseManager::instance()->db();
        QString userID = db.GetUserId();
        QString userGUID = db.GetUserGUID();
        QString receiptBase64 = receipt.toBase64();
        receiptBase64 = QString(QUrl::toPercentEncoding(receiptBase64));
        QString strExtInfo = QString("client_type=%1&user_id=%2&user_guid=%3&transaction_id=%4&receipt=%5")
                .arg(strPlat).arg(userID).arg(userGUID).arg(strTransationID).arg(receiptBase64);

        qDebug() << "transation id = " << strTransationID;
    //    qDebug() << "check receipt : " << checkUrl << strExtInfo;

        QNetworkAccessManager net;
        QNetworkRequest request;
        request.setUrl(checkUrl);
        request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/x-www-form-urlencoded"));
        QNetworkReply* reply = net.post(request, strExtInfo.toUtf8());

        QEventLoop loop;
        QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
Exemple #14
0
void
FilePrivateKeyStorage::generateKeyPair
  (const Name& keyName, const KeyParams& params)
{
  if (doesKeyExist(keyName, KEY_CLASS_PUBLIC))
    throw SecurityException("Public Key already exists");
  if (doesKeyExist(keyName, KEY_CLASS_PRIVATE))
    throw SecurityException("Private Key already exists");

  Blob publicKeyDer;
  Blob privateKeyDer;

  if (params.getKeyType() == KEY_TYPE_RSA) {
    const RsaKeyParams& rsaParams = static_cast<const RsaKeyParams&>(params);

    BIGNUM* exponent = 0;
    RSA* rsa = 0;

    exponent = BN_new();
    if (BN_set_word(exponent, RSA_F4) == 1) {
      rsa = RSA_new();
      if (RSA_generate_key_ex(rsa, rsaParams.getKeySize(), exponent, NULL) == 1) {
        // Encode the public key.
        int length = i2d_RSA_PUBKEY(rsa, NULL);
        publicKeyDer = Blob(ptr_lib::make_shared<vector<uint8_t> >(length), false);
        uint8_t* derPointer = const_cast<uint8_t*>(publicKeyDer.buf());
        i2d_RSA_PUBKEY(rsa, &derPointer);

        // Encode the private key.
        length = i2d_RSAPrivateKey(rsa, NULL);
        vector<uint8_t> pkcs1PrivateKeyDer(length);
        derPointer = &pkcs1PrivateKeyDer[0];
        i2d_RSAPrivateKey(rsa, &derPointer);
        privateKeyDer = encodePkcs8PrivateKey
          (pkcs1PrivateKeyDer, OID(RSA_ENCRYPTION_OID),
           ptr_lib::make_shared<DerNode::DerNull>());
      }
    }

    BN_free(exponent);
    RSA_free(rsa);
  }
  else if (params.getKeyType() == KEY_TYPE_ECDSA) {
    const EcdsaKeyParams& ecdsaParams = static_cast<const EcdsaKeyParams&>(params);

    OID parametersOid;
    int curveId = -1;

    // Find the entry in EC_KEY_INFO.
    for (size_t i = 0 ; i < sizeof(EC_KEY_INFO) / sizeof(EC_KEY_INFO[0]); ++i) {
      if (EC_KEY_INFO[i].keySize == ecdsaParams.getKeySize()) {
        curveId = EC_KEY_INFO[i].curveId;
        parametersOid.setIntegerList
          (EC_KEY_INFO[i].oidIntegerList, EC_KEY_INFO[i].oidIntegerListLength);

        break;
      }
    }
    if (curveId == -1)
      throw SecurityException("Unsupported keySize for KEY_TYPE_ECDSA");

    EC_KEY* ecKey = EC_KEY_new_by_curve_name(curveId);
    if (ecKey != NULL) {
      if (EC_KEY_generate_key(ecKey) == 1) {
        // Encode the public key.
        int length = i2d_EC_PUBKEY(ecKey, NULL);
        vector<uint8_t> opensslPublicKeyDer(length);
        uint8_t* derPointer = &opensslPublicKeyDer[0];
        i2d_EC_PUBKEY(ecKey, &derPointer);
        // Convert the openssl style to ndn-cxx which has the simple AlgorithmIdentifier.
        // Find the bit string which is the second child.
        ptr_lib::shared_ptr<DerNode> parsedNode = DerNode::parse
          (&opensslPublicKeyDer[0], 0);
        const std::vector<ptr_lib::shared_ptr<DerNode> >& children =
          parsedNode->getChildren();
        publicKeyDer = encodeSubjectPublicKeyInfo
          (OID(EC_ENCRYPTION_OID),
           ptr_lib::make_shared<DerNode::DerOid>(parametersOid), children[1]);

        // Encode the private key.
        EC_KEY_set_enc_flags(ecKey, EC_PKEY_NO_PARAMETERS | EC_PKEY_NO_PUBKEY);
        length = i2d_ECPrivateKey(ecKey, NULL);
        vector<uint8_t> pkcs1PrivateKeyDer(length);
        derPointer = &pkcs1PrivateKeyDer[0];
        i2d_ECPrivateKey(ecKey, &derPointer);
        privateKeyDer = encodePkcs8PrivateKey
          (pkcs1PrivateKeyDer, OID(EC_ENCRYPTION_OID),
           ptr_lib::make_shared<DerNode::DerOid>(parametersOid));
      }
    }

    EC_KEY_free(ecKey);
  }
  else
    throw SecurityException("Unsupported key type");

  string keyUri = keyName.toUri();
  string publicKeyFilePath = nameTransform(keyUri, ".pub");
  string privateKeyFilePath = nameTransform(keyUri, ".pri");

  ofstream publicKeyFile(publicKeyFilePath.c_str());
  publicKeyFile << toBase64(publicKeyDer.buf(), publicKeyDer.size(), true);
  ofstream privateKeyFile(privateKeyFilePath.c_str());
  privateKeyFile << toBase64(privateKeyDer.buf(), privateKeyDer.size(), true);

  ::chmod(publicKeyFilePath.c_str(),  S_IRUSR | S_IRGRP | S_IROTH);
  ::chmod(privateKeyFilePath.c_str(), S_IRUSR);
}
Exemple #15
0
 Writer& Writer::writeBase64(const std::string& name,
                             const void* data, size_t size)
 {
     setValueName(name);
     return writeValue(toBase64(data, size));
 }
Exemple #16
0
 Writer& Writer::writeBase64(const void* data, size_t size)
 {
     return writeValue(toBase64(data, size));
 }
Exemple #17
0
void CRASHREPORTER_send_message(const char *additional_information, const char **messages, int num_messages, Crash_Type crash_type){
  QString plugin_names = get_plugin_names();
  
  QString tosend = QString(additional_information) + "\n\n";

  tosend += VERSION "\n\n";

  tosend += "OpenGL vendor: " + QString((GE_vendor_string==NULL ? "(null)" : (const char*)GE_vendor_string )) + "\n";
  tosend += "OpenGL renderer: " + QString((GE_renderer_string==NULL ? "(null)" : (const char*)GE_renderer_string)) + "\n";
  tosend += "OpenGL version: " + QString((GE_version_string==NULL ? "(null)" : (const char*)GE_version_string)) + "\n";
  tosend += QString("OpenGL flags: %1").arg(GE_opengl_version_flags, 0, 16) + "\n\n";

  tosend += "Running plugins: " + plugin_names + "\n\n";

  tosend += "Running time: " + QString::number(running_time.elapsed()) + "\n\n";

  tosend += "\n\n";

    
  for(int i=0;i<num_messages;i++)
    tosend += QString::number(i) + ": "+messages[i] + "\n";

  tosend += "\n\n";

  int event_pos = g_event_pos;

  tosend += "start event_pos: " + QString::number(event_pos) + "\n";

  for(int i=event_pos-1; i>=0 ; i--)
    tosend += QString(g_event_log[i]) + "\n";

  for(int i=NUM_EVENTS-1; i>=event_pos ; i--)
    tosend += QString(g_event_log[i]) + "\n";

  tosend += "end event_pos: " + QString::number(g_event_pos) + "\n";
  
  tosend += "\n\n";

#if defined(FOR_LINUX)
  tosend += "LINUX\n\n";
  tosend += "/etc/os-release: "+file_to_string("/etc/os-release");
  tosend += "\n\n";
  tosend += "/proc/version: "+file_to_string("/proc/version");
  tosend += "\n\n";
  tosend += "/proc/cpuinfo: "+file_to_string("/proc/cpuinfo");
#endif

  // start process
  {
    QString program = QCoreApplication::applicationDirPath() + QDir::separator() + "crashreporter";
#if FOR_WINDOWS
    program += ".exe";
#endif

    QTemporaryFile *file;
    
    if (crash_type==CT_CRASH) {
      file = new QTemporaryFile;
    } else {
      if (g_crashreporter_file==NULL) {
        g_crashreporter_file = new QTemporaryFile;
        g_crashreporter_file->setAutoRemove(false); // We delete it in the sub process. This process is just going to exit as soon as possible.
      }
      file = g_crashreporter_file;
    }

    bool save_mixer_tree;
    
    if (crash_type==CT_CRASH)
      save_mixer_tree = false; // Don't want to risk crashing inside the crash handler.
    else
      save_mixer_tree = true;
    
    string_to_file(tosend, file, save_mixer_tree);

    /*
      Whether to block
      ================
                                    RELEASE      !RELEASE
                                -------------------------
      Crash in main thread      |     no [1]       yes [2]
      Crash in other thread     |     no [1]       yes [2]
      Assert in main thread     |     no [4]       yes [2]
      Assert in other thread    |     no [4]       yes [2,3]

      [1] When crashing in RELEASE mode, it doesn't matter wheter we block or not, because
          radium will exit immediately after finishing this function anyway, and it's
          probably better to do that as quickly as possible.

      [2] Ideally, this should happen though:
          1. All threads immediately freezes
          2. A dialog pops up asking whether to:
             a) Stop program (causing gdb to kick in)
             b) Ignore
             c) Run assert crashreporter

      [3] This can be annoying if the assert happens in the audio thread though.

      [4] Asserts are not really supposed to happen, but there are a lot of them, 
          and they might pop up unnecessarily (for instance a bug in the asserts themselves):
          * Blocking might cause the program to be non-functional unnecessarily.
          * Blocking could prevent the user from saving the current song,
            for instance if the assert window just pops up immediately after closing it.
     */

#ifdef RELEASE
    bool do_block = false;
#else
    bool do_block = true;
#endif

    QTemporaryFile emergency_save_file("radium_crash_save");

#if 0
    bool dosave = is_crash && Undo_num_undos_since_last_save()>0;
#else
    bool dosave = false; // saving inside a forked version of the program didn't really work that well. Maybe it works better in windows.
#endif
    
    if (dosave)
      emergency_save_file.open();
    
    run_program(program,
                toBase64(file->fileName()),
                toBase64(plugin_names),
                toBase64(dosave ? emergency_save_file.fileName() : NOEMERGENCYSAVE),
                crash_type==CT_CRASH ? "is_crash" : crash_type==CT_ERROR ? "is_error" : "is_warning",
                do_block
                );

    if (dosave)
      Save_Clean(STRING_create(emergency_save_file.fileName()),root,false);
  }
  
}
Exemple #18
0
 string toBase64(const Buffer &input)
 {
     return toBase64(input.getData(), input.getDataSize());
 }
//쓰레드펑션
void* GraphDog::t_function(void *_insertIndex)
{	
	int insertIndex = (int)_insertIndex;
//	std::map<int, CommandType>& commands = graphdog->commands;
//	pthread_mutex_lock(&graphdog->cmdsMutex);
	CommandsType& command = graphdog->commandQueue[insertIndex];
	pthread_mutex_lock(&command.caller->t_functionMutex);
	string token=GraphDog::get()->getToken();
	string paramStr = toBase64(desEncryption(graphdog->sKey, command.commandStr));
	string dataset = "&token=" + token + "&command=" + paramStr + "&appver=" + GraphDog::get()->getAppVersionString();
	
    string commandurl = "http://www.graphdog.net/command/";
    commandurl=commandurl.append(GraphDog::get()->getGraphDogVersion());
    commandurl=commandurl.append("/");
    commandurl=commandurl.append(GraphDog::get()->aID);
    
	// << "&param=" << paramStr
	//curl으로 명령을 날리고 겨로가를 얻는다.
	CURL *handle = GraphDog::get()->getCURL();
    curl_easy_setopt(handle, CURLOPT_URL, commandurl.c_str());
	curl_easy_setopt(handle, CURLOPT_POSTFIELDS,dataset.c_str());
	curl_easy_setopt(handle, CURLOPT_WRITEDATA, (void *)&command.chunk);
	
	//		curl_setopt($ch,CURLOPT_TIMEOUT,1000);
//	pthread_mutex_unlock(&graphdog->cmdsMutex);
	CURLcode resultCode = curl_easy_perform(handle);
	
	//##
	JsonBox::Object resultobj;
	string resultStr;
	if(resultCode == CURLE_OK)
	{
		resultStr = command.chunk.memory;// gdchunk.memory;
		if(*resultStr.rbegin() == '#') // success
		{
			try
			{
				vector<char> encText = base64To(std::string(resultStr.begin(), resultStr.end() - 1) ); // unbase64
				resultStr = desDecryption(graphdog->sKey, std::string(encText.begin(), encText.end())); // des Decryption
				resultobj = GraphDogLib::StringToJsonObject(resultStr);// result.getObject();
			}
			catch(const std::string& msg)
			{
				resultCode = CURLE_CHUNK_FAILED;
			}
		}
		else
		{
			resultCode = CURLE_CHUNK_FAILED;
		}
	}
	else
	{
		//resultCode = CURLE_CHUNK_FAILED;
	}
	
	//callbackparam 통신과 무관함. 넣어준거 그대로 피드백.
	for(auto iter = command.commands.begin(); iter != command.commands.end(); ++iter)
	{
		if(iter->second.paramStr != "")
		{
			JsonBox::Object param = GraphDogLib::StringToJsonObject(iter->second.paramStr);
			resultobj[iter->first]["param"] = JsonBox::Value(param);
		}
	}
	
	bool newToken = false;
	// 새토큰발급일 경우
	if(resultobj["tokenUpdate"].getString()=="ok"){
		//정상결과시 AuID,Token 다시 세팅
		if(resultobj["state"].getString()=="ok"){
			command.caller->setAuID(resultobj["auID"].getString());
			command.caller->setCTime(resultobj["createTime"].getString());
			command.caller->isLogin=true;
		}else{
			command.caller->setCTime("9999");
		}
		//첫실행일경우 받아온 nick,flag 저장.
//		if(resultobj["isFirst"].getBoolean()==true){
//			command.caller->setNick(resultobj["nick"].getString());
//			command.caller->setFlag(resultobj["flag"].getString());
//		}
		//기존명령 다시 등록
		std::vector<CommandParam> vcp;
		for(std::map<string, CommandType>::const_iterator iter = command.commands.begin(); iter != command.commands.end(); ++iter)
		{
			JsonBox::Value param;
			param.loadFromString(iter->second.paramStr);
			vcp.push_back(CommandParam(iter->second.action, param.getObject(), iter->second.target, iter->second.selector ));
		}
		command.caller->command(vcp);
		
		for(std::map<string, CommandType>::iterator iter = command.commands.begin(); iter != command.commands.end(); ++iter)
		{
			iter->second.target = 0;
			iter->second.selector = 0;
		}
		newToken = true;
	}
	
	if(resultobj["errorcode"].getInt()==9999){
		command.caller->setCTime("9999");
		command.caller->errorCount++;
		if(command.caller->errorCount<5){
			std::vector<CommandParam> vcp;
			for(std::map<string, CommandType>::const_iterator iter = command.commands.begin(); iter != command.commands.end(); ++iter)
			{
				JsonBox::Value param;
				param.loadFromString(iter->second.paramStr);
				CommandParam cp;
				cp.action = iter->second.action;
				cp.param = param.getObject();
				cp.selector = iter->second.selector;
				cp.target = iter->second.target;
				vcp.push_back(cp);
			}
			command.caller->command(vcp);
			for(std::map<string, CommandType>::iterator iter = command.commands.begin(); iter != command.commands.end(); ++iter)
			{
				iter->second.target = 0;
				iter->second.selector = 0;
			}
		}
		newToken = true;
	}
	
	if(newToken == false) // 새토큰 발급이 아닌 경우.
	{
//		for(auto iter = command.commands.begin(); iter != command.commands.end(); ++iter)
//		{
//			CommandType test = iter->second;
//			CCLog("dummy");
//		}
		if(resultobj["state"].getString()=="ok"){
			command.caller->errorCount=0;
		}
		command.result = resultobj;
		command.chunk.resultCode = resultCode;
	}
	pthread_mutex_unlock(&command.caller->t_functionMutex);
	
	return NULL;
}