一、标识和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. ElasticSearch总结

    转载自:https://www.cnblogs.com/WessonStar/p/8296781.html 不过我的es版本是7.2.0,然后这里要注意ik分词器放入plugins里是需要有个ik插件 ...

  2. 25.Spark下载源码和安装和使用

    安装scala 上传安装包 解压 配置scala相关的环境变量 export SCALA_HOME=/opt/modules/scala-2.11.4 export PATH=$PATH:$SCALA ...

  3. mysql中char和varchar区别

    char是一种固定长度的类型,varchar则是一种可变长度的类型  char(M)类型的数据列里,每个值都占用M个字节,如果某个长度小于M,MySQL就会在它的右边用空格字符补足.(在检索操作中那些 ...

  4. 十、LCD的framebuffer设备驱动

    在读者学习本章以及后续LCD相关章节之前,最好拥有LCD裸机基础,可以参考:LCD编程. 在内核中,表示LCD使用的是framebuffer(帧缓冲,简写为fb),其内容对应于屏幕上的界面显示.修改f ...

  5. preg_replace

    preg_replace — 执行一个正则表达式的搜索和替换 说明: preg_replace ( mixed $pattern , mixed $replacement , mixed $subje ...

  6. hdu 4857 反向拓扑问题

    尤其要注意拓扑的分层问题 不难理解 就是不怎么好想到 拓扑的思路这里就不累述了 #include <iostream> #include <cstdio> #include & ...

  7. Java锁的升级策略 偏向锁 轻量级锁 重量级锁

    这三种锁是指锁的状态,并且是专门针对Synchronized关键字.JDK 1.6 为了减少"重量级锁"的性能消耗,引入了"偏向锁"和"轻量级锁&qu ...

  8. 请问IOS中做一个手机网站的app壳复杂吗?

    公司开发了一个平台,手机网站已经做出来了,想开发一个苹果应用app,但公司没人会IOS开发,为了减小成本,现在想直接做一个壳来加载手机网站,请问在ios中复杂吗?是否有相应的控件直接加载url就行? ...

  9. cli create ssl certkey

    cli create ssl certkey ############################### # 创建CA密钥 create ssl rsakey bwsrv-root.key -ex ...

  10. Python中带参数的装饰器

    装饰器本身是用来是为一个函数是实现新的功能,并且不改变原函数的代码以及调用方式. 遇到这样一种问题: 众多函数调用了你写的装饰器,但客户有需求说,我想实现我可以随之控制装饰器是否生效. 那你就不可能在 ...