Skip to content

Instantly share code, notes, and snippets.

@Gab-km
Created April 28, 2012 19:59
Show Gist options
  • Save Gab-km/2521680 to your computer and use it in GitHub Desktop.
Save Gab-km/2521680 to your computer and use it in GitHub Desktop.
マルチパラダイムの書き方
module MultiParadigm
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 makeRijndaelManaged password =
//RijndaelManagedオブジェクトを作成
let rijndael = new RijndaelManaged()
//パスワードから共有キーと初期化ベクタを作成
let key, iv = generateKeyFromPassword password rijndael.KeySize rijndael.BlockSize
rijndael.Key <- key
rijndael.IV <- iv
rijndael
type Cryptography = Encryption | Decryption
let transform (cryptor : ICryptoTransform) encoder decoder (sourceString : string) : string =
//文字列をバイト型配列に変換する
let strBytes = encoder sourceString
//バイト型配列を暗号化または復号し、文字列に変換して返す
cryptor.TransformFinalBlock (strBytes, 0, strBytes.Length)
|> decoder
let transformString cryptography (rijndael : RijndaelManaged) sourceString =
match cryptography with
| Encryption ->
//対称暗号化オブジェクトの作成
use encryptor = rijndael.CreateEncryptor();
//文字列を暗号化する
transform encryptor Encoding.UTF8.GetBytes Convert.ToBase64String sourceString
| Decryption ->
//対称復号化オブジェクトの作成
use decryptor = rijndael.CreateDecryptor()
//暗号化された文字列を復号する
transform decryptor Convert.FromBase64String Encoding.UTF8.GetString sourceString
let encryptString sourceString password =
let rijndael = makeRijndaelManaged password
transformString Encryption rijndael sourceString
let decryptString sourceString password =
let rijndael = makeRijndaelManaged password
transformString Decryption rijndael sourceString
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment