Created
April 28, 2012 19:51
-
-
Save Gab-km/2521632 to your computer and use it in GitHub Desktop.
手続き型の書き方
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module Imperative | |
| open System | |
| open System.Text | |
| open System.Security.Cryptography | |
| let generateKeyFromPassword password keySize blockSize = | |
| //パスワードから共有キーと初期化ベクタを作成する | |
| //saltを決める | |
| let salt = Encoding.UTF8.GetBytes "saltは必ず8バイト以上" | |
| //Rfc2898DeriveBytesオブジェクトを作成する | |
| use deriveBytes = new Rfc2898DeriveBytes (password, salt) | |
| //反復処理回数を指定する デフォルトで1000回 | |
| deriveBytes.IterationCount <- 1000 | |
| //共有キーと初期化ベクタを生成する | |
| deriveBytes.GetBytes (keySize/8), deriveBytes.GetBytes (blockSize/8) | |
| let encryptString sourceString password = | |
| //RijndaelManagedオブジェクトを作成 | |
| let rijndael = new RijndaelManaged() | |
| //パスワードから共有キーと初期化ベクタを作成 | |
| let key, iv = generateKeyFromPassword password rijndael.KeySize rijndael.BlockSize | |
| rijndael.Key <- key | |
| rijndael.IV <- iv | |
| //文字列をバイト型配列に変換する | |
| let strBytes = Encoding.UTF8.GetBytes (sourceString : string) | |
| //対称暗号化オブジェクトの作成 | |
| use encryptor = rijndael.CreateEncryptor(); | |
| //バイト型配列を暗号化する | |
| let encBytes = encryptor.TransformFinalBlock (strBytes, 0, strBytes.Length) | |
| //バイト型配列を文字列に変換して返す | |
| Convert.ToBase64String encBytes | |
| let decryptString sourceString password = | |
| //RijndaelManagedオブジェクトを作成 | |
| let rijndael = new RijndaelManaged() | |
| //パスワードから共有キーと初期化ベクタを作成 | |
| let key, iv = generateKeyFromPassword password rijndael.KeySize rijndael.BlockSize | |
| rijndael.Key <- key | |
| rijndael.IV <- iv | |
| //文字列をバイト型配列に戻す | |
| let strBytes = Convert.FromBase64String sourceString | |
| //対称暗号化オブジェクトの作成 | |
| use decryptor = rijndael.CreateDecryptor() | |
| //バイト型配列を復号する | |
| //復号に失敗すると例外CryptographicExceptionが発生 | |
| let decBytes = decryptor.TransformFinalBlock (strBytes, 0, strBytes.Length) | |
| //バイト型配列を文字列に戻して返す | |
| Encoding.UTF8.GetString decBytes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment