一、标识和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. python3 爬虫利用Requests 实现下载进度条

    一.编写代码 from datetime import datetime,date,timedelta from contextlib import closing import urllib,url ...

  2. Windows Terminal Preview v0.7 Release

    Windows Terminal Preview v0.7 Release The following key bindings are included by default within this ...

  3. 使ssh记住密码

    前面介绍过Conemu , Msys2工具,提升了windows本地文件操作的效率,但使用ssh时候,总需要重新输入密码,不能像SercurityCRT等工具记住密码,使用时不是很爽快. 其实通过ss ...

  4. python Django基础操作

    Django常用命令 创建Django项目 Django-admin startprotect  mysite 创建项目以后,以下生成的文件 最外层的file:mysite/ 根目录只是你的项目的容器 ...

  5. oj上的测试点信息

    Accepted                          通过!(AC) Wrong Answer                  答案错.(WA) Runtime Error      ...

  6. 基于laravel框架构建最小内容管理系统

    校园失物招领平台开发 --基于laravel框架构建最小内容管理系统 摘要 ​ 针对目前大学校园人口密度大.人群活动频繁.师生学习生活等物品容易遗失的基本现状,在分析传统失物招领过程中的工作效率低下. ...

  7. java代码检出打包

    这里先提下前提,就是有个维护的(可能有二期的一个项目),后端是Java,由于很久都不做Java,剩下的只是不多了.之前做的Java容器要么是tomcat,要么接触过新的spring cloud.从来没 ...

  8. Java 实现简单的 RPC 框架

    RPC 简介 RPC,全称为 Remote Procedure Call,即远程过程调用,它是一个计算机通信协议.它允许像调用本地服务一样调用远程服务.它可以有不同的实现方式,而不需要了解底层网络技术 ...

  9. .NET CORE 下 MariaDB DBfirst 生成model层 并配置连接参数

    1.首先新建一个类库,然后通过NuGet安装下面三个包 2.然后在程序包管理器控制台中运行以下代码(ps:记得默认项目选择刚才新建的项目,同时设置为启动项) server 是服务器地址 databas ...

  10. docker系列五之数据卷(volumn)

    docker数据卷(volumn) 一. 为什么需要数据卷 docker镜像是由多个文件系统(只读层)叠加而成,当我们启动一个容器的时候,docker的服务端会加载镜像的只读层,并在最顶层创建一个可读 ...