I'm trying to get as3crypto to play nice with either Gibberish or EzCrypto in AES-128 mode. No matter what combination of settings I use I simply cannot get one 开发者_JAVA百科to decrypt the other, and usually get a "bad decrypt" message in ruby. Each contained environment can decrypt data it encrypted itself but one cannot seem to decrypt the other. Has anyone been able to get the two to work together?
Here's one of the variations I tried:
On the Actionscript side, using as3crypto:
//define the encryption key
var key:ByteArray = Hex.toArray("password");
//put plaintext into a bytearray
var plainText:ByteArray = Hex.toArray(Hex.fromString("this is a secret!"));
//set the encryption key
var aes:AESKey = new AESKey(key);
//encrypt the text
aes.encrypt( plainText );
trace(Base64.encode(Hex.fromArray(plainText)));
//encrypted value is N2QwZmI0YWQ4NzhmNDNhYjYzM2QxMTAwNGYzNDI1ZGUyMQ==
And on the ruby side, using gibberish:
// also tried the default size (256)
cipher = Gibberish::AES.new("password",128)
// raises the following exception: OpenSSL::Cipher::CipherError: wrong final block length
cipher.dec("N2QwZmI0YWQ4NzhmNDNhYjYzM2QxMTAwNGYzNDI1ZGUyMQ==")
I've tried all sort of different approaches, all yielding either the above exception or "bad encrypt"
Finally figured it out myself. The thing is both Gibberish and EzCrypto do not seem to provide a way to specify an IV, which is needed when using aes-cbc. The trick is to extract the iv from the first 16 bytes of the encrypted data as3crypto produces.
Here's the as3 code, which also changed a little:
// there are other ways to create the key, but this works well
var key:ByteArray = new ByteArray();
key.writeUTFBytes(MD5.encrypt("password"));
// encrypt the data. simple-aes-cbc is equiv. to aes-256-cbc in openssl/ruby, if your key is
// long enough (an MD5 is 32 bytes long)
var data:ByteArray = Hex.toArray(Hex.fromString("secret"));
var mode:ICipher= Crypto.getCipher("simple-aes-cbc", key) ;
mode.encrypt(data);
// the value here is base64, 32 bytes long. the first 16 bytes are the IV, needed to decrypt
// the data in ruby
// e.g: sEFOIF57LVGC+HMEI9EMTpcJdcu4J3qJm0PDdHE/OSY=
trace(Base64.encodeByteArray(data));
The ruby part uses a gem called encryptor to supply the iv. you can also use OpenSSL directly, it's pretty straight forward:
key = Digest::MD5.hexdigest("password")
// decode the base64 encoded data back to binary:
encrypted_data = Base64.decode64("sEFOIF57LVGC+HMEI9EMTpcJdcu4J3qJm0PDdHE/OSY=")
// the tricky part: extract the IV from the decoded data
iv = encrypted_data.slice!(0,16)
// decrypt!
Encryptor.decrypt(encrypted_data,:key=>key,:iv=>iv)
// should output "secret"
精彩评论