2014-11-08 170 views
0

即时尝试在c#中封装一个有效载荷。
我有Javascript中的代码,并试图在C#中创建相同的加密,很难重新创建相同的加密。创建像cryptoJS C#256位AES加密

给出javascript代码(不能修改):

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) 

我想创建在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)); 

我这里有几个问题,在JS你可以指定加密格式,然后使用JSON.parse。它看起来不能在c#中完成。
我使用了http://www.codeproject.com/Articles/769741/Csharp-AES-bits-Encryption-Library-with-Salt的方法。
有无论如何,我可以在C#中创建相同的代码片段?

谢谢!

+0

即从CodeProject C#代码使用PBKDF2来导出密钥和IV。所以你也需要在CryptoJS中使用PBKDF2。 CryptoJS默认使用OpenSSL来派生密钥和IV(请参阅[this](http://crypto.stackexchange.com/questions/19739/does-googles-crypto-js-aes-encryption-use-pbkdf2-as-default)后)。 – Dmitry 2014-11-08 16:48:03

+0

@Dmitry javascript代码给出我不能改变它,我需要在c#中创建相同的代码片段 – 2014-11-08 17:36:28

回答

2

该帖子中的代码:openssl using only .NET classes与CryptoJS AES兼容。

测试:

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"