直接代码:
关键点,windows下带空格目录用双引号包含,openssl参数目录中带空格,将空格用双引号包含
// 获取.exe运行目录
char exeFullPath[MAX_PATH]; // Full path
GetModuleFileName(NULL,exeFullPath,MAX_PATH);
std::string strPath=(std::string)exeFullPath; // Get full path of the file
size_t pos = strPath.find_last_of('\\', strPath.length());
std::string path = strPath.substr(0, pos+1);
std::string path_cmd = path;
std::string path_ssl = path;
// 测试
// path = "d:\\documents\\visual studio 2010\\a b c\\Projects\\1 2 3\\LZ_UTP\Debug\\";
size_t pos_cmd = path_cmd.find_first_of(' ');
while (pos_cmd != std::string::npos){
size_t pos_a = path_cmd.find_first_of('\\', pos_cmd);
size_t pos_b = path_cmd.find_last_of('\\', pos_cmd);
if (pos_a!= std::string::npos) {
path_cmd.replace(pos_a, 1,"\"\\");
++pos_a;
}
if (pos_b!= std::string::npos) {
path_cmd.replace(pos_b, 1,"\\\"");
++pos_a;
}
pos_cmd = path_cmd.find_first_of(' ', pos_a);
}
size_t pos_ssl = path_ssl.find_first_of(' ');
while (pos_ssl != std::string::npos){
path_ssl.replace(pos_ssl, 1,"\" \"");
pos_ssl = path_ssl.find_first_of(' ', pos_ssl + 2);
}
//openssl x509 -in utp_test_verify_sign.cer -inform PEM -out cert.der -outform DER
// std::string command_rd = path_cmd + "openssl.exe x509 -in "+ path_ssl +"utp_test_verify_sign.cer -inform PEM -out "+ path_ssl + "cert.der -outform DER";
std::string command_rd = path_cmd + "openssl.exe x509 -in ";
CString strFile = _T("");
CString strFileName;
CFileDialog dlgFile(TRUE, NULL, path.c_str(), OFN_HIDEREADONLY, _T("(*.cer;*.pfx;)|*.cer;*.pfx||"), NULL);
if (dlgFile.DoModal())
{
strFile = dlgFile.GetPathName();
strFileName = dlgFile.GetFileTitle();
}
if (!strFile.IsEmpty()){
std::string srcFile = CT2A(strFile.GetBuffer());
size_t pos_ssl = srcFile.find_first_of(' ');
while (pos_ssl != std::string::npos){
srcFile.replace(pos_ssl, 1,"\" \"");
pos_ssl = srcFile.find_first_of(' ', pos_ssl + 2);
}
command_rd += srcFile;
command_rd += " -inform PEM -out ";
command_rd += path_ssl;
std::string name = CT2A(strFileName.GetBuffer());
command_rd += name;
command_rd += ".der";
command_rd += " -outform DER";
}
TRACE(command_rd.c_str());
int ret = system(command_rd.c_str());
if (ret != 0){
MessageBox("生成证书失败!");
}else{
MessageBox("生成证书成功!");
}