0

im trying to encrpyt a payload in c#.
i have the code in Javascript and im trying to create same encryption in C#, having hard time to recreate the same encryption.

given javascript code (cannot be changed):

var data = 
    {
        'username':username,
        'password':password,
        'isPersistent':'false'
    };
var encrypted = CryptoJS.AES.encrypt(JSON.stringify(data),token,  { format: JsonFormatter });

    var body = {
        payload: JSON.parse(encrypted.toString()),
        token: token
    }
    debugger
    $.post(url, body).success(resultFunction)

i want to create the same encryption in c#

Dictionary<string, string> data = new Dictionary<string, string>();
data.Add("username", username);
data.Add("password", password);
data.Add("isPersistent", "false");
string token = "7e4bac048ef766e83f0ec8c079e1f90c2eb690a9";
string serializedData = json_serialize(data);
string encrypted = EncryptText(serializedData, token);
Dictionary<string, string> body = new Dictionary<string, string>();
body.Add("payload", json_deserialize(encrypted));
body.Add("token", token);
var loginWebRequest = createWebRequest(address, "POST", json_serialize(body));   

i have several issue here, in js you can specify the format of encryption and then use JSON.parse. it seems it cannot be done in c#.
i used the methods from http://www.codeproject.com/Articles/769741/Csharp-AES-bits-Encryption-Library-with-Salt.
is there anyway i can create the same code snippet in c#?

Thanks!

avi.tavdi
  • 305
  • 2
  • 4
  • 17
  • That C# code from codeproject uses PBKDF2 to derive the key and the IV. So you need to use PBKDF2 in CryptoJS too. CryptoJS uses OpenSSL to derive keys and IVs by default (see [this](http://crypto.stackexchange.com/questions/19739/does-googles-crypto-js-aes-encryption-use-pbkdf2-as-default) post). – Dmitry Nov 08 '14 at 16:48
  • @Dmitry The javascript code is given i cannot change it, i need to create the same code snippet in c# – avi.tavdi Nov 08 '14 at 17:36

1 Answers1

3

The code from this post: openssl using only .NET classes is compatible with CryptoJS AES.

Test:

JS:

var encrypted = CryptoJS.AES.encrypt("abc12345","7e4bac048ef766e83f0ec8c079e1f90c2eb690a9");
encrypted.toString(); //output: "U2FsdGVkX18eGD2hSe9UyGgTk5NGKFmvWq/3c5IYHoQ="

C#:

 var p = new Protection();
 var s = p.OpenSSLDecrypt("U2FsdGVkX18eGD2hSe9UyGgTk5NGKFmvWq/3c5IYHoQ=", "7e4bac048ef766e83f0ec8c079e1f90c2eb690a9");
 Console.WriteLine(s);//output: "abc12345"
Community
  • 1
  • 1
Dmitry
  • 6,716
  • 14
  • 37
  • 39