C# 安全性

一、标识和Principal

 1 static void Main(string[] args)
 2         {
 3             AppDomain.CurrentDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal);
 4             var principal = WindowsPrincipal.Current as WindowsPrincipal;
 5             var identity = principal.Identity as WindowsIdentity;
 6 
 7             Console.WriteLine("IdentityType: {0}", identity.ToString());
 8             Console.WriteLine("Name: {0}", identity.Name);
 9             Console.WriteLine("‘Users’?: {0}", principal.IsInRole(WindowsBuiltInRole.User));
10             Console.WriteLine("‘Administrators’? {0}", principal.IsInRole(WindowsBuiltInRole.Administrator));
11             Console.WriteLine("Authenticated: {0}", identity.IsAuthenticated);
12             Console.WriteLine("AuthType: {0}", identity.AuthenticationType);
13             Console.WriteLine("Anonymous? {0}", identity.IsAnonymous);
14             Console.WriteLine("Token: {0}", identity.Token);
15 
16             Console.WriteLine();
17             Console.WriteLine("Claims");
18             foreach (var claim in principal.Claims)
19             {
20                 Console.WriteLine("Subject: {0}", claim.Subject);
21                 Console.WriteLine("Issuer: {0}", claim.Issuer);
22                 Console.WriteLine("Type: {0}", claim.Type);
23                 Console.WriteLine("Value type: {0}", claim.ValueType);
24                 Console.WriteLine("Value: {0}", claim.Value);
25                 foreach (var prop in claim.Properties)
26                 {
27                     Console.WriteLine("	Property: {0} {1}", prop.Key, prop.Value);
28                 }
29                 Console.WriteLine();
30 
31             }
32 
33             Console.Read();
34         }
View Code

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

 1  static void Main(string[] args)
 2         {
 3             AppDomain.CurrentDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal);
 4             try
 5             {
 6                 ShowMessage();
 7 
 8             }
 9             catch (Exception ex)
10             {
11                  
12             }
13 
14         }
15         [PrincipalPermission(SecurityAction.Demand,Role="administrator")]
16         static void ShowMessage()
17         {
18             Console.WriteLine("The current principal is logged in locally");
19 
20         }
View Code

三、ECDSA算法签名

 1   class Program
 2     {
 3         internal static CngKey aliceKeySignature;
 4         internal static byte[] alicePubKeyBlob;
 5 
 6         static void Main(string[] args)
 7         {
 8             CreateKeys();
 9             byte[] aliceData = Encoding.UTF8.GetBytes("Alice");
10             byte[] aliceSignature = CreateSignature(aliceData, aliceKeySignature);
11             Console.WriteLine("Alice created signature: {0}",
12              Convert.ToBase64String(aliceSignature));
13 
14             if (VerifySignature(aliceData, aliceSignature, alicePubKeyBlob))
15             {
16                 Console.WriteLine("Alice signature verified successfully");
17             }
18         }
19 
20         static void CreateKeys()
21         {
22             aliceKeySignature = CngKey.Create(CngAlgorithm.ECDsaP256);
23             alicePubKeyBlob = aliceKeySignature.Export(CngKeyBlobFormat.GenericPublicBlob);
24         }
25 
26         static byte[] CreateSignature(byte[] data,CngKey key)
27         {
28             byte[] signature;
29             using (var signingAlg=new ECDsaCng(key))
30             {
31                 signature = signingAlg.SignData(data);
32                 signingAlg.Clear();
33             }
34             return signature;
35         }
36         static bool VerifySignature(byte[] data, byte[] signature, byte[] pubKey)
37         {
38             bool retValue = false;
39             using (CngKey key = CngKey.Import(pubKey, CngKeyBlobFormat.GenericPublicBlob))
40             using (var signingAlg = new ECDsaCng(key))
41             {
42                 retValue = signingAlg.VerifyData(data, signature);
43                 signingAlg.Clear();
44             }
45             return retValue;
46         }
47     }
View Code

四、交换密钥和安全传输

  1  class Program
  2     {
  3         static CngKey aliceKey;
  4         static CngKey bobKey;
  5         static byte[] alicePubKeyBlob;
  6         static byte[] bobPubKeyBlob;
  7 
  8         static void Main()
  9         {
 10             Run();
 11             Console.ReadLine();
 12         }
 13 
 14         private async static void Run()
 15         {
 16             try
 17             {
 18                 CreateKeys();
 19                 byte[] encrytpedData = await AliceSendsData("secret message");
 20                 await BobReceivesData(encrytpedData);
 21             }
 22             catch (Exception ex)
 23             {
 24                 Console.WriteLine(ex.Message);
 25             }
 26         }
 27 
 28 
 29 
 30         private static void CreateKeys()
 31         {
 32             aliceKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256);
 33             bobKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256);
 34             alicePubKeyBlob = aliceKey.Export(CngKeyBlobFormat.EccPublicBlob);
 35             bobPubKeyBlob = bobKey.Export(CngKeyBlobFormat.EccPublicBlob);
 36         }
 37 
 38         private async static Task<byte[]> AliceSendsData(string message)
 39         {
 40             Console.WriteLine("Alice sends message: {0}", message);
 41             byte[] rawData = Encoding.UTF8.GetBytes(message);
 42             byte[] encryptedData = null;
 43 
 44             using (var aliceAlgorithm = new ECDiffieHellmanCng(aliceKey))
 45             using (CngKey bobPubKey = CngKey.Import(bobPubKeyBlob,
 46                   CngKeyBlobFormat.EccPublicBlob))
 47             {
 48                 byte[] symmKey = aliceAlgorithm.DeriveKeyMaterial(bobPubKey);
 49                 Console.WriteLine("Alice creates this symmetric key with " +
 50                       "Bobs public key information: {0}",
 51                       Convert.ToBase64String(symmKey));
 52 
 53                 using (var aes = new AesCryptoServiceProvider())
 54                 {
 55                     aes.Key = symmKey;
 56                     aes.GenerateIV();
 57                     using (ICryptoTransform encryptor = aes.CreateEncryptor())
 58                     using (MemoryStream ms = new MemoryStream())
 59                     {
 60                         // create CryptoStream and encrypt data to send
 61                         var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);
 62 
 63                         // write initialization vector not encrypted
 64                         await ms.WriteAsync(aes.IV, 0, aes.IV.Length);
 65                         await cs.WriteAsync(rawData, 0, rawData.Length);
 66                         cs.Close();
 67                         encryptedData = ms.ToArray();
 68                     }
 69                     aes.Clear();
 70                 }
 71             }
 72             Console.WriteLine("Alice: message is encrypted: {0}", Convert.ToBase64String(encryptedData)); ;
 73             Console.WriteLine();
 74             return encryptedData;
 75         }
 76 
 77         private async static Task BobReceivesData(byte[] encryptedData)
 78         {
 79             Console.WriteLine("Bob receives encrypted data");
 80             byte[] rawData = null;
 81 
 82             var aes = new AesCryptoServiceProvider();
 83 
 84             int nBytes = aes.BlockSize >> 3;
 85             byte[] iv = new byte[nBytes];
 86             for (int i = 0; i < iv.Length; i++)
 87                 iv[i] = encryptedData[i];
 88 
 89             using (var bobAlgorithm = new ECDiffieHellmanCng(bobKey))
 90             using (CngKey alicePubKey = CngKey.Import(alicePubKeyBlob,
 91                   CngKeyBlobFormat.EccPublicBlob))
 92             {
 93                 byte[] symmKey = bobAlgorithm.DeriveKeyMaterial(alicePubKey);
 94                 Console.WriteLine("Bob creates this symmetric key with " +
 95                       "Alices public key information: {0}",
 96                       Convert.ToBase64String(symmKey));
 97 
 98                 aes.Key = symmKey;
 99                 aes.IV = iv;
100 
101                 using (ICryptoTransform decryptor = aes.CreateDecryptor())
102                 using (MemoryStream ms = new MemoryStream())
103                 {
104                     var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write);
105                     await cs.WriteAsync(encryptedData, nBytes, encryptedData.Length - nBytes);
106                     cs.Close();
107 
108                     rawData = ms.ToArray();
109 
110                     Console.WriteLine("Bob decrypts message to: {0}",
111                           Encoding.UTF8.GetString(rawData));
112                 }
113                 aes.Clear();
114             }
115         }
116     }
View Code
原文地址:https://www.cnblogs.com/farmer-y/p/6092802.html