C# 安全性
一、标识和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# 安全性的更多相关文章
- WCF之安全性
WCF 客户端代理生成 通过SvcUtil.exe http://www.cnblogs.com/woxpp/p/6232298.html WCF 安全性 之 None http://www.cnbl ...
- 线程安全性:num++操作为什么也会出问题?
线程的安全性可能是非常复杂的,在没有充足同步的情况下,由于多个线程中的操作执行顺序是不可预测的,甚至会产生奇怪的结果(非预期的).下面的Tools工具类的plus方法会使计数加一,为了方便,这里的nu ...
- WebApi安全性 使用TOKEN+签名验证
首先问大家一个问题,你在写开放的API接口时是如何保证数据的安全性的?先来看看有哪些安全性问题在开放的api接口中,我们通过http Post或者Get方式请求服务器的时候,会面临着许多的安全性问题, ...
- 数据库---实验四 oracle的安全性和完整性控制
实验内容: (一) 授权 . 以dba用户的身份登陆oracle,创建用户u1+学号后四位,u2+学号后四位. SQL> create user u1_3985 identified by &q ...
- 关于i++引出的线程不安全性的分析以及解决措施
Q:i++是线程安全的吗? A:如果是局部变量,那么i++是线程安全. 如果是全局变量,那么i++不是线程安全的. 理由:如果是局部变量,那么i++是线程安全:局部变量其他线程访问不到,所以根本不存在 ...
- 如何解决例如i++的线程不安全性
AtomicBoolean.AtomicInteger.AtomicLong.AtomicReference 各种原子性关键字,可以解决比如i++的线程不安全性的因素
- RESTful Api 身份认证安全性设计
REST是一种软件架构风格.RESTful Api 是基于 HTTP 协议的 Api,是无状态传输.它的核心是将所有的 Api 都理解为一个网络资源.将所有的客户端和服务器的状态转移(动作)封装到 H ...
- SalesForce 记录级别安全性
对象级安全性 简档 对象级安全性提供了控制 Salesforce.com 中数据的最简单方式.使用对象级安全性 您可以防止用户查看.创 建.编辑或删除特殊类型对象的任何实例 如潜在客户或业务机会.对象 ...
- Atitit.安全性方案规划设计4gm v1 q928
Atitit.安全性方案规划设计4gm v1 q928 1. 安全架构设计与功能安全检测1 2. https1 3. 账号安全体系1 4. 配置文件安全 1 5. 源码加密与安全2 6. 最高强度的 ...
- 【学习篇:他山之石,把玉攻】Ajax请求安全性讨论
在开发过程中怎样考虑ajax安全及防止ajax请求攻击的问题. 先上两段网摘: Ajax安全防范的方法: 判断request的来源地址.这样的方式不推荐,因为黑客可以更改http包头,从而绕过检测. ...
随机推荐
- Jmeter 跨线程组传递参数 之两种方法(转)
终于搞定了Jmeter跨线程组之间传递参数,这样就不用每次发送请求B之前,都需要同时发送一下登录接口(因为同一个线程组下的请求是同时发送的),只需要发送一次登录请求,请求B直接用登录请求的参数即可,直 ...
- swagger 爬坑记
Swagger 的好处不用我多说,但是一不小心可能就被坑……今天下午就被上了一课,废话不多说,直接上代码(图) 实体类: 好像没啥问题,对吧? 但是,在http://localhost:8080/sw ...
- python学习-49 json模块
json模块 --------将任何类型都转换为json字符串 方法dumps import json dic={"name":"abc"} data = js ...
- 理解Python函数和方法
什么是函数? 函数是抽象出的一组执行特定功能的重复代码,通俗理解,就是对一些重复的工作进行封装和然后直接调用,避免重复造轮子. Python中的函数如何定义? 使用def关键字,结构如下: def 函 ...
- Java中数据存储分配
(1)内存分配的策略 按照编译原理的观点,程序运行时的内存分配有三种策略,分别是静态的,栈式的,和堆式的. 静态存储分配是指在编译时就能确定每个数据目标在运行时刻的存储空间需求,因而在编 译时就可以给 ...
- ajax回调函数,全局变量赋值后,ajax外无法获取的解决
1 ajax回调函数内,function的执行与ajax外是异步的,常导致全局变量赋值后,再次使用此变量人无法获取. 所以,可以把需要的步骤,独立放在functuon中,在ajax回调函数中执行.可较 ...
- css 动画(一)transform 变形
前言:这是笔者学习之后自己的理解与整理.如果有错误或者疑问的地方,请大家指正,我会持续更新! 有段时间我是没理清 transform.translate.transition 和 animation之 ...
- poj 1837 天平问题(01背包变种)
题意:给你n个挂钩,m个砝码,要求砝码都用上,问有多少中方案数 题解:对于这道题目的状态,我们定义一个变量j为平衡度,当j=0的时候,表明天平平衡.定义dp[i][j]表达的含义为使用前n个砝码的时候 ...
- (二)CXF之用CXF官方工具生成客户端Client
一.CXF工具的下载与使用 登录CXF官网:http://cxf.apache.org/download.html 下载,本系列使用的是3.1.5版本: 添加path环境变量 二.案例 2.1 发布w ...
- Mysql的实现原理
上篇文章已经简单介绍了Mysql索引的基本介绍,这篇文章主要讲解一下所以的实现原理.索引的定义其实非常复杂,严格的定义需要用到关系代数的概念,不在咱们讨论范围内,这里咱们只讨论mysql的常用的引擎的 ...