Aegis.Security.Encryption 加密类库

本文档提供 Aegis.Security.Encryption.Extensions 加密类库的详细使用说明,包括各种加密算法的介绍、API说明和代码示例。

目录


快速开始

引入Nuget包

dotnet add package Aegis.Security.Encryption

引用命名空间

using Aegis.Security.Encryption.Extensions;

对称加密算法

1. AES加密

算法简介

AES(Advanced Encryption Standard)是目前最广泛使用的对称加密算法,安全性高、性能好。支持128位、192位和256位密钥长度。

特点:

  • 安全性高,适合加密敏感数据
  • 支持多种加密模式(CBC、CFB、OFB、CTR)
  • 禁用不安全的ECB模式
  • 默认使用PKCS7填充

主要方法

1.1 字符串加密
public static string AESEncrypt(
    this string plainText,                        // 待加密的明文,不能为空
    string key,                                    // 密钥字符串,必须是16/24/32字节(对应128/192/256位)
    string iv,                                     // 初始化向量字符串,必须是16字节
    Encoding encoding = null,                      // 字符串编码,默认UTF8
    CipherMode mode = CipherMode.CBC,              // 加密模式,默认CBC(禁用ECB)
    PaddingMode padding = PaddingMode.PKCS7        // 填充模式,默认PKCS7
)
1.2 字符串解密
public static string AESDecrypt(
    this string cipherText,                        // Base64编码的密文
    string key,                                    // 密钥字符串,必须是16/24/32字节
    string iv,                                     // 初始化向量字符串,必须是16字节
    Encoding encoding = null,                      // 字符串编码,默认UTF8
    CipherMode mode = CipherMode.CBC,              // 加密模式,必须与加密时一致
    PaddingMode padding = PaddingMode.PKCS7        // 填充模式,必须与加密时一致
)
1.3 生成密钥对
public static (byte[] key, byte[] iv) AESGenerateKeyPair(
    int keySize = 256                              // 密钥长度,可选128/192/256位,默认256
)

调用示例

// 示例1:使用字符串密钥加密解密
string plainText = "这是需要加密的敏感数据";
string key = "1234567890123456";  // 16字节密钥(128位)
string iv = "abcdefghijklmnop";   // 16字节IV

// 加密
string encrypted = plainText.AESEncrypt(key, iv);
Console.WriteLine($"加密结果: {encrypted}");

// 解密
string decrypted = encrypted.AESDecrypt(key, iv);
Console.WriteLine($"解密结果: {decrypted}");

// 示例2:生成随机密钥
var (keyBytes, ivBytes) = AESExtensions.AESGenerateKeyPair(256); // 256位密钥
string text = "Hello World";

// 使用字节数组加密
string encrypted2 = text.AESEncrypt(keyBytes, ivBytes);
string decrypted2 = encrypted2.AESDecrypt(keyBytes, ivBytes);

// 示例3:使用不同的加密模式
string encrypted3 = plainText.AESEncrypt(
    key,
    iv,
    mode: CipherMode.CFB,           // 使用CFB模式
    padding: PaddingMode.PKCS7
);

2. DES加密

算法简介

DES(Data Encryption Standard)是一种传统的对称加密算法,使用56位有效密钥(8字节,含校验位)。由于密钥长度较短,安全性不如AES,仅用于兼容旧系统。

注意: 新项目建议使用AES代替DES。

主要方法

2.1 字符串加密
public static string DESEncrypt(
    this string plainText,                         // 待加密的明文,不能为空
    string key,                                     // 密钥,必须是8字节
    string iv,                                      // 初始化向量,必须是8字节
    CipherMode mode = CipherMode.CBC,               // 加密模式,默认CBC
    PaddingMode padding = PaddingMode.PKCS7,        // 填充模式,默认PKCS7
    Encoding encoding = null                        // 字符串编码,默认UTF8
)
2.2 字符串解密
public static string DESDecrypt(
    this string cipherText,                         // Base64编码的密文
    string key,                                     // 密钥,必须是8字节
    string iv,                                      // 初始化向量,必须是8字节
    CipherMode mode = CipherMode.CBC,               // 加密模式,必须与加密时一致
    PaddingMode padding = PaddingMode.PKCS7,        // 填充模式,必须与加密时一致
    Encoding encoding = null                        // 字符串编码,默认UTF8
)

调用示例

string plainText = "敏感数据";
string key = "12345678";  // 8字节密钥
string iv = "abcdefgh";   // 8字节IV

// 加密
string encrypted = plainText.DESEncrypt(key, iv);
Console.WriteLine($"DES加密: {encrypted}");

// 解密
string decrypted = encrypted.DESDecrypt(key, iv);
Console.WriteLine($"DES解密: {decrypted}");

// 使用字节数组
byte[] keyBytes = Encoding.UTF8.GetBytes(key);
byte[] ivBytes = Encoding.UTF8.GetBytes(iv);
byte[] dataBytes = Encoding.UTF8.GetBytes(plainText);

byte[] encryptedBytes = dataBytes.DESEncrypt(keyBytes, ivBytes);
byte[] decryptedBytes = encryptedBytes.DESDecrypt(keyBytes, ivBytes);

3. SM4加密(国密)

算法简介

SM4是中国国家密码管理局发布的分组密码算法,密钥长度为128位(16字节),用于替代DES/AES在商用密码领域的应用。

特点:

  • 符合中国商用密码标准
  • 128位密钥和分组长度
  • 支持多种工作模式
  • 基于BouncyCastle实现

主要方法

3.1 字符串加密
public static string SM4Encrypt(
    this string text,                               // 待加密的文本,不能为空
    string keyHex,                                  // 十六进制格式的密钥(32位十六进制=16字节)
    string ivHex = null,                            // 十六进制格式的IV(ECB模式可忽略)
    SM4Mode mode = SM4Mode.CBC,                     // 加密模式(默认CBC,禁用ECB)
    SM4Padding padding = SM4Padding.PKCS7Padding,   // 填充模式,默认PKCS7Padding
    Encoding encoding = null                        // 文本编码,默认UTF8
)
3.2 字符串解密
public static string SM4Decrypt(
    this string encryptedBase64,                    // Base64格式的加密文本
    string keyHex,                                  // 十六进制格式的密钥
    string ivHex = null,                            // 十六进制格式的IV(ECB模式可忽略)
    SM4Mode mode = SM4Mode.CBC,                     // 加密模式,必须与加密时一致
    SM4Padding padding = SM4Padding.PKCS7Padding,   // 填充模式,必须与加密时一致
    Encoding encoding = null                        // 文本编码,默认UTF8
)
3.3 生成密钥
public static string GenerateSM4KeyHex()            // 生成十六进制格式的随机密钥(32位十六进制)
public static string GenerateSM4IVHex()             // 生成十六进制格式的随机IV(32位十六进制)

枚举说明

SM4Mode(加密模式)

  • CBC - 密码块链接模式(推荐)
  • CTR - 计数器模式
  • CFB - 密码反馈模式
  • OFB - 输出反馈模式
  • ECB - 电子密码本模式(已禁用,不安全)

SM4Padding(填充模式)

  • PKCS7Padding - PKCS7填充(推荐)
  • ZeroPadding - 零填充
  • NoPadding - 无填充(CBC模式下使用NoPadding时,数据长度必须为16的倍数)

调用示例

// 示例1:生成密钥并加密
string keyHex = SM4Extensions.GenerateSM4KeyHex();
string ivHex = SM4Extensions.GenerateSM4IVHex();

string plainText = "国密SM4加密测试";
string encrypted = plainText.SM4Encrypt(keyHex, ivHex);
Console.WriteLine($"SM4加密: {encrypted}");

string decrypted = encrypted.SM4Decrypt(keyHex, ivHex);
Console.WriteLine($"SM4解密: {decrypted}");

// 示例2:使用固定密钥
string fixedKey = "0123456789abcdef0123456789abcdef";  // 32位十六进制(16字节)
string fixedIV = "fedcba9876543210fedcba9876543210";

string text = "商用密码数据";
string enc = text.SM4Encrypt(fixedKey, fixedIV);
string dec = enc.SM4Decrypt(fixedKey, fixedIV);

// 示例3:使用不同的工作模式
string encrypted_ctr = plainText.SM4Encrypt(
    keyHex,
    ivHex,
    mode: SM4Mode.CTR,  // CTR模式
    padding: SM4Padding.NoPadding  // 无填充
);

// 示例4:字节数组加密
byte[] keyBytes = SM4Extensions.GenerateSM4Key();
byte[] ivBytes = SM4Extensions.GenerateSM4IV();
byte[] dataBytes = Encoding.UTF8.GetBytes("数据");

byte[] encryptedBytes = dataBytes.SM4Encrypt(keyBytes, ivBytes);
byte[] decryptedBytes = encryptedBytes.SM4Decrypt(keyBytes, ivBytes);

非对称加密算法

4. RSA加密

算法简介

RSA是最广泛使用的非对称加密算法,基于大数分解的数学难题。使用公钥加密、私钥解密,适合加密小量数据(如对称密钥)。

特点:

  • 公钥加密,私钥解密
  • 支持数字签名
  • 密钥长度建议≥2048位
  • 支持PEM和XML两种密钥格式

主要方法

4.1 加密和解密
// 公钥加密
public static string RSAEncrypt(
    this string plainText,                          // 待加密的明文
    string publicKey,                               // 公钥字符串(PEM或XML格式)
    RsaKeyFormat keyFormat = RsaKeyFormat.Pem,      // 密钥格式(Pem或Xml),默认Pem
    RSAEncryptionPadding padding = null             // 填充模式,默认OaepSHA256
)

// 私钥解密
public static string RSADecrypt(
    this string encryptedTextBase64,                // Base64编码的密文
    string privateKey,                              // 私钥字符串(PEM或XML格式)
    RsaKeyFormat keyFormat = RsaKeyFormat.Pem,      // 密钥格式,必须与加密时一致
    RSAEncryptionPadding padding = null             // 填充模式,必须与加密时一致
)
4.2 生成密钥对
public static (string PublicKey, string PrivateKey) RSAGenerateKeyPair(
    int keySize = 2048,                             // 密钥长度(位),最小2048,默认2048
    RsaKeyFormat keyFormat = RsaKeyFormat.Pem       // 密钥格式,默认Pem
)

调用示例

// 示例1:生成密钥对并加密
var (publicKey, privateKey) = RSAExtensions.RSAGenerateKeyPair();

string plainText = "需要加密的数据";

// 使用公钥加密
string encrypted = plainText.RSAEncrypt(publicKey);
Console.WriteLine($"RSA加密: {encrypted}");

// 使用私钥解密
string decrypted = encrypted.RSADecrypt(privateKey);
Console.WriteLine($"RSA解密: {decrypted}");

// 示例2:使用XML格式密钥
var (pubKeyXml, priKeyXml) = RSAExtensions.RSAGenerateKeyPair(2048, RsaKeyFormat.Xml);
string enc = plainText.RSAEncrypt(pubKeyXml, RsaKeyFormat.Xml);
string dec = enc.RSADecrypt(priKeyXml, RsaKeyFormat.Xml);

// 示例3:加密字节数据
byte[] data = Encoding.UTF8.GetBytes("Binary Data");
string encryptedData = data.RSAEncrypt(publicKey);
byte[] decryptedData = encryptedData.RSADecryptData(privateKey);

// 示例4:使用不同的填充模式
string encrypted2 = plainText.RSAEncrypt(
    publicKey,
    RsaKeyFormat.Pem,
    RSAEncryptionPadding.OaepSHA256  // 显式指定填充模式
);

5. SM2加密(国密)

算法简介

SM2是中国国家密码管理局发布的椭圆曲线公钥密码算法,基于256位椭圆曲线,用于替代RSA在商用密码领域的应用。

特点:

  • 基于椭圆曲线密码学(ECC)
  • 256位密钥,安全性等同于RSA-3072
  • 支持加密和数字签名
  • 符合中国商用密码标准

主要方法

5.1 加密和解密
// 公钥加密
public static string SM2Encrypt(
    this string plainText,                          // 待加密的明文
    string publicKey,                               // Hex或Base64格式的公钥
    Encoding encoding = null                        // 文本编码,默认UTF8
)

// 私钥解密
public static string SM2Decrypt(
    this string cipherText,                         // Hex格式的密文
    string privateKey,                              // Hex或Base64格式的私钥
    Encoding encoding = null                        // 文本编码,默认UTF8
)
5.2 生成密钥对
public static (string PublicKey, string PrivateKey) SM2GenerateKeyPair()
// 返回:(Hex格式的公钥, Hex格式的私钥)

调用示例

// 示例1:生成密钥对并加密
var (publicKey, privateKey) = SM2Extensions.SM2GenerateKeyPair();
Console.WriteLine($"公钥: {publicKey}");
Console.WriteLine($"私钥: {privateKey}");

string plainText = "国密SM2加密测试数据";

// 使用公钥加密
string encrypted = plainText.SM2Encrypt(publicKey);
Console.WriteLine($"SM2加密: {encrypted}");

// 使用私钥解密
string decrypted = encrypted.SM2Decrypt(privateKey);
Console.WriteLine($"SM2解密: {decrypted}");

// 示例2:字节数组加密
byte[] data = Encoding.UTF8.GetBytes("Binary Data");
byte[] pubKeyBytes = Org.BouncyCastle.Utilities.Encoders.Hex.Decode(publicKey);
byte[] priKeyBytes = Org.BouncyCastle.Utilities.Encoders.Hex.Decode(privateKey);

byte[] encryptedBytes = data.SM2Encrypt(pubKeyBytes);
byte[] decryptedBytes = encryptedBytes.SM2Decrypt(priKeyBytes);

数字签名算法

6. RSA签名

算法简介

RSA数字签名用于验证数据完整性和来源可信性。使用私钥对数据签名,公钥验证签名。

主要方法

6.1 签名和验签
// 私钥签名
public static string RSASign(
    this string text,                               // 待签名的文本
    string privateKey,                              // 私钥字符串(PEM或XML格式)
    RsaKeyFormat keyFormat = RsaKeyFormat.Pem,      // 密钥格式,默认Pem
    HashAlgorithmName hashAlgorithm = null,         // 哈希算法,默认SHA256
    RSASignaturePadding padding = null              // 签名填充模式,默认PSS
)

// 公钥验签
public static bool RSAVerify(
    this string text,                               // 原始文本
    string signatureBase64,                         // Base64编码的签名
    string publicKey,                               // 公钥字符串(PEM或XML格式)
    RsaKeyFormat keyFormat = RsaKeyFormat.Pem,      // 密钥格式,必须与签名时一致
    HashAlgorithmName hashAlgorithm = null,         // 哈希算法,必须与签名时一致
    RSASignaturePadding padding = null              // 签名填充模式,必须与签名时一致
)

调用示例

// 生成密钥对
var (publicKey, privateKey) = RSAExtensions.RSAGenerateKeyPair();

string data = "需要签名的重要数据";

// 使用私钥签名
string signature = data.RSASign(privateKey);
Console.WriteLine($"签名: {signature}");

// 使用公钥验签
bool isValid = data.RSAVerify(signature, publicKey);
Console.WriteLine($"验签结果: {isValid}");

// 使用不同的哈希算法
string signature2 = data.RSASign(
    privateKey,
    hashAlgorithm: HashAlgorithmName.SHA512,
    padding: RSASignaturePadding.Pss
);

bool isValid2 = data.RSAVerify(
    signature2,
    publicKey,
    hashAlgorithm: HashAlgorithmName.SHA512,
    padding: RSASignaturePadding.Pss
);

7. SM2签名

算法简介

SM2数字签名是国密算法标准的一部分,基于椭圆曲线的数字签名算法。

主要方法

// 私钥签名
public static string SM2Sign(
    this string data,                               // 待签名的字符串
    string privateKey,                              // Hex或Base64格式的私钥
    string userId = null,                           // 用户ID字符串(可选,符合国密规范)
    Encoding encoding = null                        // 文本编码,默认UTF8
)

// 公钥验签
public static bool SM2Verify(
    this string data,                               // 原始字符串数据
    string signature,                               // Hex格式的签名
    string publicKey,                               // Hex或Base64格式的公钥
    string userId = null,                           // 用户ID字符串,必须与签名时一致
    Encoding encoding = null                        // 文本编码,默认UTF8
)

调用示例

// 生成密钥对
var (publicKey, privateKey) = SM2Extensions.SM2GenerateKeyPair();

string data = "需要签名的数据";

// 签名(不使用userId)
string signature = data.SM2Sign(privateKey);
Console.WriteLine($"SM2签名: {signature}");

// 验签
bool isValid = data.SM2Verify(signature, publicKey);
Console.WriteLine($"SM2验签: {isValid}");

// 使用userId签名(符合国密规范)
string userId = "user@example.com";
string signature2 = data.SM2Sign(privateKey, userId);
bool isValid2 = data.SM2Verify(signature2, publicKey, userId);

// 字节数组签名
byte[] dataBytes = Encoding.UTF8.GetBytes(data);
byte[] privateKeyBytes = Org.BouncyCastle.Utilities.Encoders.Hex.Decode(privateKey);
byte[] publicKeyBytes = Org.BouncyCastle.Utilities.Encoders.Hex.Decode(publicKey);

byte[] signatureBytes = dataBytes.SM2Sign(privateKeyBytes);
bool valid = dataBytes.SM2Verify(signatureBytes, publicKeyBytes);

8. DSA签名

算法简介

DSA(Digital Signature Algorithm)是美国联邦信息处理标准的数字签名算法,专门用于数字签名(不支持加密)。

主要方法

// 私钥签名
public static string DSASign(
    this string data,                               // 待签名的原始数据
    string privateKey,                              // 私钥字符串(PEM或XML格式)
    DsaKeyFormat keyFormat = DsaKeyFormat.Pem,      // 密钥格式,默认Pem
    HashAlgorithmName hashAlgorithm = null          // 哈希算法,默认SHA256
)

// 公钥验签
public static bool DSAVerify(
    this string data,                               // 原始数据
    string signatureBase64,                         // Base64编码的签名
    string publicKey,                               // 公钥字符串(PEM或XML格式)
    DsaKeyFormat keyFormat = DsaKeyFormat.Pem,      // 密钥格式,必须与签名时一致
    HashAlgorithmName hashAlgorithm = null          // 哈希算法,必须与签名时一致
)
生成密钥对
public static (string PublicKey, string PrivateKey) DSAGenerateKeyPair(
    int keySize = 2048,                             // 密钥大小(位),默认2048
    DsaKeyFormat keyFormat = DsaKeyFormat.Pem       // 密钥格式,默认Pem
)

调用示例

// 生成密钥对
var (publicKey, privateKey) = DSAExtensions.DSAGenerateKeyPair(2048);

string data = "待签名数据";

// 签名
string signature = data.DSASign(privateKey);
Console.WriteLine($"DSA签名: {signature}");

// 验签
bool isValid = data.DSAVerify(signature, publicKey);
Console.WriteLine($"DSA验签: {isValid}");

// 使用XML格式
var (pubXml, priXml) = DSAExtensions.DSAGenerateKeyPair(2048, DsaKeyFormat.Xml);
string sig = data.DSASign(priXml, DsaKeyFormat.Xml);
bool valid = data.DSAVerify(sig, pubXml, DsaKeyFormat.Xml);

// 字节数组签名
byte[] dataBytes = Encoding.UTF8.GetBytes(data);
string signature2 = dataBytes.DSASign(privateKey);
bool isValid2 = dataBytes.DSAVerify(signature2, publicKey);

哈希算法

9. SM3哈希(国密)

算法简介

SM3是中国国家密码管理局发布的密码杂凑算法,输出256位(32字节)哈希值,用于替代SHA-256在商用密码领域的应用。

特点:

  • 输出256位哈希值
  • 抗碰撞性强
  • 支持HMAC消息认证码

主要方法

9.1 哈希计算
// 字符串哈希
public static string SM3Hash(
    this string text,                               // 待计算哈希的文本
    Encoding encoding = null                        // 文本编码,默认UTF8
)
// 返回:十六进制格式的SM3哈希值

// 字节数组哈希
public static byte[] SM3Hash(this byte[] data)      // 返回SM3哈希结果(字节数组)
public static string SM3HashToHex(this byte[] data) // 返回十六进制格式的SM3哈希值
9.2 HMAC计算
// 字符串HMAC
public static string SM3Hmac(
    this string text,                               // 待计算的文本
    string keyHex,                                  // 十六进制格式的HMAC密钥
    Encoding encoding = null                        // 文本编码,默认UTF8
)
// 返回:十六进制格式的SM3-HMAC值

// 字节数组HMAC
public static byte[] SM3Hmac(
    this byte[] data,                               // 待计算的数据
    byte[] key                                      // HMAC密钥(字节数组)
)
// 返回:SM3-HMAC结果(字节数组)

public static string SM3HmacToHex(
    this byte[] data,                               // 待计算的数据
    byte[] key                                      // HMAC密钥
)
// 返回:十六进制格式的SM3-HMAC值

调用示例

// 示例1:计算字符串的SM3哈希
string text = "需要计算哈希的数据";
string hash = text.SM3Hash();
Console.WriteLine($"SM3哈希: {hash}");

// 示例2:计算字节数组的哈希
byte[] data = Encoding.UTF8.GetBytes("数据");
byte[] hashBytes = data.SM3Hash();
string hashHex = data.SM3HashToHex();
Console.WriteLine($"SM3哈希(Hex): {hashHex}");

// 示例3:计算HMAC-SM3
string hmacKey = "0123456789abcdef0123456789abcdef";
string hmac = text.SM3Hmac(hmacKey);
Console.WriteLine($"SM3-HMAC: {hmac}");

// 示例4:字节数组HMAC
byte[] keyBytes = Org.BouncyCastle.Utilities.Encoders.Hex.Decode(hmacKey);
byte[] hmacBytes = data.SM3Hmac(keyBytes);
string hmacHex = data.SM3HmacToHex(keyBytes);

// 示例5:文件哈希计算
byte[] fileData = File.ReadAllBytes("document.pdf");
string fileHash = fileData.SM3HashToHex();
Console.WriteLine($"文件SM3哈希: {fileHash}");

文档版本: 1.0 最后更新: 2025-12-05

results matching ""

    No results matching ""