You need to enable JavaScript to run this app. C# .NET中BouncyCastle支持的短字符串快速较安全加密算法如何选择
优惠活动
大模型
产品
解决方案
定价
更多

C# .NET中BouncyCastle支持的短字符串快速较安全加密算法如何选择

适配方案推荐

直接推荐使用 AES-128 运行在CBC模式下,配合PKCS7填充,完全匹配你的所有需求,理由如下:

  • 性能表现最优:AES是当前全球范围内软硬件优化最成熟的对称加密算法,BouncyCastle为.NET场景提供的AES实现做了针对性性能优化,处理数千条10~30字符的短字符串耗时可以忽略,完全满足速度要求。
  • 实现逻辑极简:CBC模式不需要处理GCM模式所需的认证标签生成校验逻辑,仅需为每条待加密字符串生成1个独立的16字节随机IV,加密完成后将IV与密文拼接,再转Base64存储即可,加解密代码量极少。
  • 安全等级匹配:128位长度的AES密钥已达到中等安全防护要求,每条记录使用独立IV的规则可以彻底避免相同明文生成相同密文的特征泄露问题,适配密文存储到未加密文件的场景。
实现注意事项
  • 密钥长度可按需求选16字节(AES-128)、24字节(AES-192)、32字节(AES-256),中等安全场景选AES-128即可,性能优于更长密钥的版本。
  • IV不需要保密,每次加密生成的16字节随机IV直接拼接在密文前即可,解密时先解码Base64字符串,取前16字节作为IV,剩余内容作为密文解密即可。
  • BouncyCastle对应核心API调用路径:AesEngine → 包装为CbcBlockCipher → 包装为PaddedBufferedBlockCipher(使用PKCS7填充)即可完成加解密能力构造。
核心代码示例(C#)
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Paddings;
using Org.BouncyCastle.Crypto.Parameters;
using System.Security.Cryptography;

// 加密方法
public static string EncryptString(string plainText, byte[] key)
{
    // 生成16字节随机IV
    byte[] iv = new byte[16];
    RandomNumberGenerator.Fill(iv);
    
    // 初始化加密器
    IBlockCipher aesEngine = new AesEngine();
    CbcBlockCipher cbcMode = new CbcBlockCipher(aesEngine);
    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(cbcMode, new Pkcs7Padding());
    cipher.Init(true, new ParametersWithIV(new KeyParameter(key), iv));
    
    // 加密处理
    byte[] plainBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
    byte[] cipherBytes = cipher.DoFinal(plainBytes);
    
    // 拼接IV和密文后转Base64
    byte[] resultBytes = new byte[iv.Length + cipherBytes.Length];
    Buffer.BlockCopy(iv, 0, resultBytes, 0, iv.Length);
    Buffer.BlockCopy(cipherBytes, 0, resultBytes, iv.Length, cipherBytes.Length);
    return Convert.ToBase64String(resultBytes);
}

// 解密方法
public static string DecryptString(string base64CipherText, byte[] key)
{
    byte[] allBytes = Convert.FromBase64String(base64CipherText);
    // 拆分IV和密文
    byte[] iv = allBytes.Take(16).ToArray();
    byte[] cipherBytes = allBytes.Skip(16).ToArray();
    
    // 初始化解密器
    IBlockCipher aesEngine = new AesEngine();
    CbcBlockCipher cbcMode = new CbcBlockCipher(aesEngine);
    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(cbcMode, new Pkcs7Padding());
    cipher.Init(false, new ParametersWithIV(new KeyParameter(key), iv));
    
    // 解密处理
    byte[] plainBytes = cipher.DoFinal(cipherBytes);
    return System.Text.Encoding.UTF8.GetString(plainBytes);
}

内容的提问来源于stack exchange,提问作者DotNET Afficionado

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 23:03:03