⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 caservice.cpp

📁 完成数字证书加密
💻 CPP
📖 第 1 页 / 共 3 页
字号:
	m_swap = m_db->m_swap, m_db->m_swap="";	return result;}string CAService::importThirdCRL(char* crl, string issuer){	CRL Crl;	return Crl.importThirdCRL(crl, issuer);}bool CAService::toBeHandle(string id){   if (atoi(id.c_str()) != m_id) {        return false;   }   return true;}void CAService::exportCertificateFromCertList(char* infile){	CertList *cl = new CertList();	assert( cl!=NULL );	cl->readCertFromCertList(infile);	if (cl) delete cl, cl=NULL;}bool CAService::checkInitialResult(){	bool flag = false;	if (readCAconfig("System", "Initial").c_str()=="yes") {		flag = true;	}	else {		flag= false;	}	return flag;}void CAService::initializeEnvironment(){	char path[512];	memset(path, 0, 512);	strcpy(path, CA_CONFIG_PATH);	if (!locateFile(path)) {		createCAConfigFile();	}		if (readCAconfig("System", "Initial")=="yes") {		cout<< "System has been initialized , do you want to repeat to do ? (y/n) ";		char ch=0;		cin >> ch;		if (tolower(ch)=='n') {			return ;		}		setCAConfigItem("Root", "", "no");		setCAConfigItem("System", "rootDN", "none");	}	assert(m_caPath!="");	if ((mkdir(m_caPath.c_str(), 0666)==-1) && (errno!=EEXIST)) {		writelog(strerror(errno));		return ;	}	string cd = "cd " + m_caPath;	system(cd.c_str());		mkdir(m_crlPath.c_str(), 0666);	mkdir(m_exportPath.c_str(), 0666);	mkdir(m_importPath.c_str(), 0666);	mkdir(m_rootPath.c_str(), 0666);	mkdir(m_usersPath.c_str(), 0666);	mkdir(m_reqPath.c_str(), 0666);	setCAConfigItem("System", "Initial", "yes");	if (!m_db->initCADB()) {		writelog("initializing db fail.");		return ;	}}void CAService::setCAConfigSet(string keyword, string object, string value){	this->setCAConfigItem("Log","time","");	this->setCAConfigItem("Log","object","");	this->setCAConfigItem("Log","content","");	this->setCAConfigItem("Log","status","");	this->setCAConfigItem("Log","why","");}void CAService::setCAConfigItem(string keyword, string objectName, string value){	FILE *fd = fopen(CA_CONFIG_PATH, "rb");	assert(fd != NULL);	char *line  = (char*)calloc(1, 1*K);	assert(line != NULL);	string config = "";	while (!feof(fd)) {		memset(line, 0, 1*K);		fgets(line, 1*K, fd); 		config.append(line);	}	fclose(fd);		NggObject *object = NggObject::fromXML(config);	assert(object != NULL);		for (int i=0; i<object->m_Contains.size(); i++) {		if (object->m_Contains[i]->m_Name==keyword) {			if (keyword == "Root" || keyword == "Operator" || keyword == "Administrator"|| keyword=="SerialNumber") {				object->m_Contains[i]->m_Value = value;			}			else {				NggObject *nggobject = object->m_Contains[i];				assert(object != NULL);				for (int ii=0; ii<nggobject->m_Contains.size(); ii++) {					if (nggobject->m_Contains[ii]->m_Name==objectName) {						nggobject->m_Contains[ii]->m_Value = value;						break;					}				}								if (nggobject) nggobject=NULL;								}							break;		}	}	fd = fopen(CA_CONFIG_PATH, "wb");	assert( fd!=NULL );		fputs(object->toXML().c_str(), fd);	if (object) delete object, object=NULL;	if (line) free(line), line=NULL;	fclose(fd);}void CAService::backup(string src, string dst, string action){	string shell="";		if (action=="cp") {		shell="touch "+dst;		system(shell.c_str());	}		shell="";	shell.append("cp ").		append(src).		append(" ").		append(dst);	system(shell.c_str());	if (action=="rm") {		shell="";		shell.append("rm ").append(src);		system(shell.c_str());	}	}bool CAService::issueRootCertificate(char*outMsg, stuSUBJECT *rootinfo, int bits, 	   					   int days, const char* certFile, const char* priFile, int type){	X509 *x509=NULL;	EVP_PKEY *pkey=NULL;	BIO * bcert=NULL,* bkey=NULL;	bool ret=true;	int i=0,j=0;	string cert=m_rootPath+"/";	cert.append(certFile);	string priv=m_rootPath+"/";	priv.append(priFile);	string srcCert = cert;	string dstCert = m_caPath + "/"+readCAconfig("Directory", "tmp")+"/";	dstCert.append(certFile);	string srcPriv = priv;	string dstPriv = m_caPath + "/"+readCAconfig("Directory", "tmp")+"/";	dstPriv.append(priFile);	if (readCAconfig("Root", "")=="yes") {		backup(srcCert, dstCert);		backup(srcPriv, dstPriv);	}	if(((bcert=BIO_new_file(cert.c_str(), "w"))== NULL)||			((bkey=BIO_new_file(priv.c_str(), "w")) == NULL))	{		strcpy(outMsg,"Create File Error");		return false;	}	if(makeRootCert(rootinfo,&x509,&pkey,bits,days,outMsg))	{		i=PEM_write_bio_X509(bcert,x509);		j=PEM_write_bio_PrivateKey(bkey,pkey,NULL,NULL,0,NULL, NULL);		if(!i||!j)		{			ret=false;			strcpy(outMsg,"Save Cert or Key File Error");		}	}	else		ret=false;	BIO_free(bcert);	BIO_free(bkey);	X509_free(x509);	EVP_PKEY_free(pkey);		if (readCAconfig("Root", "")=="yes") {		if (!ret) {			backup(dstCert, srcCert, "rm");			backup(dstPriv, srcPriv, "rm");		}	}		this->setCAConfigItem("Root","","yes");	int year=0, month=0, day=0;	getCurrentTime(year, month, day);	this->setCAConfigItem("Time","year",toString(year).c_str());	this->setCAConfigItem("Time","month",toString(month).c_str());	this->setCAConfigItem("Time","day",toString(day).c_str());	this->setCAConfigItem("Log","time","");	this->setCAConfigItem("Log","object","CA");	this->setCAConfigItem("Log","content","succeed to create root certificate !");	this->setCAConfigItem("Log","status","ok");	this->setCAConfigItem("Log","why","none");		setCAConfigItem("System", "rootCertPath", certFile);	setCAConfigItem("System", "rootKeyPath", priFile);		return true;}void CAService::getCurrentTime(int& year, int& month, int& day){	time_t tm;	time(&tm);	struct tm *begintime = localtime(&tm);	year = begintime->tm_year;	if (year>=100) {		year = 2000+year-100;	}	month = begintime->tm_mon+1;	day = begintime->tm_mday;}string CAService::toString(long value){	char str[10];	sprintf(str, "%d", value);	string result="";    return result.append(str);}bool CAService::issueTerminalCertificate(char* outfile, char *reqfile, int type, char* outlist, int len){	return makeUserCert(outfile, reqfile, type, outlist, len);}bool CAService::makeRootCert(stuSUBJECT *rootInfo, X509** x, EVP_PKEY** key, int bits, int days, char* outmsg){	X509* x509 = NULL;	EVP_PKEY* pk = NULL;	RSA* rsa = NULL;	X509_NAME *name = NULL;	x509 = X509_new();	pk = EVP_PKEY_new();	rsa = RSA_generate_key(bits, RSA_F4, NULL, NULL);	assert(x509 != NULL);	assert(pk != NULL);	assert(rsa != NULL);	if (!EVP_PKEY_assign_RSA(pk, rsa)) {		writelog("initializing  root cert env fail .");		EVP_PKEY_free(pk);		X509_free(x509);		return false;	}	X509_set_version(x509, 2);	m_serialNumber = 1;	m_sn = toString(m_serialNumber);	ASN1_INTEGER_set(X509_get_serialNumber(x509), m_serialNumber);	setCAConfigItem("SerialNumber", "", toString(++m_serialNumber));	X509_gmtime_adj(X509_get_notBefore(x509), 0);	X509_gmtime_adj(X509_get_notAfter(x509), (long)DAY*days);	setCAConfigItem("Time", "span", toString(days/365));	X509_set_pubkey(x509, pk);	name = X509_get_subject_name(x509);	setInfo(name,NID_name, rootInfo->name);		setInfo(name,NID_countryName, rootInfo->countryName);	setInfo(name,NID_organizationName, rootInfo->organizationName);	setInfo(name,NID_organizationalUnitName, rootInfo->organizationalUnitName);	setInfo(name,NID_commonName, rootInfo->commonName);	setCAConfigItem("System", "Issuer", rootInfo->name);	if (readCAconfig("Root", "")=="yes") {		if (checkWhetherUserHaveExisted(getRequestSubject(name).c_str())) {			writelog("user has existed .");			EVP_PKEY_free(pk);			X509_free(x509);			return false;		}	}		shutdownConnect();	initializeConnect();		X509_set_issuer_name(x509,name);	if (!X509_sign(x509, pk, EVP_sha1())) {		writelog("sign fail ..................");		EVP_PKEY_free(pk);		X509_free(x509);		return false;	}	importCertToDB(x509, "root", pk);		*x=x509;	*key=pk;}bool CAService::setInfo(X509_NAME* x509name, int type, char* iput){	X509_NAME_add_entry_by_NID(x509name,type,MBSTRING_ASC,(UCHAR*)iput,-1, -1, 0);	return true;}bool CAService::makeUserCert(char* outfile, char* reqfile, int type, char* outlist, int filelen){	if (readCAconfig("Root", "")=="no") {		writelog("root cert is not exist.");		return false;	}		BIO *reqbio = NULL;	const EVP_MD *dgst=NULL;	EVP_PKEY *pktmp=NULL;	X509_CINF *ci;	X509_REQ* req;	assert( m_rootCertPath!="" );	assert( m_rootPrivKeyPath!="" );	char cert[512], priv[512];	memset(cert, 0, 512);	memset(priv, 0, 512);	strcpy(cert, m_rootCertPath);	strcpy(priv, m_rootPrivKeyPath);	if (!locateFile(cert) && !locateFile(priv)) {		return false;	}		X509* rootcert= LoadCert(m_rootCertPath);	EVP_PKEY* key = loadRootPriv(m_rootPrivKeyPath);	assert(rootcert != NULL);	assert(key != NULL);		if (!X509_check_private_key(rootcert,key)) {		return false;	}	if (filelen != 0) {		if ((reqbio=BIO_new_mem_buf(reqfile, filelen))==NULL) {			return false;		}		}	else {		string req = m_reqPath + "/";		req.append(reqfile);		if ((reqbio=BIO_new_file(req.c_str(), "r"))==NULL) {			cout << "file : " << req << "is not exist " << endl;						return false;		}	}		if ((req=PEM_read_bio_X509_REQ(reqbio, NULL, NULL, NULL)) == NULL) {		return false;	}	dgst = EVP_get_digestbyname("sha1");	if ((pktmp=X509_REQ_get_pubkey(req)) == NULL) {		return false;	}//	int i=X509_REQ_verify(req,pktmp);	privkey is preserved by gui	int i=1;	EVP_PKEY_free(pktmp);		if (i<0) {		writelog("verity req error----------------");		return false;	}	if (!i) {		writelog("verity req error");		return false;	}	X509* x509 = X509_new();	assert(x509 != NULL);		X509_set_version(x509, 2L);		ASN1_INTEGER_set(X509_get_serialNumber(x509), atoi(readCAconfig("SerialNumber").c_str()));	m_sn = readCAconfig("SerialNumber");		setCAConfigItem("SerialNumber", "", toString(atoi(readCAconfig("SerialNumber").c_str())+1));	// exist ?	if (checkWhetherUserHaveExisted(getRequestSubject(X509_REQ_get_subject_name(req)).c_str())) {		writelog("user has existed .");		return false;	}//	shutdownConnect();//	initializeConnect();		X509_set_issuer_name(x509, X509_get_issuer_name(rootcert));		int year=0, month=0, day=0;	getCurrentTime(year, month, day);	int eclips = (year-atoi(readCAconfig("Time", "year").c_str()))*YEAR+				(month-atoi(readCAconfig("Time", "month").c_str()))*30+				(day-atoi(readCAconfig("Time", "day").c_str()));		int span = atoi(readCAconfig("Time", "span").c_str())*YEAR;	int result = span-eclips;	assert(result >= 0);	int days=atoi(readCAconfig("Users", "Period_of_Validate").c_str());	if (!days) {		days=1;	}	days*=365;		if (result >= days) {		X509_gmtime_adj(X509_get_notAfter(x509), (long)DAY*days);	}	else {		X509_gmtime_adj(X509_get_notAfter(x509), (long)DAY*span);	}	if (year <= (atoi(readCAconfig("Time", "year").c_str())+10)) {		X509_gmtime_adj(X509_get_notBefore(x509), year);	}	X509_set_pubkey(x509, X509_REQ_get_pubkey(req));	X509_set_subject_name(x509, X509_REQ_get_subject_name(req));		ci=rootcert->cert_info;		if (!X509_sign(x509,key,dgst)) {		writelog("signing to cert fail.");		return false;	}	string certType="";	if (type!=GW_CERTIFICATE) {		certType="user";	}	else {		certType="gw";	}		//	if (type==GW_CERTIFICATE) {		if (outlist==NULL) {			strcpy(outfile, createCertList(outlist, x509).c_str());			importCertListToDB(getDN(x509), outfile, certType);		}		else {			importCertListToDB(getDN(x509), createCertList(outlist, x509).c_str(), certType);		}//	}//	else {//		importCertToDB(x509, certType);//	}	if (!filelen) {//		if (type==USER_CERTIFICATE) {		BIO* bcert=NULL;		string user_cert = m_usersPath + "/";		user_cert.append(outfile);		if((bcert=BIO_new_file(user_cert.c_str(), "w"))== NULL) {			return false;		}		PEM_write_bio_X509(bcert,x509);		BIO_free(bcert);//		}	}//	else if (type==USER_CERTIFICATE) {	else {/*		BIO* out = BIO_new(BIO_s_mem());		PEM_write_bio_X509(out, x509);		int len = BIO_read(out, outfile, 10*K);

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -