[Reading Notes] C # advanced programming Chapter 1 Security,

Source: Internet
Author: User

[Reading Notes] C # advanced programming Chapter 1 Security,

(1) identity authentication and authorization

Two basic pillars of security are identity authentication and authorization. Identity Authentication is a process of identifying users. Authorization is performed after verifying whether the identified users can access feature resources.

 

1. ID and Principal

You can use the identity to verify the user who runs the application. Principal is an object that contains the user's identity and role.

AppDomain. currentDomain. setPrincipalPolicy (PrincipalPolicy. windowsPrincipal); var principal = WindowsPrincipal. current as WindowsPrincipal; var identity = principal. identity as WindowsIdentity; Console. writeLine ("ID type: {0}", identity. toString (); Console. writeLine ("Name: {0}", identity. name); Console. writeLine ("Whether the role is a user: {0}", principal. isInRole (WindowsBuiltInRole. user); Console. writeLine ("Whether the role is a super administrator: {0}", principal. isInRole (WindowsBuiltInRole. administrator); Console. writeLine ("whether to authenticate: {0}", identity. isAuthenticated); Console. writeLine ("authentication type: {0}", identity. authenticationType); Console. writeLine ("Anonymous: {0}", identity. isAnonymous); Console. writeLine ("account Tag: {0}", identity. token );

 

2. Role

Role-based security can effectively solve resource access problems.

 

3. Declare role-based security

If you use an account in a non-local User group to run the following code, the ShowMessage () method throws an exception.

Static void Main (string [] args) {AppDomain. currentDomain. setPrincipalPolicy (PrincipalPolicy. windowsPrincipal); try {ShowMessage ();} catch (SecurityException exception) {Console. writeLine ("capturing security exceptions :( {0})", exception. message); Console. writeLine ("the current subject should be placed in the local user group");} Console. readKey ();} [PrincipalPermission (SecurityAction. demand, Role = "BUILTIN \ Users")] private static void ShowMessage () {Console. writeLine ("the current subject has logged on to the local computer"); Console. writeLine ("(the member in the local user group is )");}

 

4. Claim

In addition to using roles, you can also use claims to access user information. The ability to describe an object in relation to the object. Entities are usually users or applications. Capability describes the operations that an object can perform. This claim is much more flexible than the role model.

Var principal = WindowsPrincipal. Current as ClaimsPrincipal; Console. WriteLine (); Console. WriteLine ("gets a set containing all declarations that come from the declaration identifier associated with this declarative body. "); Foreach (var claim in principal. claims) {Console. writeLine ("Topic: {0}", claim. subject) Console. writeLine ("issuer: {0}", claim. issuer); Console. writeLine ("claim 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 ("\ t attribute: {0} {1}", prop. key, prop. value);} Console. writeLine ();}

 

5. Client application services

Code is too long.

Server Source Code: Download

Client source code: Download

Before running the SDK, you must note that the client app. config: the connection location of serviceUri to be modified is the connection run by the server. For example, serviceUri in the source code is serviceUri = "http: // localhost: 59514/Role_JSON_Appservice.axd ", to modify the link address (for example, http: // localhost: 9999/) and Role_JSON_Appservice.axd after you run the website, serviceUri = "http: // localhost: 9999/Role_JSON_Appservice.axd" is final ".

 

(2) Encryption

1. Signature

1 internal static CngKey aliceKeySignature; 2 internal static byte [] alicePubKeyBlob; 3 static void Main (string [] args) 4 {5 CreateKeys (); 6 7 byte [] aliceData = Encoding. UTF8.GetBytes ("Alice"); 8 byte [] aliceSignature = CreateSignatrue (aliceData, aliceKeySignature); 9 10 Console. writeLine ("Alice created the signature: {0}", Convert. toBase64String (aliceSignature); 11 12 if (VerifySignature (aliceData, aliceSignature, alicePubKeyBlob) 13 {14 Console. writeLine ("Alice's signature verification succeeded"); 15} 16 17 Console. readKey (); 18} 19 20 private static bool VerifySignature (byte [] data, byte [] signature, byte [] pubKey) 21 {22 bool retValue = false; 23 using (CngKey key = CngKey. import (pubKey, CngKeyBlobFormat. genericPublicBlob) 24 using (var signingAlg = new ECDsaCng (key) 25 {26 retValue = signingAlg. verifyData (data, signature); 27 signingAlg. clear (); 28} 29 return retValue; 30} 31 32 private static byte [] CreateSignatrue (byte [] data, CngKey key) 33 {34 byte [] signature; 35 using (var signingAlg = new ECDsaCng (key) 36 {37 signature = signingAlg. signData (data); 38 signingAlg. clear (); 39} 40 return signature; 41} 42 43 44 private static void CreateKeys () 45 {46 aliceKeySignature = CngKey. create (CngAlgorithm. ECDiffieHellmanP256); 47 alicePubKeyBlob = aliceKeySignature. export (CngKeyBlobFormat. genericPublicBlob); 48}

 

 

2. Key Exchange and secure transmission

Use the DiffieHellman algorithm to exchange a symmetric key for secure transmission.

 

(3) Resource Access Control

In the operating system, all resources are protected by the access control list (ACL. The resource has an associated security descriptor. The security descriptor contains information about the resource owner and references two access control lists: the Free Access Control List (DACL, which determines who has access permissions) and the system access control list (SACL, identify audit rules for Security Event Logs ). The ACL contains a list of access control items (ACE, including types, security identifiers, and permissions. In DACL, the ACE type can be allow or deny access. The permissions that can be set and obtained using files are create, read, write, delete, modify, change, and obtain permissions.

Obtain the access control list of a file:

Static void Main (string [] args) {string fileName = @ "C: \ Users \ Administrator \ Desktop \ 1.txt"; using (FileStream fs = File. open (fileName, FileMode. open) {FileSecurity securityDescriptor = fs. getAccessControl (); AuthorizationRuleCollection rules = securityDescriptor. getAccessRules (true, true, typeof (NTAccount); foreach (AuthorizationRule rule in rules) {var fileRule = rule as FileSystemAccessRule; Console. writeLine ("access type: {0}", fileRule. accessControlType); Console. writeLine ("permission: {0}", fileRule. fileSystemRights); Console. writeLine ("Identity: {0}", fileRule. identityReference. value); Console. writeLine ();}}}

 

Modify access permissions reference: http://www.cnblogs.com/wolf-sun/p/4591734.html

 

 

(5) code access security

In role-based security, you can define what users are allowed to do. In code-based security, you can specify what code can do.

1. Level 1 security transparency

Use the SecurityRules feature to annotate the Assembly and set SecurityRuleSet. Level2 to the level added by application. net4.

[assembly: SecurityRules(SecurityRuleSet.Level2)]

 

2. Permissions

If the code runs in the sandbox, the sandbox can define. NET permissions to define the operations that the code can perform. Permission is an action that allows (or disables) The execution of each code group (for example, reading files in the file system ).. The. NET permission is independent of the operating system permission .. . NET permission is only verified by CLR.

 

(1) permission set

A permission set is a set of permissions.

 

(2) Permission requirements through programming

An assembly can be declared or programmed to require permissions.

 

(3) Use the sandbox API to include unauthorized code

 

 

(5) Use a certificate to publish code

The digital certificate can be used to sign the Assembly so that the software consumer can verify the identity of the software publisher.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.