一、标识和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. 【转】SpringMVC框架实现后端向前端传数据

    首先还是页面userAdd.jsp.它既是发出请求的页面,也是接收返回结果的页面: <%@ page language="java" import="java.ut ...

  2. c函数模板实现

    实现冒泡排序模板 #include <stdio.h> #include <stdlib.h> #include <time.h> #include <str ...

  3. Linux "yin"才们的奇"yin"小技巧 --请用东北发音夸他们

    1. include/linux/bits.h GENMASK(h, l) /* * Create a contiguous bitmask starting at bit position @l a ...

  4. 剑指offer52:正则表达式匹配

    1 题目描述 请实现一个函数用来匹配包括'.'和'*'的正则表达式.模式中的字符‘.’表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次). 在本题中,匹配是指字符串的所有字符匹配整个 ...

  5. We Need More Bosses CodeForces - 1000E (无向图缩点)

    大意: 给定无向连通图, 定义两个点$s,t$个价值为切断一条边可以使$s,t$不连通的边数. 求最大价值. 显然只有桥会产生贡献. 先对边双连通分量缩点建树, 然后求直径即为答案. #include ...

  6. Luogu4770 NOI2018你的名字(后缀自动机+线段树合并)

    先考虑l=1,r=n,并且不要求本质不同的情况.对原串建SAM,将询问串在上面跑,得到每个前缀的最长匹配后缀即可得到答案. 然后考虑本质不同.对询问串也建SAM,统计每个节点的贡献,得到该点right ...

  7. MySQL 子查询(四)子查询的优化、将子查询重写为连接

    MySQL 5.7 ref ——13.2.10.10优化子查询 十.子查询的优化 开发正在进行中,因此从长远来看,没有什么优化建议是可靠的.以下列表提供了一些您可能想要使用的有趣技巧.See also ...

  8. git this exceeds GitHub's file size limit of 100.00 MB

    git push origin master过程中,出现如下错误 关键词:this exceeds GitHub's file size limit of 100.00 MB 推的时候忽略文件的操作: ...

  9. ckplayer获取播放时长一

    <div id="a1"></div> <div id="nowTime"></div> <script ...

  10. Unity中的Character Controller

    Unity中默认提供了一个Character Controller的组件用于实现角色控制,一个3D的游戏物体,可以直接添加.Character Controller会自动模拟出Capsule Coll ...