2009年5月1日金曜日

as3cryptoを使ってみた


ようやくas3cryptoを試してみた。
ドキュメント少ないなぁ・・・と思っていたけれど、始めてみたらDemoソースコードを読めるので難しいことはなかった。
StudyCrypto.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
showStatusBar="false"
width="320" height="300"
styleName="study"
borderThickness="1">
<mx:Style>
.study {
paddingBottom: 3;
paddingLeft: 3;
paddingRight: 3;
paddingTop: 3;
}
</mx:Style>
<mx:Script>
<![CDATA[
import com.hurlant.crypto.Crypto;
import com.hurlant.crypto.symmetric.ICipher;
import com.hurlant.crypto.symmetric.IPad;
import com.hurlant.crypto.symmetric.IVMode;
import com.hurlant.crypto.symmetric.PKCS5;
import com.hurlant.util.Base64;
import com.hurlant.util.Hex;

public static function encrypt(name:String, k:String, s:String):ByteArray {
var e:ByteArray = new ByteArray();
var key:ByteArray = Hex.toArray(Hex.fromString(k));
var data:ByteArray = Hex.toArray(Hex.fromString(s));
var pad:IPad = new PKCS5();
var cipher:ICipher = Crypto.getCipher(name, key, pad);
pad.setBlockSize(cipher.getBlockSize());
cipher.encrypt(data);
e.writeObject(data);
if(cipher is IVMode){
var ivmode:IVMode = cipher as IVMode;
e.writeObject(ivmode.IV);
}
e.position = 0;
return e;
}

public static function decrypt(name:String, k:String, e:ByteArray):String {
var data:ByteArray = e.readObject();
var kdata:ByteArray = Hex.toArray(Hex.fromString(k));
var pad:IPad = new PKCS5();
var cipher:ICipher = Crypto.getCipher(name, kdata, pad);
if(cipher is IVMode){
var ivmode:IVMode = cipher as IVMode;
ivmode.IV = e.readObject();
}
cipher.decrypt(data);
return Hex.toString(Hex.fromArray(data));
}

private function run():void {
const name:String = 'aes-cbc';
var e:ByteArray = encrypt(name, key.text, src.text);
o0.text = Base64.encode(Hex.fromArray(e));
o1.text = decrypt(name, key.text, Hex.toArray(Base64.decode(o0.text)));
}
]]>
</mx:Script>
<mx:Form styleName="study" width="100%" cornerRadius="6" borderColor="#218BD5" borderStyle="solid">
<mx:FormItem label="Password" width="100%">
<mx:TextInput width="100%" id="key" change="btn.enabled = (4 &lt;= key.text.length)"/>
</mx:FormItem>
<mx:FormItem label="Input" width="100%">
<mx:TextInput width="100%" id="src"/>
</mx:FormItem>
<mx:FormItem width="100%">
<mx:Button id="btn" label="run" click="run()" enabled="false"/>
</mx:FormItem>
</mx:Form>
<mx:Form styleName="study" width="100%" height="100%" cornerRadius="6" borderColor="#218BD5" borderStyle="solid">
<mx:FormItem label="Encrypt" width="100%" height="100%">
<mx:TextArea width="100%" height="100%" id="o0"/>
</mx:FormItem>
<mx:FormItem label="Decrypt" width="100%" height="100%">
<mx:TextArea width="100%" height="100%" id="o1"/>
</mx:FormItem>
</mx:Form>
</mx:WindowedApplication>

0 件のコメント:

コメントを投稿