首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >让as3crypto与ruby一起工作(胡言乱语/EzCrypto)

让as3crypto与ruby一起工作(胡言乱语/EzCrypto)
EN

Stack Overflow用户
提问于 2011-06-27 18:02:35
回答 1查看 1.6K关注 0票数 0

我正在尝试让as3crypto在AES-128模式下使用胡言乱语或EzCrypto。无论我使用哪种设置组合,我都无法让其中一种设置解密另一种设置,并且通常会在ruby中得到“糟糕的解密”消息。每个包含的环境都可以解密它自己加密的数据,但一个似乎不能解密另一个。有没有人能让这两者一起工作呢?

下面是我尝试过的一个变体:

在ActionScript端,使用as3crypto:

代码语言:javascript
复制
//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==

在红宝石方面,使用胡言乱语:

代码语言:javascript
复制
// 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==")

我尝试了所有不同的方法,都产生了上面的异常或“糟糕的加密”

EN

回答 1

Stack Overflow用户

发布于 2011-06-28 22:19:12

我自己终于想明白了。问题是两者都是胡言乱语,EzCrypto似乎没有提供一种方法来指定IV,这是使用aes-cbc时所需的。诀窍是从as3crypto产生的加密数据的前16个字节中提取iv。

下面是as3代码,也做了一些改动:

代码语言:javascript
复制
// 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));

ruby部分使用一个名为encryptor的gem来提供iv。你也可以直接使用OpenSSL,它非常简单:

代码语言:javascript
复制
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"
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6491267

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档