作成 2010.08.14
更新 2011.11.27
PowerShell で他言語を使用する C# 編
このサンプルはテキストの暗号化と復号を行ないます。
この例では実行前に C:\temp フォルダを作成しておく必要があります。
$provider = New-Object Microsoft.CSharp.CSharpCodeProvider
$params = New-Object System.CodeDom.Compiler.CompilerParameters
$params.GenerateInMemory = $True
$params.TreatWarningsAsErrors = $True
$refs = "System.dll","mscorlib.dll"
$params.ReferencedAssemblies.AddRange($refs)

# C Sharp
$txtCode = '
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

public class CryptTest {
	public readonly char[] trim_password;
	public readonly byte[] crypt_key;
	public readonly byte[] crypt_IV;
	public const string TRIM_PASSWORD = "\t\r\n\0";
	public const string SECRET_PATH = @"C:\temp\sec-key.txt";
	public CryptTest(){
		trim_password = TRIM_PASSWORD.ToCharArray();
		if(File.Exists(SECRET_PATH)){
			string read_str = File.ReadAllText(SECRET_PATH);
			string[] temp_str1 = read_str.Split(new char[]{(char)10}, 2);
			crypt_key = Convert.FromBase64String(temp_str1[0]);
			crypt_IV = Convert.FromBase64String(temp_str1[1]);
		}else{
			RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();
			crypt_key = rc2CSP.Key;
			crypt_IV = rc2CSP.IV;
			File.WriteAllText(SECRET_PATH,
				Convert.ToBase64String(crypt_key)+"\n"+Convert.ToBase64String(crypt_IV));
		}
	}
	public string Encrypt(string plaintext){
		MemoryStream ms = new MemoryStream();
		RC2 rc2 = new RC2CryptoServiceProvider();
		CryptoStream s = new CryptoStream(ms,
			rc2.CreateEncryptor(crypt_key, crypt_IV),
			CryptoStreamMode.Write);
		byte [] p = Encoding.UTF8.GetBytes(plaintext);
		s.Write(p,0,p.Length);
		s.FlushFinalBlock();
		return Convert.ToBase64String(ms.ToArray());
	}
	public string Decrypt(string ciphertext){
		MemoryStream ms = new MemoryStream();
		RC2 rc2 = new RC2CryptoServiceProvider();
		CryptoStream s = new CryptoStream(ms,
			rc2.CreateDecryptor(crypt_key, crypt_IV),
			CryptoStreamMode.Write);
		byte [] c = Convert.FromBase64String(ciphertext);
		s.Write(c, 0, c.Length);
		s.FlushFinalBlock();
		return Encoding.UTF8.GetString(ms.GetBuffer()).Trim(trim_password);
	}
}
'

$results = $provider.CompileAssemblyFromSource($params, $txtCode)
$results.Errors
$mAssembly = $results.CompiledAssembly
$i = $mAssembly.CreateInstance("CryptTest")
$c = $i.Encrypt("!p@ssw0rd")
$c
$r = $i.Decrypt($c)
$r

©2004-2017 UPKEN IPv4