C#加密和解密、哈希

一、加密和解密数据

C#中常用的加密算法包括:对称加密算法(如AES、DES)、非对称加密算法(如RSA)、哈希算法(如MD5、SHA)。这些算法可以通过.NET Framework或.NET Core中提供的相关类来实现。

使用AES进行对称加密

在C#中使用AES进行对称加密通常涉及使用System.Security.Cryptography命名空间中的相关类。您需要创建一个Aes实例,设置密钥和初始化向量(IV)等参数,然后使用该实例来加密和解密数据。

以下是一个简单的示例代码:

using System;
using System.Security.Cryptography;
using System.Text;
public class AESEncryptionExample
{ // 使用AES对字符串进行加密并返回加密后的字节数组
    public static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
    { if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV");
        byte[] encrypted;
        using (Aes aesAlg = Aes.Create())
        { aesAlg.Key = Key;
            aesAlg.IV = IV;
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
            using (MemoryStream msEncrypt = new MemoryStream())
            { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    { swEncrypt.Write(plainText); // 将原始字符串写入加密流
                    }
                    encrypted = msEncrypt.ToArray(); // 将加密后的数据转换为字节数组
                }
            }
        }
        return encrypted;
    }
}

二、哈希数据

在C#中,您可以使用System.Security.Cryptography命名空间中的类来进行哈希数据。常用的哈希算法包括MD5、SHA1、SHA256、SHA384和SHA512等。您可以创建相应的哈希算法提供程序,并将要哈希的数据传递给它们以获得哈希值。

一些常用的非键哈希算法

算法说明
MD5(消息摘要算法5)广泛用于产生数据的短标识,常见于校验文件完整性等场景。然而,由于其安全性存在漏洞,不再适合加密应用。
SHA-1(安全散列算法1)曾经被广泛使用,但随着计算机技术的发展,已被证明不再足够安全。
SHA-256、SHA-384、SHA-512这些是SHA算法家族中的一部分,提供了比SHA-1更高级别的安全性。它们通常用于生成安全哈希值,以确保数据的完整性和安全性。

这些哈希算法在计算机科学和信息安全领域中扮演着重要的角色,用于加密通信、数字签名、密码存储等各种安全应用。

哈希与常用的SHA256算法

以下是一个简单的代码示例,演示如何计算给定字符串的SHA256哈希值:

using System;
using System.Security.Cryptography;
using System.Text;
public class SHA256Example
{ public static string CalculateSHA256(string input)
    { using (SHA256 sha256 = SHA256.Create())
        { byte[] inputBytes = Encoding.UTF8.GetBytes(input);
            byte[] hashBytes = sha256.ComputeHash(inputBytes);
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            { builder.Append(hashBytes[i].ToString("x2"));
            }
            return builder.ToString();
        }
    }
}

三、签名数据

签名数据通常是使用非对称加密算法(如RSA)生成数字签名。数字签名可以确保数据的完整性和来源验证,以便确认数据未被篡改且来自预期的发送方。

使用SHA256和RSA算法进行签名

using System;
using System.Security.Cryptography;
using System.Text;
public class RSASignatureExample
{ public static byte[] SignData(string data, RSAParameters privateKey)
    { using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
        { rsa.ImportParameters(privateKey);
            byte[] dataBytes = Encoding.UTF8.GetBytes(data);
            byte[] signature = rsa.SignData(dataBytes, CryptoConfig.MapNameToOID("SHA256"));
            return signature;
        }
    }
    public static bool VerifyData(string data, byte[] signature, RSAParameters publicKey)
    { using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
        { rsa.ImportParameters(publicKey);
            byte[] dataBytes = Encoding.UTF8.GetBytes(data);
            return rsa.VerifyData(dataBytes, CryptoConfig.MapNameToOID("SHA256"), signature);
        }
    }
}

希望这些关于C#中加密、哈希和签名数据的示例对您有所帮助。如果您有任何其他问题,或者需要进一步的解释或示例,请随时告诉我。我随时为您提供帮助!