一、标识和Principal

 static void Main(string[] args)
{
AppDomain.CurrentDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal);
var principal = WindowsPrincipal.Current as WindowsPrincipal;
var identity = principal.Identity as WindowsIdentity; Console.WriteLine("IdentityType: {0}", identity.ToString());
Console.WriteLine("Name: {0}", identity.Name);
Console.WriteLine("‘Users’?: {0}", principal.IsInRole(WindowsBuiltInRole.User));
Console.WriteLine("‘Administrators’? {0}", principal.IsInRole(WindowsBuiltInRole.Administrator));
Console.WriteLine("Authenticated: {0}", identity.IsAuthenticated);
Console.WriteLine("AuthType: {0}", identity.AuthenticationType);
Console.WriteLine("Anonymous? {0}", identity.IsAnonymous);
Console.WriteLine("Token: {0}", identity.Token); Console.WriteLine();
Console.WriteLine("Claims");
foreach (var claim in principal.Claims)
{
Console.WriteLine("Subject: {0}", claim.Subject);
Console.WriteLine("Issuer: {0}", claim.Issuer);
Console.WriteLine("Type: {0}", claim.Type);
Console.WriteLine("Value type: {0}", claim.ValueType);
Console.WriteLine("Value: {0}", claim.Value);
foreach (var prop in claim.Properties)
{
Console.WriteLine("\tProperty: {0} {1}", prop.Key, prop.Value);
}
Console.WriteLine(); } Console.Read();
}

二、声明基于角色的安全性

  static void Main(string[] args)
{
AppDomain.CurrentDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal);
try
{
ShowMessage(); }
catch (Exception ex)
{ } }
[PrincipalPermission(SecurityAction.Demand,Role="administrator")]
static void ShowMessage()
{
Console.WriteLine("The current principal is logged in locally"); }

三、ECDSA算法签名

   class Program
{
internal static CngKey aliceKeySignature;
internal static byte[] alicePubKeyBlob; static void Main(string[] args)
{
CreateKeys();
byte[] aliceData = Encoding.UTF8.GetBytes("Alice");
byte[] aliceSignature = CreateSignature(aliceData, aliceKeySignature);
Console.WriteLine("Alice created signature: {0}",
Convert.ToBase64String(aliceSignature)); if (VerifySignature(aliceData, aliceSignature, alicePubKeyBlob))
{
Console.WriteLine("Alice signature verified successfully");
}
} static void CreateKeys()
{
aliceKeySignature = CngKey.Create(CngAlgorithm.ECDsaP256);
alicePubKeyBlob = aliceKeySignature.Export(CngKeyBlobFormat.GenericPublicBlob);
} static byte[] CreateSignature(byte[] data,CngKey key)
{
byte[] signature;
using (var signingAlg=new ECDsaCng(key))
{
signature = signingAlg.SignData(data);
signingAlg.Clear();
}
return signature;
}
static bool VerifySignature(byte[] data, byte[] signature, byte[] pubKey)
{
bool retValue = false;
using (CngKey key = CngKey.Import(pubKey, CngKeyBlobFormat.GenericPublicBlob))
using (var signingAlg = new ECDsaCng(key))
{
retValue = signingAlg.VerifyData(data, signature);
signingAlg.Clear();
}
return retValue;
}
}

四、交换密钥和安全传输

  class Program
{
static CngKey aliceKey;
static CngKey bobKey;
static byte[] alicePubKeyBlob;
static byte[] bobPubKeyBlob; static void Main()
{
Run();
Console.ReadLine();
} private async static void Run()
{
try
{
CreateKeys();
byte[] encrytpedData = await AliceSendsData("secret message");
await BobReceivesData(encrytpedData);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
} private static void CreateKeys()
{
aliceKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256);
bobKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256);
alicePubKeyBlob = aliceKey.Export(CngKeyBlobFormat.EccPublicBlob);
bobPubKeyBlob = bobKey.Export(CngKeyBlobFormat.EccPublicBlob);
} private async static Task<byte[]> AliceSendsData(string message)
{
Console.WriteLine("Alice sends message: {0}", message);
byte[] rawData = Encoding.UTF8.GetBytes(message);
byte[] encryptedData = null; using (var aliceAlgorithm = new ECDiffieHellmanCng(aliceKey))
using (CngKey bobPubKey = CngKey.Import(bobPubKeyBlob,
CngKeyBlobFormat.EccPublicBlob))
{
byte[] symmKey = aliceAlgorithm.DeriveKeyMaterial(bobPubKey);
Console.WriteLine("Alice creates this symmetric key with " +
"Bobs public key information: {0}",
Convert.ToBase64String(symmKey)); using (var aes = new AesCryptoServiceProvider())
{
aes.Key = symmKey;
aes.GenerateIV();
using (ICryptoTransform encryptor = aes.CreateEncryptor())
using (MemoryStream ms = new MemoryStream())
{
// create CryptoStream and encrypt data to send
var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); // write initialization vector not encrypted
await ms.WriteAsync(aes.IV, , aes.IV.Length);
await cs.WriteAsync(rawData, , rawData.Length);
cs.Close();
encryptedData = ms.ToArray();
}
aes.Clear();
}
}
Console.WriteLine("Alice: message is encrypted: {0}", Convert.ToBase64String(encryptedData)); ;
Console.WriteLine();
return encryptedData;
} private async static Task BobReceivesData(byte[] encryptedData)
{
Console.WriteLine("Bob receives encrypted data");
byte[] rawData = null; var aes = new AesCryptoServiceProvider(); int nBytes = aes.BlockSize >> ;
byte[] iv = new byte[nBytes];
for (int i = ; i < iv.Length; i++)
iv[i] = encryptedData[i]; using (var bobAlgorithm = new ECDiffieHellmanCng(bobKey))
using (CngKey alicePubKey = CngKey.Import(alicePubKeyBlob,
CngKeyBlobFormat.EccPublicBlob))
{
byte[] symmKey = bobAlgorithm.DeriveKeyMaterial(alicePubKey);
Console.WriteLine("Bob creates this symmetric key with " +
"Alices public key information: {0}",
Convert.ToBase64String(symmKey)); aes.Key = symmKey;
aes.IV = iv; using (ICryptoTransform decryptor = aes.CreateDecryptor())
using (MemoryStream ms = new MemoryStream())
{
var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write);
await cs.WriteAsync(encryptedData, nBytes, encryptedData.Length - nBytes);
cs.Close(); rawData = ms.ToArray(); Console.WriteLine("Bob decrypts message to: {0}",
Encoding.UTF8.GetString(rawData));
}
aes.Clear();
}
}
}

C# 安全性的更多相关文章

  1. WCF之安全性

    WCF 客户端代理生成 通过SvcUtil.exe http://www.cnblogs.com/woxpp/p/6232298.html WCF 安全性 之 None http://www.cnbl ...

  2. 线程安全性:num++操作为什么也会出问题?

    线程的安全性可能是非常复杂的,在没有充足同步的情况下,由于多个线程中的操作执行顺序是不可预测的,甚至会产生奇怪的结果(非预期的).下面的Tools工具类的plus方法会使计数加一,为了方便,这里的nu ...

  3. WebApi安全性 使用TOKEN+签名验证

    首先问大家一个问题,你在写开放的API接口时是如何保证数据的安全性的?先来看看有哪些安全性问题在开放的api接口中,我们通过http Post或者Get方式请求服务器的时候,会面临着许多的安全性问题, ...

  4. 数据库---实验四 oracle的安全性和完整性控制

    实验内容: (一) 授权 . 以dba用户的身份登陆oracle,创建用户u1+学号后四位,u2+学号后四位. SQL> create user u1_3985 identified by &q ...

  5. 关于i++引出的线程不安全性的分析以及解决措施

    Q:i++是线程安全的吗? A:如果是局部变量,那么i++是线程安全. 如果是全局变量,那么i++不是线程安全的. 理由:如果是局部变量,那么i++是线程安全:局部变量其他线程访问不到,所以根本不存在 ...

  6. 如何解决例如i++的线程不安全性

    AtomicBoolean.AtomicInteger.AtomicLong.AtomicReference 各种原子性关键字,可以解决比如i++的线程不安全性的因素

  7. RESTful Api 身份认证安全性设计

    REST是一种软件架构风格.RESTful Api 是基于 HTTP 协议的 Api,是无状态传输.它的核心是将所有的 Api 都理解为一个网络资源.将所有的客户端和服务器的状态转移(动作)封装到 H ...

  8. SalesForce 记录级别安全性

    对象级安全性 简档 对象级安全性提供了控制 Salesforce.com 中数据的最简单方式.使用对象级安全性 您可以防止用户查看.创 建.编辑或删除特殊类型对象的任何实例 如潜在客户或业务机会.对象 ...

  9. Atitit.安全性方案规划设计4gm  v1 q928

    Atitit.安全性方案规划设计4gm  v1 q928 1. 安全架构设计与功能安全检测1 2. https1 3. 账号安全体系1 4. 配置文件安全 1 5. 源码加密与安全2 6. 最高强度的 ...

  10. 【学习篇:他山之石,把玉攻】Ajax请求安全性讨论

    在开发过程中怎样考虑ajax安全及防止ajax请求攻击的问题. 先上两段网摘: Ajax安全防范的方法: 判断request的来源地址.这样的方式不推荐,因为黑客可以更改http包头,从而绕过检测. ...

随机推荐

  1. Linux下载安装mysql5.7教程

    首先下载mysql 的安装包,可以去官网下载,网址:https://dev.mysql.com/downloads/mysql/ 然后下滑,在这个地方选择你想要安装的版本: 这里我选择的5.7.点击进 ...

  2. [转帖]ASP.NET Core 中间件(Middleware)详解

    ASP.NET Core 中间件(Middleware)详解   本文为官方文档译文,官方文档现已非机器翻译 https://docs.microsoft.com/zh-cn/aspnet/core/ ...

  3. 多线程-Task、await/async

    Task创建无返回值 Task是.netframwork4.0重新分装的多线程类.原因以前的多线程(thread threadpool)不好用.(.net framwork也是的发展的,现在的EF,刚 ...

  4. 部门innercode刷新

    最近遇到一个小需求,就是刷新部门的innercode.在导入数据的时候,innercode乱了,所以需要刷新.那先说说innercode是什么吧. 大家都知道部门是一个树形结构,但是有时候想知道一个部 ...

  5. 扩散:Apache2放开virtualhost,wamp启动apache服务失败

    原文链接:https://blog.csdn.net/weixin_45688623/article/details/101423164 CSDN写过过程了,有点长,这里不赘述了,只写最后我设置的结果 ...

  6. python爬虫框架scrapy 豆瓣实战

    Scrapy 官方介绍是 An open source and collaborative framework for extracting the data you need from websit ...

  7. Fabric中的节点类型

    在Fabric中,尽管所有对等节点/peer都是相同的,但它们可以根据网络的配置方式承担多个角色:(①②是主要的节点类型) ①提交节点: 通道中的每个对等节点都是一个提交节点.它们接收生成的交易区块, ...

  8. asp.net core-11.WebHost的配置

    1.添加空的web网站 ,在目录下添加settings.json文件,在控制台上输出json的信息 public class Program { public static void Main(str ...

  9. 无服务架构在IOT的应用场景——使用函数工作流处理DIS数据

    在物联网领域,复杂性往往并非在于传感器,真正的复杂性在于各种传感器产生的大量数据,以及对这些数据的处理,所以开发者不得不花费大量的时间去构建和维护后端服务器来处理这样一个庞大的数据流.而在今天这个敏捷 ...

  10. Ubuntu 搭建 配置 nfs服务器

    什么是NFS? NFS(Network File System)即网络文件系统,是FreeBSD支持的文件系统中的一种,它允许网络中的计算机之间通过TCP/IP网络共享资源.在NFS的应用中,本地NF ...