1. はじめに
やってみた系自分用メモ。OpenSSLは何かと便利だけど、C#からどう使うのかよくわかりませんでした。「OpenSSL .NET を使うらしい」みたいなことが書いてありましたが、これもよくわからない。結局たどり着いたのは「openssl.exeを直接叩く」というものでした。やりたいことに対して、ゴールが目の前にあるのなら使います。
ということで、
- OpenSSLがインストールしてある
- OpenSSL.exe が実行できる(パスに追加してある)
が前提条件になります。以下の記事は導入時の参考になります。
#2. コード
Program.cs
// Program.cs
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
// openssl の実行ファイルパス
string opensslPath = @"openssl.exe";
// 実行したい openssl コマンド
string arguments = "ecparam -name prime256v1 -genkey";
// ProcessStartInfo を設定
ProcessStartInfo psi = new ProcessStartInfo
{
FileName = opensslPath,
Arguments = arguments,
RedirectStandardOutput = true, // 標準出力を取得
RedirectStandardError = true, // エラー出力も取得
UseShellExecute = false, // true のとき Redirect は無効
CreateNoWindow = true
};
try
{
using (Process proc = Process.Start(psi))
{
// 標準出力と標準エラーを読み取る
string output = proc.StandardOutput.ReadToEnd();
string error = proc.StandardError.ReadToEnd();
proc.WaitForExit(); // 終了を待つ
Console.WriteLine("Output:");
Console.WriteLine(output);
if (!string.IsNullOrEmpty(error))
{
Console.WriteLine("Error:");
Console.WriteLine(error);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
}
}
}