常见的加密/解密代码示例C#和Node.js的/密码 [英] Common encrypt/decrypt code example for C# and Node.js/crypto

查看:189
本文介绍了常见的加密/解密代码示例C#和Node.js的/密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用应用程序请求路由(ARR)在IIS中传递一组路径到Node.js的网站。我的问题是能够获取/设置在两侧的身份验证票证。



我真的很需要一个加密/解密对一个简单的例子,将C#和工作Node.js的接近开箱与两个相同的结果。我会在这个问题上合作作为自己时间允许,在未来的几天里,并打算回答,如果没有人来了我以前的答案。



我的本意是到节点侧写作为Node.js的侧连接/ Express模块​​。我已经在ASP.Net解决方案做一个自定义身份验证,并可以很容易的东西,可以从两个平台安全(只要它们共享相同的密钥)取代我现在的方法。






当前的代码来创建 AccountController.cs


$身份验证cookie b $ b

 私人无效ProcessUserLogin(MyEntityModel分贝,SiteUser用户,布尔记得= FALSE)
{
变种角色=的string.join(|,值:。user.SiteRoles.Select(SR => sr.Name.ToLowerInvariant()修剪())是不同的()ToArray的());

//更新laston结果
user.UserAgent = Request.UserAgent;
user.LastOn = DateTimeOffset.UtcNow;
db.SaveChanges();

//创建并弄走饼干
变种authTicket =新的FormsAuthenticationTicket(
1
,user.Username
,DateTime.Now $ B $ ?b,DateTime.Now.AddDays(31)//最大31天
,记得
,string.IsNullOrWhiteSpace(角色)客人:角色
);
VAR票= FormsAuthentication.Encrypt(authTicket);
变种的cookie =新的HttpCookie(FormsAuthentication.FormsCookieName,门票);
如果(记住)cookie.Expires = DateTime.Now.AddDays(8);
Response.Cookies.Add(饼干);
}






当前代码读取身份验证cookie 的Global.asax.cs

 无效Application_AuthenticateRequest(对象发件人,EventArgs参数) 
{
的HttpCookie authCookie = Context.Request.Cookies [FormsAuthentication.FormsCookieName]
如果(authCookie == NULL)回报;

的FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

的String [] =角色authTicket.UserData.Split(新的char [] {'|'});

//创建新的通用标识,以及相应的本金...
变种G =新的GenericIdentity(authTicket.Name);
变种多达=新的GenericPrincipal(G,角色);对于当前请求和线程(应用程序将处理来自这里转换)

//设置的主要
= Thread.CurrentPrincipal中= Context.User起来;
}






的Web.config

 <?XML版本=1.0编码=utf-8 >?; 
<结构>
<&的System.Web GT;
<会员和GT;
<供应商>
<! - 删除默认提供者,所以自定义覆盖工程 - >
<清/>
< /供应商>
< /会员>
< /system.web>
< /结构>


解决方案

下面是一个使用作品的例子DES算法。 参考

 使用系统; 
使用System.Text;
使用System.Security.Cryptography;

公共类测试
{
公共静态字符串加密(字符串toEncrypt,串键,布尔useHashing)
{
字节[] keyArray;
字节[] = toEncryptArray UTF8Encoding.UTF8.GetBytes(toEncrypt);

如果(useHashing)
{
MD5CryptoServiceProvider hashmd5 =新MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(键));
}
,否则
keyArray = UTF8Encoding.UTF8.GetBytes(键);

变种TDES =新TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
// tdes.Mode = CipherMode.CBC; //这是默认的
// tdes.Padding = PaddingMode.PKCS7; //这是默认的

Console.WriteLine(四:{0},Convert.ToBase64String(tdes.IV));

ICryptoTransform的cTransform = tdes.CreateEncryptor();
字节[] = resultArray cTransform.TransformFinalBlock(toEncryptArray,0,
toEncryptArray.Length);
返回Convert.ToBase64String(resultArray,0,resultArray.Length);
}

公共静态无效的主要()
{
Console.WriteLine(加密为:{0},加密(12345,abcdefghijklmnop ,FALSE));
}
}



它输出



 四:pdMBMjdeFdo = $ b加密为$ b:3uDkdT6aQ3c = 

和使用正确的算法 DES-EDE-CBC 在Node.js的:

  VAR密码=要求('密码'); 

变种ALG ='DES-EDE-CBC';

VAR键=新的缓冲区('abcdefghijklmnop','utf-8');
变种IV =新的缓冲区('pdMBMjdeFdo =','的base64');

变种加密=新的缓冲区('3uDkdT6aQ3c =','的base64');
无功源=12345;

VAR密码= crypto.createCipheriv(ALG,钥匙,IV);
变种编码= cipher.update(来源:ASCII,BASE64');
编码+ = cipher.final('的base64');

的console.log(编码,encrypted.toString('的base64'));

VAR译码= crypto.createDecipheriv(ALG,钥匙,IV);
VAR解码= decipher.update(加密,'二进制','ASCII码');
解码+ = decipher.final('ASCII码');

的console.log(解码,源);



它输出



  3uDkdT6aQ3c = 3uDkdT6aQ3c = 
12345 12345


I'm attempting to use Application Request Routing (ARR) in IIS for passing a set of paths to a Node.js website. My issue is being able to get/set the authentication ticket on either side.

I just really need a simple example of an Encrypt/Decrypt pair that will work for C# and Node.js close to out of the box with the same results for both. I'll be working on this problem myself as time permits over the next few days, and intend to answer if nobody comes up with an answer before me.

My intention is to write the node side as a connect/express module on the Node.js side. I am already doing a custom authentication in the ASP.Net solution, and can easily replace my current method with something that can be secure from both platforms (so long as they share the same key).


Current code to create the authentication cookie in AccountController.cs

private void ProcessUserLogin(MyEntityModel db, SiteUser user, bool remember=false)
{
  var roles = String.Join("|", value:user.SiteRoles.Select(sr => sr.Name.ToLowerInvariant().Trim()).Distinct().ToArray());

  //update the laston record(s)
  user.UserAgent = Request.UserAgent;
  user.LastOn = DateTimeOffset.UtcNow;
  db.SaveChanges();

  // Create and tuck away the cookie
  var authTicket = new FormsAuthenticationTicket(
    1
    ,user.Username
    ,DateTime.Now
    ,DateTime.Now.AddDays(31) //max 31 days
    ,remember
    ,string.IsNullOrWhiteSpace(roles) ? "guest" : roles
  );
  var ticket = FormsAuthentication.Encrypt(authTicket);
  var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticket);
  if (remember) cookie.Expires = DateTime.Now.AddDays(8);
  Response.Cookies.Add(cookie);
}


Current code to read the authentication cookie in Global.asax.cs

void Application_AuthenticateRequest(object sender, EventArgs args)
{
  HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
  if (authCookie == null) return;

  FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

  string[] roles = authTicket.UserData.Split(new Char[] { '|' });

  //create new generic identity, and corresponding principal...
  var g = new GenericIdentity(authTicket.Name);
  var up = new GenericPrincipal(g, roles);

  //set principal for current request & thread (app will handle transitions from here)
  Thread.CurrentPrincipal = Context.User = up;
}


Relevant portion of the Web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <membership>
      <providers>
        <!-- Remove default provider(s), so custom override works -->
        <clear />
      </providers>
    </membership>
  </system.web>
</configuration>

解决方案

Here is a work example using DES algorithm. reference

using System;
using System.Text;
using System.Security.Cryptography;

public class Test
{
    public static string Encrypt(string toEncrypt, string key, bool useHashing) 
    {     
        byte[] keyArray;     
        byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);      

        if (useHashing)     
        {         
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));     
        }     
        else
            keyArray = UTF8Encoding.UTF8.GetBytes(key);      

        var tdes = new TripleDESCryptoServiceProvider();
        tdes.Key = keyArray;     
        // tdes.Mode = CipherMode.CBC;  // which is default     
        // tdes.Padding = PaddingMode.PKCS7;  // which is default

        Console.WriteLine("iv: {0}", Convert.ToBase64String(tdes.IV));

        ICryptoTransform cTransform = tdes.CreateEncryptor();     
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0,
            toEncryptArray.Length);      
        return Convert.ToBase64String(resultArray, 0, resultArray.Length); 
    }  

    public static void Main()
    {
        Console.WriteLine("encrypted as: {0}", Encrypt("12345", "abcdefghijklmnop", false));
    }
}

which outputs

iv: pdMBMjdeFdo=
encrypted as: 3uDkdT6aQ3c=

And use the right algorithm des-ede-cbc in node.js:

var crypto = require('crypto');

var alg = 'des-ede-cbc';

var key = new Buffer('abcdefghijklmnop', 'utf-8');
var iv = new Buffer('pdMBMjdeFdo=', 'base64');

var encrypted = new Buffer('3uDkdT6aQ3c=', 'base64');
var source = '12345';

var cipher = crypto.createCipheriv(alg, key, iv);
var encoded = cipher.update(source, 'ascii', 'base64');
encoded += cipher.final('base64');

console.log(encoded, encrypted.toString('base64'));

var decipher = crypto.createDecipheriv(alg, key, iv);
var decoded = decipher.update(encrypted, 'binary', 'ascii');
decoded += decipher.final('ascii');

console.log(decoded, source);

which outputs

3uDkdT6aQ3c= 3uDkdT6aQ3c=
12345 12345

这篇关于常见的加密/解密代码示例C#和Node.js的/密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆