问题
I need to encrypt some files in ASP.net and decrypt them in a flash application built with Action Script 3.
AS3 developer found a lib call AS3crypto which seems like a good one for AS3. The idea is encrypt and decrypt using same key. Symmetrical Encryption?
But I am struggling to find .Net equivalent that would use same algorithm for encryption.
I have tried RC4 example from 4guysfromrolla blog which works too slow for me. I have tried AES on this example (http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged(v=vs.100).aspx) which works great on .Net but I can't seem to decrypt using AS3crypto to get the same file back. AS3crypto doesn't seem to like to have IV for decryption. I can only supply one key.
So far I am lost. How can I encrypt a file in .Net and decrypt it back in AS3 to get the same file back?
回答1:
Notice: use 16 char length for both Key and IV, ex: Key: 1234567890123456 and IV: 9876543210654321
Here is C# code
public byte[] Encrypt(byte[] someData, string KEY, string IV)
{
//preparing
byte[] keyBytes = Encoding.UTF8.GetBytes(KEY);
byte[] ivBytes = Encoding.UTF8.GetBytes(IV);
//here goes encryption
RijndaelManaged rijndaelManaged = new RijndaelManaged();
rijndaelManaged.Key = keyBytes;
rijndaelManaged.IV = ivBytes;
rijndaelManaged.BlockSize = 128;
rijndaelManaged.Mode = CipherMode.CBC;
ICryptoTransform encryptor = rijndaelManaged.CreateEncryptor(rijndaelManaged.Key, rijndaelManaged.IV);
byte[] result = null;
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(someData, 0, someData.Length);
cryptoStream.FlushFinalBlock();
result = memoryStream.ToArray();
}
}
return result;
}
And here is AS3 code using AS3Crypto library
private function decrypt(input:ByteArray, decrKey:String, decrIV:String):ByteArray
{
var key:ByteArray = Hex.toArray(Hex.fromString(decrKey));
var pad:IPad = new NullPad();
var aes:ICipher = Crypto.getCipher("aes-cbc", key, pad);
var ivmode:IVMode = aes as IVMode;
ivmode.IV = Hex.toArray(Hex.fromString(decrIV));
aes.decrypt(input);
return input;
}
来源:https://stackoverflow.com/questions/17276371/encrypt-in-net-and-decrypt-in-as3