【C#】加密、解密消息、用户注册、生成随机字节数组、安全访问、签名数据 (.net5 c#9)

引用CryptographyLib 项目库:

消息对称加密与解密

using System;                       // Exception
using System.Security.Cryptography; // CryptographicException
using Packt.Shared;                 // Protector
using static System.Console;

namespace EncryptionApp
{
  class Program
  {
    static void Main(string[] args)
    {
      Write("Enter a message that you want to encrypt: ");
      string message = ReadLine();
      Write("Enter a password: ");
      string password = ReadLine();

      string cryptoText = Protector.Encrypt(message, password);

      WriteLine($"Encrypted text: {cryptoText}");
      Write("Enter the password: ");
      string password2 = ReadLine();

      try
      {
        string clearText = Protector.Decrypt(cryptoText, password2);
        WriteLine($"Decrypted text: {clearText}");
      }
      catch (CryptographicException ex)//加密异常
      {
        WriteLine("{0}\nMore details: {1}",
          arg0: "You entered the wrong password!",
          arg1: ex.Message);
      }
      catch (Exception ex)
      {
        WriteLine("Non-cryptographic exception: {0}, {1}",
          arg0: ex.GetType().Name,
          arg1: ex.Message);
      }
    }
  }
}

注册 用户名和密码:

using System;
using Packt.Shared;
using static System.Console;

namespace HashingApp
{
  class Program
  {
    static void Main(string[] args)
    {
      WriteLine("Registering Alice with Pa$$w0rd.");
      var alice = Protector.Register("Alice", "Pa$$w0rd");//注册:账号 密码
      WriteLine($"Name: {alice.Name}");
      WriteLine($"Salt: {alice.Salt}");
      WriteLine("Password (salted and hashed): {0}",
        arg0: alice.SaltedHashedPassword);
      WriteLine();

      Write("Enter a new user to register: ");
      string username = ReadLine();
      Write($"Enter a password for {username}: ");
      string password = ReadLine();
      var user = Protector.Register(username, password);
      WriteLine($"Name: {user.Name}");
      WriteLine($"Salt: {user.Salt}");
      WriteLine("Password (salted and hashed): {0}",
        arg0: user.SaltedHashedPassword);
      WriteLine();

      bool correctPassword = false;
      while (!correctPassword)
      {
        Write("Enter a username to log in: ");
        string loginUsername = ReadLine();
        Write("Enter a password to log in: ");
        string loginPassword = ReadLine();
                //验证 用户名和密码
        correctPassword = Protector.CheckPassword(
          loginUsername, loginPassword);

        if (correctPassword)
        {
          WriteLine($"Correct! {loginUsername} has been logged in.");
        }
        else
        {
          WriteLine("Invalid username or password. Try again.");
        }
      }
    }
  }
}

生成真正随机的秘钥和初始化向量:

        public static byte[] GetRandomKeyOrIV(int size)
        {
            var r = RandomNumberGenerator.Create();
            var data = new byte[size];
            r.GetNonZeroBytes(data);
            // data is an array now filled with 
            // cryptographically strong random bytes·
            return data;
        }

using System;
using Packt.Shared;
using static System.Console;

namespace RandomizingApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Write("How big do you want the key (in bytes): ");
            string size = ReadLine();
            //生成随机秘钥和初始化向量
            byte[] key = Protector.GetRandomKeyOrIV(int.Parse(size));

            WriteLine($"Key as byte array:");
            for (int b = 0; b < key.Length; b++)
            {
                Write($"{key[b]:x2} ");
                if (((b + 1) % 16) == 0) WriteLine();
            }
            WriteLine();
            ReadLine();
        }
    }
}

安全访问,角色授权

using System;
using static System.Console;
using Packt.Shared;
using System.Threading;
using System.Security;
using System.Security.Permissions;
using System.Security.Principal;
using System.Security.Claims;

namespace SecureApp
{
    class Program
    {
        static void Main(string[] args)
        {//注册三个用户,带有角色(权利)
            Protector.Register("Alice", "Pa$$w0rd", new[] { "Admins" });
            Protector.Register("Bob", "Pa$$w0rd",
              new[] { "Sales", "TeamLeads" });
            Protector.Register("Eve", "Pa$$w0rd");

            Write($"Enter your user name: ");
            string username = ReadLine();
            Write($"Enter your password: ");
            string password = ReadLine();
            //登录
            Protector.LogIn(username, password);
            if (Thread.CurrentPrincipal == null)
            {
                WriteLine("Log in failed.");
                return;
            }

            var p = Thread.CurrentPrincipal;//当前线程委托人

            WriteLine($"IsAuthenticated: {p.Identity.IsAuthenticated}");//已授权  有角色
            WriteLine($"AuthenticationType: {p.Identity.AuthenticationType}");// AuthenticationType: PacktAuth
            WriteLine($"Name: {p.Identity.Name}");
            WriteLine($"IsInRole(\"Admins\"): {p.IsInRole("Admins")}");//如果当前委托人是指定角色的成员,则为真; 否则,假的。
            WriteLine($"IsInRole(\"Sales\"): {p.IsInRole("Sales")}");

            if (p is ClaimsPrincipal)//支持多个基于声明的身份的 System.Security.Principal.IPrincipal 实现。
            {
                WriteLine($"{p.Identity.Name} has the following claims:");
                //获取一个集合,其中包含来自与此声明主体关联的所有声明标识的所有声明。
                foreach (Claim claim in (p as ClaimsPrincipal).Claims)
                {
                    WriteLine($"{claim.Type}: {claim.Value}");
                }
            }
            /*
                Enter your user name: Bob
                Enter your password: Pa$$w0rd
                IsAuthenticated: True
                AuthenticationType: PacktAuth
                Name: Bob
                IsInRole("Admins"): False
                IsInRole("Sales"): True
                Bob has the following claims:
                http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name: Bob
                http://schemas.microsoft.com/ws/2008/06/identity/claims/role: Sales
                http://schemas.microsoft.com/ws/2008/06/identity/claims/role: TeamLeads
                System.Security.SecurityException: User must be a member of Admins to access this feature.
            */
            try
            {
                SecureFeature();
            }
            catch (System.Exception ex)
            {
                WriteLine($"{ex.GetType()}: {ex.Message}");
            }
            ReadLine();
        }

        static void SecureFeature()
        {
            if (Thread.CurrentPrincipal == null)
            {
                throw new SecurityException(
                  "A user must be logged in to access this feature.");
            }

            if (!Thread.CurrentPrincipal.IsInRole("Admins"))
            {
                throw new SecurityException(
                  "User must be a member of Admins to access this feature.");
            }

            WriteLine("You have access to this secure feature.");
        }
    }
}

数据生成签名、验证签名

using System;
using Packt.Shared;
using static System.Console;

namespace SigningApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Write("输入一些文字进行签名: ");
            string data = ReadLine();
            var signature = Protector.GenerateSignature(data);//RSA签名数据的哈希值
            WriteLine($"Signature: {signature}");
            WriteLine("用于检查签名的公钥:");
            WriteLine(Protector.PublicKey);

            if (Protector.ValidateSignature(data, signature))//验证签名
            {
                WriteLine("Correct! Signature is valid.");
            }
            else
            {
                WriteLine("Invalid signature.");
            }

            // 通过用 X 替换第一个字符来模拟假签名
            var fakeSignature = signature.Replace(signature[0], 'X');

            if (Protector.ValidateSignature(data, fakeSignature))//验证签名
            {
                WriteLine("Correct! Signature is valid.");
            }
            else
            {
                WriteLine($"Invalid signature: {fakeSignature}");
            }
        }
    }
}
 //生成数据的签名   先SHA256加密数据
        public static string GenerateSignature(string data)
        {
            byte[] dataBytes = Encoding.Unicode.GetBytes(data);
            var sha = SHA256.Create();
            var hashedData = sha.ComputeHash(dataBytes);

            var rsa = RSA.Create();
            PublicKey = rsa.ToXmlStringExt(false); // exclude private key

            return ToBase64String(rsa.SignHash(hashedData,
              HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1));//RSASignaturePadding指定用于 RSA 签名创建或验证操作的填充模式和参数。
        }
        //验证签名
        public static bool ValidateSignature(
          string data, string signature)
        {
            byte[] dataBytes = Encoding.Unicode.GetBytes(data);
            var sha = SHA256.Create();
            var hashedData = sha.ComputeHash(dataBytes);//数据的哈希值
            byte[] signatureBytes = FromBase64String(signature);//签名数据
            var rsa = RSA.Create();
            rsa.FromXmlStringExt(PublicKey);//导入RSA参数
            //验证哈希值
            return rsa.VerifyHash(hashedData, signatureBytes,
              HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
        }

猜你喜欢

转载自blog.csdn.net/cxyhjl/article/details/130105331