在nodejs中解密.Net cookie
我在.Net中创build了一个encryption的cookie,我试图在nodejs中解密它的内容。 但是nodejs总是抛出exception“TypeError:DecipherFinal fail”
在.NET中,我使用AESencryption方法
932D86BB1448EEAA423F38495A2290746D81C27E55D1DC264279537006D6F4CC.
我的web.config文件有以下行
<machineKey validationKey="A5326FFC9D3B74527AECE124D0B7BE5D85D58AFB12AAB3D76319B27EE57608A5A7BCAB5E34C7F1305ECE5AC78DB1FFEC0A9435C316884AB4C83D2008B533CFD9" decryptionKey="932D86BB1448EEAA423F38495A2290746D81C27E55D1DC264279537006D6F4CC" validation="SHA1" decryption="AES" />
在.Net中生成我的cookie的代码如下所示:
var ticket = new FormsAuthenticationTicket(0, "test", DateTime.Now, DateTime.Now.AddYears(1), true, "test"); var encryptedTicket = FormsAuthentication.Encrypt(ticket); Response.Cookies.Add(new HttpCookie(cookieName, encryptedTicket));
解密cookie的nodejs代码是
var crypto = require('crypto'); var logger = require('winston'); var deckey = "932D86BB1448EEAA423F38495A2290746D81C27E55D1DC264279537006D6F4CC"; function hex2a(hex) { var str = ''; for (var i = 0; i < hex.length; i += 2) str += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); return str; } function decrypt(cookie) { var ivc = cookie, iv, cipherText, ivSize = 16, res; ivc = new Buffer(ivc, 'hex'); iv = new Buffer(ivSize); cipherText = new Buffer(ivc.length - ivSize); ivc.copy(iv, 0, 0, ivSize); ivc.copy(cipherText, 0, ivSize); iv = new Buffer(Array(16)); c = crypto.createDecipheriv('aes-256-cbc', hex2a(deckey), iv.toString()); res = c.update(cipherText, 'binary'); res += c.final('binary'); //<-- throws TypeError: DecipherFinal fail return res; }
我有点失落,我会感谢提示或想法是什么可能是问题。
您可以在这里看到Encryp和Decrypt的源代码以及所有不同的可能性(Framework20SP1,Framework20SP2等)
https://github.com/Microsoft/referencesource/blob/master/System.Web/Security/FormsAuthentication.cs
我花了几个小时来阅读这些代码,但是一旦得到它,就可以为你的特定encryption设置编写一个简单的代码。
一个关键不是一个string,看一下来自fromCharCode()
的方法:
fromCharCode()
方法将Unicode值转换为字符。
这意味着任何hex转换为文本字符,而createDecipheriv()
方法指定:
key和iv必须是“二进制”编码的string或缓冲区。
请注意,这只是可能出现的问题之一,我还没有时间来运行代码(还)。
你的问题可能是自动填充失败,默认打开。 你想要closures它,通过添加:
c.setAutoPadding(false);