Resumé

AES-Rijndael con ActionScript e ASP.Net

Cristian Merighi () 4,86

Come passare dati criptati in tutta sicurezza tra un oggetto Flash e un applicativo server side sviluppato in tecnologia .Net utilizzando l'algoritmo Rijndael/AES.
Questo articolo è da considerarsi obsoleto. Alcune funzionalità potrebbero non essere più disponibili e non è possibile aggiungere commenti.

In questi giorni sto lavorando ad un concorso online consistente in un gioco flash custom che ha il compito di coinvolgere gli utenti del web in modo da poterne stilare una classifica (in termini di punteggio ottenuto al gioco).
I 10 top scorers riceveranno un gran bel premio una volta terminato il concorso...

Nulla da dire sul fatto che la caratteristica più richiesta al concorso è stata quella della sicurezza! (Sì, lo so che non è una novità e che anzi è basilare, sta di fatto che stavolta più di altre volte l'accento è stato marcato visto il montepremi...)

Il punto cruciale di debolezza per l'applicativo è il passaggio di dati tra il gioco in flash (client side) e lo strato di logica dell'applicativo (server side).
Abbiamo voluto evitare che navigatori maliziosi potessero sniffare, postare, forzare dati in modo da falsare la classifica.

Per fare ciò ci siamo affidati alla crittazione dei dati!

Sappiamo bene che impossibile impedire a un utente di visualizzarsi i propri pacchetti http, solo ci accontentiamo che non li possa leggere in modo da poter poi riprodurre post falsati.
Il .Net Framework di suo è piuttosto ricco quanto ad API per la crittazione (e per le versioni future è previsto un ulteriore ampliamento delle librerie, date un occhio a cosa è compreso nella prossima CTP di Orcas), l'ActionScript invece difetta di questo tipo di classi...
Grazie al lavoro di Mika Palmu, che ha messo insieme un package davvero utile di classi ActionScript 2.0 focalizzate sulla crittografazione, possiamo affrontare la missione con relativa tranquillità...

Di seguito un esempio funzionante dell'operatività richiesta:

Di seguito il nucleo di codice ActionScript utilizzato per la crittazione...

var aesMode:String = "ECB";
var aesKey:String = "01230123012390129012901A"; // equal key server side
var aes:it.pacem.Rijndael = new it.pacem.Rijndael(192, 128);
cipher_txt.text = aes.encrypt(plain_txt.text, aesKey, aesMode);

...e quello C# utilizzato, lato server, per la decrittazione:

MemoryStream msDecrypt = null;
CryptoStream csDecrypt = null;
StreamReader srDecrypt = null;

System.Security.Cryptography.RijndaelManaged aesAlg = null;

string plaintext = null;

try
{
    // Create a RijndaelManaged object
    // with the specified key (IV parameter is obmitted because of ECB CipherMode).
    aesAlg = new System.Security.Cryptography.RijndaelManaged();
    aesAlg.Key = "01230123012390129012901A";
    aesAlg.Mode = CipherMode.ECB;
    // set PaddingMode.Zeros in order to use the same padding mode as in flash actionscript class
    aesAlg.Padding = PaddingMode.Zeros;

    // Create a decrytor to perform the stream transform.
    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

    // Create the streams used for decryption.
    msDecrypt = new MemoryStream(cipherText);
    csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
    srDecrypt = new StreamReader(csDecrypt);

    // Read the decrypted bytes from the decrypting stream
    // and place them in a string.
    plaintext = srDecrypt.ReadToEnd();
}
finally
{
    // Clean things up.
    // Close the streams.
    if (srDecrypt != null)
        srDecrypt.Close();
    if (csDecrypt != null)
        csDecrypt.Close();
    if (msDecrypt != null)
        msDecrypt.Close();

    // Clear the RijndaelManaged object.
    if (aesAlg != null)
        aesAlg.Clear();
}

Per maggiori specifiche sull'algoritmo Rijndael/AES, rimandiamo al documento ufficiale sullo standard AES (FIPS PUB 197) e alla documentazione MSDN sulla classe System.Security.Cryptography.RijndaelManaged.

pdf file « download AES Standard (FIPS PUB 197) in PDF format
zip file « download code

Take care. Bye.

Feedbacks

  • Re: AES-Rijndael with ActionScript and ASP.Net

    zuppaman sabato 10 marzo 2007 5,00

    Thx for this very nice sample !

  • Re: AES-Rijndael with ActionScript and ASP.Net

    CMerighi sabato 10 marzo 2007 0,00

    You're welcome, Zuppaman. Glad to see that you appreciate it...

  • Re: AES-Rijndael with ActionScript and ASP.Net

    Kees martedì 13 marzo 2007 0,00

    Great example! thanks

  • Re: AES-Rijndael with ActionScript and ASP.Net

    jake martedì 4 marzo 2008 4,00

    hi, i am a student from Singapore. i am currently working on a sch project that involves flash lite application which need to use AES encryption. but after looking at your example, i am still pretty much confused. basically i have a AES Key - 16byte, and a string of data. how do i go about doing the encryption? can you advise?

  • Re: AES-Rijndael with ActionScript and ASP.Net

    CMerighi mercoledì 5 marzo 2008 0,00

    Hi Jake, I guess the downloadable example is pretty straightforward, you can anyway send your perplexities to my email address: cristian(at)pacem(dot)it. I'll try - I'll be out til next week - to answer as soon as possible.

  • Re: AES-Rijndael with ActionScript and ASP.Net

    xenonii sabato 15 marzo 2008 0,00

    If you put the key in the SWF, it is still unsecure i think, since they can decompile the SWF and read the key. Is there a solution for this?

  • Re: AES-Rijndael with ActionScript and ASP.Net

    CMerighi sabato 15 marzo 2008 0,00

    You're right Xenonii and this is a good question, clientside stuff is always risky. In the specific case mentioned at the beginning of this article, I've been flushing to the client several different swf's binaries, with different embedded keys (using ashx file). Each single user never faced the same swf more than once. That way even an hyper-malicious user couldn't repeat the same request to the server twice, the swf itself wasn't cached in the temporary internet files storage and hence unretrievable. The encryption was only one of the expedients used in that scenario.

  • Re: AES-Rijndael with ActionScript and ASP.Net

    Shiv domenica 16 marzo 2008 0,00

    Ok, So I use this code but when decrypting on the server side, I get junk. I've used the cipher text that your client produces on this page as well as one I've made in Flex Builder 3 using the code you show. Chritian, This is exactly what I'm looking for. An ActionScript and C# example. Thank you! However, I'm not able to get this to work on the C# end. I use the cipher text the client on this page produces. I take that cipher text and use it in the C3 code you've shown. The result of junk. I've build my own client in FlexBuilder 3. The cipher text it produces (using the same key) is different from what your client produces. Attempting to decrypt this cipher text using the C3 code you're provided again results in junk. Note: The C# code you show in this page is not compilable. The Key property is a byte[] so I use Encoding.Utf8.GetBytes() to convery the string key to a byte[]. I do the same for the cipher text (Which also need to be a byte[]. Even though I use the same key you have here. My cipher text is different from the one your client produces.

  • Re: AES-Rijndael with ActionScript and ASP.Net

    CMerighi lunedì 17 marzo 2008 0,00

    Hi Shiv, did you take a look to the code provided at the bottom of the article? There you'll find the fully working bunch of files used for the example above (C# .ashx + .fla + .as). Of course the extract of C# code printed on the page won't compile: it's just an extract. Take a look at the full code inside the .ashx file. There you'll see I've been using Ascii encoding to translate the cipher text (coming from the flash request) into cipher byte[], then I passed it all to a RijndaelManaged instance. Bye!

  • Re: AES-Rijndael with ActionScript and ASP.Net

    Terry lunedì 23 giugno 2008 0,00

    Cristian, Thanks for posting this article - it was a big help in a current project. I did run into one strange problem, though, which also appears in your sample code: when calling decryptStringFromBytes_AES()to decrypt the string sent from Flash, the decrypted string contains a bunch of null characters appended to it. The workaround I used is to strip them out in a while loop before storing them in a database.

  • Re: AES-Rijndael with ActionScript and ASP.Net

    Andrzej P. mercoledì 13 agosto 2008 5,00

    Great example !

  • Re: AES-Rijndael with ActionScript and ASP.Net

    Selim martedì 23 settembre 2008 5,00

    I like your script. I want to use it but i have a problem. I convert it to vb.net. It works correctly.But at the .aspx page variable always return with a few white spaces(blanks) at the end. Like this: "test ". So i couldnt equal it some other variable. I try everything i know(RTrim, replace, Cstr). But i couldnt remove those white spaces from code. Any idea??

  • Re: AES-Rijndael with ActionScript and ASP.Net

    CMerighi mercoledì 24 settembre 2008 0,00

    Hi Selim, it's an intrinsic issue that relies upon the <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.paddingmode.aspx" target="_blank">PaddingMode</a> that's been used. See the post from Terry (few lines above)...

  • Re: AES-Rijndael with ActionScript and ASP.Net

    Rao lunedì 20 ottobre 2008 5,00

    Great example. ThanX

  • Re: AES-Rijndael with ActionScript and ASP.Net

    John venerdì 31 ottobre 2008 5,00

    Thanks for this example, I'm wondering how would I encrypt the data going from aps.net to actionscript.

  • Re: AES-Rijndael with ActionScript and ASP.Net

    John venerdì 31 ottobre 2008 5,00

    Actually I fixed my problem, I wasn't setting the padding or the CipherMode. Caused all sorts of crazy errors.

  • Re: AES-Rijndael with ActionScript and ASP.Net

    Parag martedì 4 novembre 2008 5,00

    Good example... I had searching on net for a similar code.

  • Re: AES-Rijndael with ActionScript and ASP.Net

    Keith mercoledì 19 novembre 2008 4,00

    Hi, I'm trying to encrypt a string in the flash which contains spanish characters such as áéí. When I decrypt it in the aspx, those characters appear as funny characters. I believe this is caused by the fact that Rijndael.as is using ASCII encoding, how can this be changed to use UTF-8 encoding? Thanks!

  • Re: AES-Rijndael with ActionScript and ASP.Net

    matute martedì 17 febbraio 2009 0,00

    'bout the whitespaces issue, try replacing the "\0" with "". str.replace("\0","") it's quite easier (and faster) than using a loop cheers

  • Re: AES-Rijndael with ActionScript and ASP.Net

    Gerry sabato 21 febbraio 2009 5,00

    How would you do the reverse, please provide sample code of encypting text on the server and decypt in flash file. Thanks. Get sample just does not cover both senorio's

  • Re: AES-Rijndael with ActionScript and ASP.Net

    Enrique venerdì 6 marzo 2009 5,00

    Thank You Very Much, it was very useful...

  • Re: AES-Rijndael with ActionScript and ASP.Net

    CuneyQ mercoledì 18 marzo 2009 5,00

    it was ver useful, thank you. is there c# codes for encrypt ?!?

  • Re: AES-Rijndael with ActionScript and ASP.Net

    Navagon lunedì 30 marzo 2009 0,00

    Great work. Regarding the key imbedding, I would use a an asymmetric (public/private) key pair. Embed the public key and keep the private on the server. This will ensure the message can only be decrypted at the server

  • Re: AES-Rijndael with ActionScript and ASP.Net

    Mike giovedì 30 luglio 2009 0,00

    Hello, that's a great example thank you. But I have a problem to use this source code with this php classes. The result is just good with only 16 characters. I really don't know why... http://www.phpclasses.org/browse/package/4238.html Someone can help ?

  • Re: AES-Rijndael with ActionScript and ASP.Net

    Alex Kleshchevnikov martedì 22 settembre 2009 0,00

    Is there an example of encrypt in C# and decrypt in actionscript?

  • Re: AES-Rijndael with ActionScript and ASP.Net

    yil mercoledì 9 dicembre 2009 0,00

    great topic tanks alot

  • Re: AES-Rijndael with ActionScript and ASP.Net

    Hi all giovedì 17 dicembre 2009 0,00

    anyone can help me decrypt it on PHP code. thanks.

  • can not encrypt chinese word.

    Malcom lunedì 18 gennaio 2010 5,00

    Hi, If I encrypt a chinese word(two bytes) and decrypt it. I got different result. Can it resolve ? Thanks.

  • Re: AES-Rijndael with ActionScript and ASP.Net

    Josh venerdì 2 luglio 2010 5,00

    I got this working great... but there are a few issues 1) Every decrypted message has "0\0\0\0\0\0\" on the end 2) It mistakes " for 3) It also incorrectly decrypts \ as \ Any clue on how to fix?

feedback
 

Syndicate

Autore

Cristian Merighi facebook twitter google+ youtube

Ultimi articoli

Top rated

Archivio

Dove sono?

Autore

Cristian Merighi facebook twitter google+ youtube

Le mie letture

Feeds