CaUtil_openssl.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  1. using Microsoft.Extensions.Logging;
  2. using Newtonsoft.Json;
  3. using System;
  4. using System.Diagnostics;
  5. using System.Diagnostics.Metrics;
  6. using System.Reflection;
  7. using System.Runtime.ConstrainedExecution;
  8. using System.Security.AccessControl;
  9. using System.Security.Cryptography;
  10. using System.Security.Cryptography.X509Certificates;
  11. using System.Text;
  12. using System.Xml.Linq;
  13. namespace CAUtilLib
  14. {
  15. public partial class CaUtil_openssl
  16. {
  17. /// <summary>
  18. /// 建構子生成路徑可透過SetPath進行路徑覆寫
  19. /// </summary>
  20. public CaUtil_openssl(ILogger<CaUtil> logger)
  21. {
  22. if (string.IsNullOrWhiteSpace(this.path))
  23. {
  24. string path = Directory.GetCurrentDirectory();
  25. //string parentPath = Directory.GetParent(Directory.GetParent(Directory.GetParent(Directory.GetParent(path).ToString()).ToString()).ToString()) + @"\";
  26. string filePath = Path.Combine(path, "temp");
  27. bool exists = Directory.Exists(filePath);
  28. if (!exists)
  29. {
  30. CreateFolder(filePath);
  31. MoveFile(@"zerova_v3.cnf", filePath + @"\zerova_v3.cnf");
  32. }
  33. this.path = filePath;
  34. }
  35. this.logger = logger;
  36. }
  37. private string path = "";
  38. private readonly ILogger<CaUtil> logger;
  39. /// <summary>
  40. /// 檔案路徑
  41. /// </summary>
  42. public string SavePath
  43. {
  44. get => path;
  45. set
  46. {
  47. if (this.path == value)
  48. {
  49. return;
  50. }
  51. this.path = value;
  52. string filePath = this.path;
  53. CreateFolder(filePath);
  54. MoveFile(@"zerova_v3.cnf", Path.Combine(filePath, @"zerova_v3.cnf"));
  55. }
  56. }
  57. public OSType OS { get; set; }
  58. private string ExecuteShell => OS == OSType.Windows ? "cmd.exe" : "/bin/bash";
  59. private string CatCmd => OS == OSType.Windows ? "type " : "cat";
  60. /// <summary>
  61. /// 生成RootCA憑證
  62. /// </summary>
  63. /// <param name="name">Root CA</param>
  64. /// <param name="Days">憑證有效期限</param>
  65. /// <param name="SerialNumber">序號</param>
  66. /// <param name="Cn">主機名或網站地址</param>
  67. /// <param name="organizationName">組織名稱</param>
  68. /// <param name="Hash">使用SHA256/SHA512演算法進行簽名</param>
  69. /// <param name="RsaKey">生成2048位元或4096位元的私鑰</param>
  70. /// <param name="Caformat">生成crt 或者pem 格式</param>
  71. /// <returns></returns>
  72. public async Task<bool> CreateRootCA(
  73. string name,
  74. string commonName,
  75. string organizationName,
  76. string Country = "TW",
  77. string State = "Taipei",
  78. int Days = 3650,
  79. string SerialNumber = "",
  80. HashAlgorithm Hash = HashAlgorithm.SHA512,
  81. OpensslGenrsaRsa RsaKey = OpensslGenrsaRsa.Key4096)
  82. {
  83. if (string.IsNullOrEmpty(SerialNumber))
  84. {
  85. SerialNumber = await GetOpenSSLRandSn();
  86. }
  87. var status = false;
  88. var keyName = "";
  89. keyName = name;
  90. string sn = "0x" + SerialNumber;
  91. HashAlgorithm ha = Hash;
  92. var sslKey = (int)RsaKey;
  93. var subjString = CreateSubjectString(CommonName: commonName, Organization: organizationName, Country: Country, State: State);
  94. if (await CreateKey(keyName, RsaKey) &&
  95. await ExecShellCmd("openssl", $"req -x509 -new -nodes -set_serial {sn} -key {keyName}.key -{ha} -days {Days} -subj \"{subjString}\" -out {name}.crt ") &&
  96. await MergeFile($"{name}.pem", $"{name}.crt", $"{keyName}.key")
  97. //&& await ExecShellCmd("certutil", $"-f -addstore root {RootCa}.crt ")
  98. //&& await ExecShellCmd("certutil", $"-f -addstore root {RootCa}.crt ")
  99. )
  100. {
  101. return true;
  102. }
  103. return false;
  104. //create
  105. string[] strs = new string[5];
  106. strs[0] = "openssl genrsa -out " + keyName + ".key " + sslKey + " ";
  107. strs[1] = "openssl req -x509 -new -nodes -set_serial " + sn + " -key " + keyName + ".key -" + ha + " -days " + Days + " -subj \"/C=TW/ST=Taipei/O=" + organizationName + "/OU=phihong_sub.IO/CN=" + commonName + "/emailAddress=phihong_sub@mail.com\" -out " + name + ".crt ";
  108. strs[2] = CatCmd + name + ".crt " + keyName + ".key > " + name + ".pem ";
  109. strs[3] = "certutil -f -addstore root " + name + ".crt ";
  110. strs[4] = "certutil -f -addstore root " + name + ".crt ";
  111. for (int i = 0; i < strs.Length; i++)
  112. {
  113. var process = new Process
  114. {
  115. StartInfo = new ProcessStartInfo
  116. {
  117. FileName = ExecuteShell,
  118. Arguments = "/C " + strs[i],
  119. WorkingDirectory = this.path,
  120. StandardOutputEncoding = Encoding.UTF8,
  121. RedirectStandardOutput = true,
  122. RedirectStandardError = true,
  123. UseShellExecute = false,
  124. Verb = "runas"
  125. }
  126. };
  127. process.Start();
  128. _ = process.StandardOutput.ReadToEndAsync().ContinueWith(( t => {
  129. logger.LogTrace(t.Result);
  130. }));
  131. _ = process.StandardError.ReadToEndAsync().ContinueWith((t => {
  132. logger.LogTrace(t.Result);
  133. }));
  134. await process.WaitForExitAsync();
  135. if (process.ExitCode != 0)
  136. {
  137. return false;
  138. }
  139. }
  140. return status;
  141. }
  142. /// <summary>
  143. /// 生成SubCA子憑證
  144. /// </summary>
  145. /// <param name="RootCaName">CA憑證名稱</param>
  146. /// <param name="Days">憑證有效期限</param>
  147. /// <param name="SubCA">子憑證名稱</param>
  148. /// <param name="SerialNumber">序號</param>
  149. /// <param name="commonName">主機名或網站地址</param>
  150. /// <param name="organizationName">組織名稱</param>
  151. /// <param name="Hash">使用SHA256/SHA512演算法進行簽名</param>
  152. /// <param name="RsaKey">生成2048位元或4096位元的私鑰</param>
  153. /// <param name="Caformat">生成crt 或者pem 格式</param>
  154. /// <returns></returns>
  155. public async Task<bool> CreateSubCA(string RootCa, string Days,
  156. string SubCA, string SerialNumber, string commonName, string organizationName, HashAlgorithm Hash, OpensslGenrsaRsa RsaKey, Certificateformat Caformat)
  157. {
  158. if (string.IsNullOrEmpty(SerialNumber))
  159. {
  160. SerialNumber = await GetOpenSSLRandSn();
  161. }
  162. var status = false;
  163. var str = "";
  164. string sn = "0x" + SerialNumber;
  165. //hashAlgorithm ha = Hash;
  166. var sslKey = (int)RsaKey;
  167. Certificateformat format = Caformat;
  168. if (await ExecShellCmd("openssl", $"genrsa -out {SubCA}.key {sslKey}") &&
  169. await ExecShellCmd("openssl", $"req -new -{Hash} -nodes -key {SubCA}.key -out {SubCA}.csr -subj \"/C=TW/ST=Taipei/O={organizationName}/OU=phihong_sub.IO/CN={commonName}/emailAddress=phihong_sub@mail.com\" ") &&
  170. await ExecShellCmd("openssl", $"x509 -set_serial {sn} -req -in {SubCA}.csr -CA {RootCa}.crt -CAkey {RootCa}.key -CAcreateserial -out {SubCA}.crt -days {Days} -sha256 -extfile zerova_v3.cnf ") &&
  171. await MergeFile($"{SubCA}.pem", $"{SubCA}.crt", $"{SubCA}.key"))
  172. {
  173. return true;
  174. }
  175. return false;
  176. string[] strs = new string[4];
  177. strs[0] = "openssl genrsa -out " + SubCA + ".key " + sslKey + " ";
  178. strs[1] = "openssl req -new -" + Hash + " -nodes -key " + SubCA + ".key -out " + SubCA + ".csr -subj \"/C=TW/ST=Taipei/O=" + organizationName + "/OU=phihong_sub.IO/CN=" + commonName + "/emailAddress=phihong_sub@mail.com\" ";
  179. //var str8 = "openssl x509 -set_serial " + sn + " -req -in " + subKeyName + ".csr -CA " + caPath + "\\" + crtName + ".crt -CAkey " + this.path + "\\" + rootCaName + ".key -CAcreateserial -out " + subKeyName + ".crt -days " + days + " -sha256 -extfile zerova_v3.cnf ";
  180. strs[2] = "openssl x509 -set_serial " + sn + " -req -in " + SubCA + ".csr -CA " + RootCa + ".crt -CAkey " + this.path + "\\" + RootCa + ".key -CAcreateserial -out " + SubCA + ".crt -days " + Days + " -sha256 -extfile zerova_v3.cnf ";
  181. strs[3] = CatCmd + SubCA + ".crt " + SubCA + ".key > " + SubCA + ".pem ";
  182. for (int i = 0; i < strs.Length; i++)
  183. {
  184. var process = new Process
  185. {
  186. StartInfo = new ProcessStartInfo
  187. {
  188. FileName = ExecuteShell,
  189. Arguments = "/C " + strs[i],
  190. WorkingDirectory = this.path,//"D:\\project\\vs\\ConsoleApp2",
  191. RedirectStandardOutput = true,
  192. UseShellExecute = false,
  193. Verb = "runas"
  194. }
  195. };
  196. process.Start();
  197. string output = process.StandardOutput.ReadToEnd();
  198. await process.WaitForExitAsync();
  199. }
  200. return status;
  201. }
  202. public async Task<bool> SignCsr(string SubCA, string RootCa, int? Days = null, string? SerialNumber = null)
  203. {
  204. Days ??= 3650;
  205. if (string.IsNullOrEmpty(SerialNumber))
  206. {
  207. SerialNumber = await GetOpenSSLRandSn();
  208. }
  209. string sn = "0x" + SerialNumber;
  210. if (await ExecShellCmd("openssl", $"x509 -set_serial {sn} -req -in {SubCA}.csr -CA {RootCa}.crt -CAkey {RootCa}.key -CAcreateserial -out {SubCA}.crt -days {Days} -sha256 -extfile zerova_v3.cnf "))
  211. {
  212. return true;
  213. }
  214. return false;
  215. }
  216. /// <summary>
  217. /// 生成Csr 檔案
  218. /// </summary>
  219. /// <param name="Key">key 名稱</param>
  220. /// <param name="Csr">csr 名稱</param>
  221. /// <param name="commonName">主機名或網站地址</param>
  222. /// <param name="organizationName">組織名稱</param>
  223. /// <returns></returns>
  224. public async Task<bool> CreateCsr(
  225. string Key,
  226. string Csr,
  227. string commonName,
  228. string organizationName,
  229. HashAlgorithm Hash = HashAlgorithm.SHA512)
  230. {
  231. var status = false;
  232. var subjString = CreateSubjectString(CommonName: commonName, Organization: organizationName, Country: "TW", State: "Taipei");
  233. if (await ExecShellCmd("openssl", $"req -new -{Hash} -nodes -key {Key}.key -out {Csr}.csr -subj \"{subjString}\" "))
  234. {
  235. return true;
  236. }
  237. return false;
  238. string[] strs = new string[4];
  239. strs[0] = "openssl req -new -SHA256 -nodes -key " + Key + ".key -out " + Csr + ".csr -subj \"/C=TW/ST=Taipei/O=" + organizationName + "/OU=phihong_sub.IO/CN=" + commonName + "/emailAddress=phihong_sub@mail.com\" ";
  240. for (int i = 0; i < strs.Length; i++)
  241. {
  242. var process = new Process
  243. {
  244. StartInfo = new ProcessStartInfo
  245. {
  246. FileName = ExecuteShell,
  247. Arguments = "/C " + strs[i],
  248. WorkingDirectory = this.path,//"D:\\project\\vs\\ConsoleApp2",
  249. RedirectStandardOutput = true,
  250. UseShellExecute = false,
  251. Verb = "runas"
  252. }
  253. };
  254. process.Start();
  255. string output = process.StandardOutput.ReadToEnd();
  256. await process.WaitForExitAsync();
  257. }
  258. return status;
  259. }
  260. private object CreateSubjectString(string CommonName = "", string Organization = "", string Country = "", string State = "")
  261. {
  262. ///C=TW/ST=Taipei/O={organizationName}/OU=phihong_sub.IO/CN={commonName}/emailAddress=phihong_sub@mail.com\
  263. var toReturn = string.Empty;
  264. if (!string.IsNullOrEmpty(Country))
  265. {
  266. toReturn += $"/C={Country}";
  267. }
  268. if (!string.IsNullOrEmpty(State))
  269. {
  270. toReturn += $"/ST={State}";
  271. }
  272. if (!string.IsNullOrEmpty(Organization))
  273. {
  274. toReturn += $"/O={Organization}";
  275. }
  276. if (!string.IsNullOrEmpty(CommonName))
  277. {
  278. toReturn += $"/CN={CommonName}";
  279. }
  280. return toReturn;
  281. }
  282. /// <summary>
  283. /// 讀取憑證資訊
  284. /// </summary>
  285. /// <param name="path">檔案名稱</param>
  286. /// <param name="fileName">檔案路徑</param>
  287. /// <returns></returns>
  288. public string ReadCertificateHashData(string path, string fileName)//改成接收pem string 格式
  289. {
  290. var json = "";
  291. var file = Path.Combine(path, fileName);
  292. X509Certificate2 certificate = new X509Certificate2(file);
  293. X509Extension extension = certificate.Extensions["2.5.29.35"];
  294. var issuer_key_hash = "";
  295. if (extension != null)
  296. {
  297. issuer_key_hash = extension.Format(true);
  298. }
  299. string hashAlgorithm = certificate.SignatureAlgorithm.FriendlyName;
  300. string serialNumber = certificate.SerialNumber;
  301. byte[] issuerDER = certificate.IssuerName.RawData;
  302. SHA1 sha1 = SHA1.Create();
  303. byte[] hashBytes = sha1.ComputeHash(issuerDER);
  304. var data = new
  305. {
  306. hashAlgorithm = hashAlgorithm,
  307. issuerNameHash = BitConverter.ToString(hashBytes).Replace("-", ""),
  308. issuerKeyHash = issuer_key_hash,
  309. serialNumber = serialNumber,
  310. thumbprint = certificate.Thumbprint
  311. };
  312. string thumbprint = certificate.Thumbprint;
  313. json = JsonConvert.SerializeObject(data);
  314. return json;
  315. }
  316. /// <summary>
  317. /// 讀取憑證資訊
  318. /// </summary>
  319. /// <param name="FileName">檔案名稱</param>
  320. /// <returns></returns>
  321. public string ReadCertificateHashData(string fileName)
  322. {
  323. var json = "";
  324. var file = Path.Combine(this.path, fileName);
  325. X509Certificate2 certificate = new X509Certificate2(file);
  326. X509Extension extension = certificate.Extensions["2.5.29.35"];
  327. var issuer_key_hash = "";
  328. if (extension != null)
  329. {
  330. issuer_key_hash = extension.Format(true);
  331. }
  332. string hashAlgorithm = certificate.SignatureAlgorithm.FriendlyName;
  333. string serialNumber = certificate.SerialNumber;
  334. byte[] issuerDER = certificate.IssuerName.RawData;
  335. SHA1 sha1 = SHA1.Create();
  336. byte[] hashBytes = sha1.ComputeHash(issuerDER);
  337. var data = new
  338. {
  339. hashAlgorithm,
  340. issuerNameHash = BitConverter.ToString(hashBytes).Replace("-", ""),
  341. issuerKeyHash = issuer_key_hash,
  342. serialNumber,
  343. thumbprint = certificate.Thumbprint
  344. };
  345. string thumbprint = certificate.Thumbprint;
  346. json = JsonConvert.SerializeObject(data);
  347. return json;
  348. }
  349. /// <summary>
  350. /// PEM 格式的憑證的內容
  351. /// </summary>
  352. /// <param name="str">憑證內容</param>
  353. /// <returns></returns>
  354. public string ReadCertificateHashDataByString(string str)
  355. {
  356. var json = "";
  357. byte[] UTF8bytes = Encoding.UTF8.GetBytes(str);
  358. X509Certificate2 certificate = new X509Certificate2(UTF8bytes);
  359. X509Extension extension = certificate.Extensions["2.5.29.35"];
  360. var issuer_key_hash = "";
  361. if (extension != null)
  362. {
  363. issuer_key_hash = extension.Format(true);
  364. }
  365. string hashAlgorithm = certificate.SignatureAlgorithm.FriendlyName;
  366. string serialNumber = certificate.SerialNumber;
  367. byte[] issuerDER = certificate.IssuerName.RawData;
  368. SHA1 sha1 = SHA1.Create();
  369. byte[] hashBytes = sha1.ComputeHash(issuerDER);
  370. var data = new
  371. {
  372. hashAlgorithm = hashAlgorithm,
  373. issuerNameHash = BitConverter.ToString(hashBytes).Replace("-", ""),
  374. issuerKeyHash = issuer_key_hash,
  375. serialNumber = serialNumber,
  376. thumbprint = certificate.Thumbprint
  377. };
  378. string thumbprint = certificate.Thumbprint;
  379. json = JsonConvert.SerializeObject(data);
  380. return json;
  381. }
  382. /// <summary>
  383. /// 驗證client憑證
  384. /// </summary>
  385. /// <param name="StrCA">CA憑證</param>
  386. /// <param name="StrSub">子憑證</param>
  387. /// <param name="Url">url localhost:3000</param>
  388. /// <returns></returns>
  389. public async Task<bool> VerifyClient(string CA, string SubCA, string Url)
  390. {
  391. var str = "";
  392. bool isExists = false;
  393. if (await ExecShellCmd("openssl", $"s_client -connect {Url} -CAfile {CA} -cert {SubCA} -tls1_2 -state"))
  394. {
  395. return true;
  396. }
  397. return false;
  398. var str1 = "openssl s_client -connect " + Url + " -CAfile " + CA + " -cert " + SubCA + " -tls1_2 -state ";
  399. str = await ClientCmd(str1);
  400. string searchString = "(ok)";
  401. string line = GetLineFromString(str, searchString);
  402. if (line != null)
  403. isExists = line.Contains(searchString);
  404. return isExists;
  405. }
  406. /// <summary>
  407. /// Cmd字串指令
  408. /// </summary>
  409. /// <param name="str1">字串指令</param>
  410. /// <returns></returns>
  411. private async Task<string> ClientCmd(string str1)
  412. {
  413. var status = false;
  414. var str = "";
  415. string[] strs = { str1 };
  416. for (int i = 0; i < strs.Length; i++)
  417. {
  418. var process = new Process
  419. {
  420. StartInfo = new ProcessStartInfo
  421. {
  422. FileName = ExecuteShell,
  423. Arguments = "/C " + strs[i],
  424. WorkingDirectory = this.path,//"D:\\project\\vs\\ConsoleApp2",
  425. RedirectStandardOutput = true,
  426. UseShellExecute = false,
  427. //Verb = "runas"
  428. }
  429. };
  430. process.Start();
  431. var output = new List<string>();
  432. while (process.StandardOutput.Peek() > -1)
  433. {
  434. output.Add(process.StandardOutput.ReadLine());
  435. }
  436. process.Kill();
  437. str = string.Join("", output.ToArray());
  438. }
  439. return str;
  440. }
  441. /// <summary>
  442. /// 將Root CA與Sub CA進行憑證驗證
  443. /// </summary>
  444. /// <param name="Ca">CA檔案名稱</param>
  445. /// <param name="Sub">SubCA憑證名稱</param>
  446. /// <returns>True/Flase</returns>
  447. public async Task<bool> VerifyCertificateByCertificate(string Sub, string Ca)
  448. {
  449. if (await ExecShellCmd("openssl", $"verify -CAfile {Ca} {Sub}"))
  450. {
  451. return true;
  452. }
  453. return false;
  454. var status = true;
  455. var str = "";
  456. var str1 = "openssl verify -CAfile " + Ca + " " + Sub;
  457. bool isExists = false;
  458. str = await ClientCmd(str1);
  459. string searchString = "OK";
  460. string line = GetLineFromString(str, searchString);
  461. if (line != null)
  462. isExists = line.Contains(searchString);
  463. return isExists;
  464. }
  465. public async Task<bool> VerifyCertificateByCertificates(string Sub, string CaPath)
  466. {
  467. if (await ExecShellCmd("openssl", $"verify -CApath {CaPath} {Sub}"))
  468. {
  469. return true;
  470. }
  471. return false;
  472. }
  473. public async Task<bool> CalculateHash(string CrtName,string hashName)
  474. {
  475. if (await ExecShellCmd("openssl", $"x509 -in {CrtName} -hash -noout -out {hashName}"))
  476. {
  477. return true;
  478. }
  479. return false;
  480. }
  481. /// <summary>
  482. /// Crt轉Pem
  483. /// </summary>
  484. /// <param name="CaName">檔案名稱</param>
  485. /// <returns></returns>
  486. public async Task<bool> CrtToPem(string CaName)
  487. {
  488. if (await ExecShellCmd("openssl", $"x509 -in {CaName}.crt -out {CaName}.pem"))
  489. {
  490. return true;
  491. }
  492. return false;
  493. var status = false;
  494. var str = "openssl x509 -in " + CaName + ".crt -out " + CaName + ".pem ";
  495. var process = new Process
  496. {
  497. StartInfo = new ProcessStartInfo
  498. {
  499. FileName = ExecuteShell,
  500. Arguments = "/C " + str,
  501. WorkingDirectory = this.path,
  502. RedirectStandardOutput = true,
  503. UseShellExecute = false,
  504. Verb = "runas"
  505. }
  506. };
  507. process.Start();
  508. string output = process.StandardOutput.ReadToEnd();
  509. await process.WaitForExitAsync();
  510. return status;
  511. }
  512. /// <summary>
  513. /// Pem轉Crt
  514. /// </summary>
  515. /// <param name="CaName">檔案名稱</param>
  516. /// <returns></returns>
  517. public async Task<bool> PemToCrt(string CaName)
  518. {
  519. if (await ExecShellCmd("openssl", $"x509 -outform der -in {CaName}.pem -out {CaName}.crt"))
  520. {
  521. return true;
  522. }
  523. return false;
  524. var status = false;
  525. var str = "openssl x509 -outform der -in " + CaName + ".pem -out " + CaName + ".crt ";
  526. var process = new Process
  527. {
  528. StartInfo = new ProcessStartInfo
  529. {
  530. FileName = ExecuteShell,
  531. Arguments = "/C " + str,
  532. WorkingDirectory = this.path,
  533. RedirectStandardOutput = true,
  534. UseShellExecute = false,
  535. Verb = "runas"
  536. }
  537. };
  538. process.Start();
  539. string output = process.StandardOutput.ReadToEnd();
  540. await process.WaitForExitAsync();
  541. return status;
  542. }
  543. public async Task<bool> CreateKey(string keyName,
  544. OpensslGenrsaRsa RsaKey = OpensslGenrsaRsa.Key4096)
  545. {
  546. var sslKey = (int)RsaKey;
  547. if (await ExecShellCmd("openssl", $"genrsa -out {keyName}.key {sslKey}"))
  548. {
  549. return true;
  550. }
  551. return false;
  552. }
  553. /// <summary>
  554. /// 產生資料夾
  555. /// </summary>
  556. /// <param name="path"></param>
  557. /// <returns></returns>
  558. private bool CreateFolder(string path)
  559. {
  560. string subPath = path;
  561. bool status = true;
  562. bool exists = Directory.Exists(subPath);
  563. status = !exists;
  564. if (status)
  565. {
  566. Directory.CreateDirectory(subPath);
  567. }
  568. return status;
  569. }
  570. /// <summary>
  571. /// 確認檔案是否存在
  572. /// </summary>
  573. /// <param name="filePath"></param>
  574. /// <returns></returns>
  575. private bool CheckFiles(string FilePath)
  576. {
  577. bool status = true;
  578. bool exists = File.Exists(FilePath);
  579. status = exists;
  580. return status;
  581. }
  582. /// <summary>
  583. /// 檔案搬移
  584. /// </summary>
  585. /// <param name="file"></param>
  586. /// <param name="moveTo"></param>
  587. /// <returns></returns>
  588. private bool MoveFile(string file, string moveTo)
  589. {
  590. bool status = false;
  591. if (CheckFiles(file) &&
  592. !CheckFiles(moveTo))
  593. {
  594. //File.Move(file, moveTo);
  595. File.Copy(file, moveTo, true);
  596. status = true;
  597. }
  598. else
  599. {
  600. }
  601. return status;
  602. }
  603. /// <summary>
  604. /// 取得第幾行的字串
  605. /// </summary>
  606. /// <param name="InputString"></param>
  607. /// <param name="SearchString"></param>
  608. /// <returns></returns>
  609. private static string GetLineFromString(string InputString, string SearchString)
  610. {
  611. using (StringReader reader = new StringReader(InputString))
  612. {
  613. int lineNumber = 1;
  614. string line = "";
  615. while ((line = reader.ReadLine()) != null)
  616. {
  617. if (line.Contains(SearchString))
  618. {
  619. return line;
  620. }
  621. lineNumber++;
  622. }
  623. return reader.ReadLine();
  624. }
  625. }
  626. }
  627. }