暗号化をWindowsに任せる2
↑の続編。 こっちの方が利用頻度は高いかな。
ProtectedMemoryで暗号化したデータをファイル等に保存しても、
完全な形で復元できません。(何文字か壊れる)
まあ中の人にも事情というものがあるのでしょう。
ということでファイルに保存する時のことを考えて、ProtectedDataクラスの使い方も簡単にご紹介。
public class Foo { private readonly DataProtectionScope scope = DataProtectionScope.CurrentUser; private readonly byte[] entropy = null;//new byte[] { 1 }; private readonly Encoding encode = Encoding.Unicode; private readonly string filePath = "protecteddata.txt"; public void Protect() { Console.WriteLine( "pass :" ); byte[] pass = this.encode.GetBytes( Console.ReadLine() ); byte[] encryptedData = ProtectedData.Protect( pass, this.entropy, this.scope ); Console.WriteLine( this.encode.GetString( encryptedData ) ); using ( Stream s = File.Open( this.filePath, FileMode.Create ) ) { s.Write( encryptedData, 0, encryptedData.Length ); } } public void Unprotect() { byte[] readBuffer = new byte[ 512 ]; using ( Stream s = File.Open( this.filePath, FileMode.Open ) ) { s.Read( readBuffer, 0, readBuffer.Length ); } byte[] decryptedData = ProtectedData.Unprotect( readBuffer, this.entropy, this.scope ); Console.WriteLine( this.encode.GetString( decryptedData ) ); } }
手抜きな部分が多いですが(特にentropyあたり)、一応これで復号可能です。笑
protecteddata.txtというファイルに吐き出します。おえーー。
こっちはProtectedMemoryと違い、16の倍数バイトでなくても大丈夫みたいです。
あと、Unprotectを実行しても"\0"が余計にくっついて来ないという。
ProtectedMemoryでは渡した配列を対象に操作を行いましたが、
ProtectedDataでは結果が別の配列として返ってきます。
もちろん文書はRijndael等で暗号化し、鍵のみWindowsに任せるようにしましょう。
それぞれの詳細についてはMSDN Libをご覧くださいませー。