重要前提
安装AI Skills的关键前提是:必须科学上网,且开启TUN模式,这一点至关重要,直接决定安装能否顺利完成,在此郑重提醒三遍:科学上网,科学上网,科学上网。查看完整安装教程 →
cryptography by melodic-software/claude-code-plugins
npx skills add https://github.com/melodic-software/claude-code-plugins --skill cryptography安全实施密码学操作的全面指南,涵盖加密算法、密码哈希、TLS 和密钥管理。
在以下情况下使用此技能:
| 算法 | 类型 | 密钥长度 | 使用场景 | 状态 |
|---|---|---|---|---|
| AES-256-GCM | 对称 | 256 位 | 数据加密 | ✅ 推荐 |
| ChaCha20-Poly1305 | 对称 | 256 位 | 数据加密(移动端) | ✅ 推荐 |
| RSA-OAEP | 非对称 | 2048+ 位 | 密钥交换 | ✅ 推荐 |
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
| ECDH (P-256) | 非对称 | 256 位 | 密钥协商 | ✅ 推荐 |
| X25519 | 非对称 | 256 位 | 密钥协商 | ✅ 推荐 |
| DES | 对称 | 56 位 | 无 | ❌ 已弃用 |
| 3DES | 对称 | 168 位 | 仅限遗留系统 | ⚠️ 避免使用 |
| Blowfish | 对称 | 32-448 位 | 无 | ⚠️ 避免使用 |
| 算法 | 类型 | 密钥长度 | 使用场景 | 状态 |
|---|---|---|---|---|
| Ed25519 | EdDSA | 256 位 | 签名 | ✅ 推荐 |
| ECDSA (P-256) | ECC | 256 位 | 签名,JWT | ✅ 推荐 |
| RSA-PSS | RSA | 2048+ 位 | 签名 | ✅ 推荐 |
| RSA PKCS#1 v1.5 | RSA | 2048+ 位 | 遗留签名 | ⚠️ 请改用 PSS |
| 算法 | 输出长度 | 使用场景 | 状态 |
|---|---|---|---|
| SHA-256 | 256 位 | 通用哈希 | ✅ 推荐 |
| SHA-384 | 384 位 | 更高安全性 | ✅ 推荐 |
| SHA-512 | 512 位 | 最高安全性 | ✅ 推荐 |
| SHA-3-256 | 256 位 | SHA-2 的替代方案 | ✅ 推荐 |
| BLAKE2b | 256-512 位 | 快速哈希 | ✅ 推荐 |
| MD5 | 128 位 | 无(已破解) | ❌ 切勿使用 |
| SHA-1 | 160 位 | 无(已破解) | ❌ 切勿使用 |
切勿使用通用哈希函数(SHA-256、MD5)处理密码。
| 算法 | 推荐度 | 内存密集型 | 备注 |
|---|---|---|---|
| Argon2id | ✅ 最佳 | 是 | PHC 竞赛获胜者,推荐用于新系统 |
| bcrypt | ✅ 良好 | 否 | 广泛支持,久经考验 |
| scrypt | ✅ 良好 | 是 | 良好但调优复杂 |
| PBKDF2 | ⚠️ 可接受 | 否 | NIST 批准,但易受 GPU 攻击 |
using Konscious.Security.Cryptography;
using System.Security.Cryptography;
using System.Text;
/// <summary>
/// Argon2id 密码哈希器,采用 OWASP 2023 推荐参数。
/// </summary>
public static class Argon2PasswordHasher
{
private const int DegreeOfParallelism = 4;
private const int MemorySize = 65536; // 64 MB
private const int Iterations = 3;
private const int HashLength = 32;
private const int SaltLength = 16;
/// <summary>
/// 使用 Argon2id 哈希密码。
/// </summary>
public static string Hash(string password)
{
var salt = RandomNumberGenerator.GetBytes(SaltLength);
var hash = ComputeHash(password, salt);
// 返回 PHC 格式:$argon2id$v=19$m=65536,t=3,p=4$salt$hash
return $"$argon2id$v=19$m={MemorySize},t={Iterations},p={DegreeOfParallelism}${Convert.ToBase64String(salt)}${Convert.ToBase64String(hash)}";
}
/// <summary>
/// 根据存储的哈希值验证密码。
/// </summary>
public static bool Verify(string storedHash, string password)
{
var parts = ParseHash(storedHash);
if (parts is null) return false;
var computedHash = ComputeHash(password, parts.Value.Salt);
return CryptographicOperations.FixedTimeEquals(computedHash, parts.Value.Hash);
}
private static byte[] ComputeHash(string password, byte[] salt)
{
using var argon2 = new Argon2id(Encoding.UTF8.GetBytes(password))
{
Salt = salt,
DegreeOfParallelism = DegreeOfParallelism,
MemorySize = MemorySize,
Iterations = Iterations
};
return argon2.GetBytes(HashLength);
}
private static (byte[] Salt, byte[] Hash)? ParseHash(string storedHash)
{
// 解析 PHC 格式:$argon2id$v=19$m=...,t=...,p=...$salt$hash
var parts = storedHash.Split('$');
if (parts.Length < 6) return null;
var salt = Convert.FromBase64String(parts[4]);
var hash = Convert.FromBase64String(parts[5]);
return (salt, hash);
}
}
// 用法
var hash = Argon2PasswordHasher.Hash("user_password");
// 返回:$argon2id$v=19$m=65536,t=3,p=4$...
if (Argon2PasswordHasher.Verify(hash, "user_password"))
{
// 密码有效
}
using BCrypt.Net;
// 哈希密码(工作因子 12 = 2^12 次迭代)
var passwordHash = BCrypt.Net.BCrypt.HashPassword("user_password", workFactor: 12);
// 验证密码
if (BCrypt.Net.BCrypt.Verify("user_password", passwordHash))
{
Console.WriteLine("Password valid");
}
| 算法 | 最低要求 | 推荐值 | 高安全性 |
|---|---|---|---|
| Argon2id | t=2, m=19MB | t=3, m=64MB | t=4, m=128MB |
| bcrypt | 10 | 12 | 14 |
| scrypt | N=2^14 | N=2^16 | N=2^18 |
| PBKDF2 | 310,000 | 600,000 | 1,000,000 |
有关详细的密码哈希指南: 请参阅 密码哈希参考
using System.Security.Cryptography;
/// <summary>
/// AES-256-GCM 加密工具。
/// </summary>
public static class AesGcmEncryption
{
private const int NonceSize = 12; // 96 位
private const int TagSize = 16; // 128 位
private const int KeySize = 32; // 256 位
/// <summary>
/// 使用 AES-256-GCM 加密数据。返回 nonce + 密文 + tag。
/// </summary>
public static byte[] Encrypt(ReadOnlySpan<byte> plaintext, ReadOnlySpan<byte> key)
{
var nonce = RandomNumberGenerator.GetBytes(NonceSize);
var ciphertext = new byte[plaintext.Length];
var tag = new byte[TagSize];
using var aes = new AesGcm(key, TagSize);
aes.Encrypt(nonce, plaintext, ciphertext, tag);
// 组合:nonce + 密文 + tag
var result = new byte[NonceSize + ciphertext.Length + TagSize];
nonce.CopyTo(result.AsSpan(0, NonceSize));
ciphertext.CopyTo(result.AsSpan(NonceSize));
tag.CopyTo(result.AsSpan(NonceSize + ciphertext.Length));
return result;
}
/// <summary>
/// 使用 AES-256-GCM 解密数据。输入为 nonce + 密文 + tag。
/// </summary>
public static byte[] Decrypt(ReadOnlySpan<byte> combined, ReadOnlySpan<byte> key)
{
var nonce = combined[..NonceSize];
var ciphertext = combined[NonceSize..^TagSize];
var tag = combined[^TagSize..];
var plaintext = new byte[ciphertext.Length];
using var aes = new AesGcm(key, TagSize);
aes.Decrypt(nonce, ciphertext, tag, plaintext);
return plaintext;
}
/// <summary>
/// 生成安全的 256 位密钥。
/// </summary>
public static byte[] GenerateKey() => RandomNumberGenerator.GetBytes(KeySize);
}
// 用法
var key = AesGcmEncryption.GenerateKey();
var encrypted = AesGcmEncryption.Encrypt("sensitive data"u8, key);
var decrypted = AesGcmEncryption.Decrypt(encrypted, key);
using System.Security.Cryptography;
using System.Text;
/// <summary>
/// 使用 PBKDF2 从密码派生加密密钥。
/// </summary>
public static class KeyDerivation
{
private const int SaltSize = 16;
private const int KeySize = 32; // AES-256 的 256 位
private const int Iterations = 600000; // OWASP 2023 推荐
/// <summary>
/// 从密码派生加密密钥。返回 (key, salt)。
/// </summary>
public static (byte[] Key, byte[] Salt) DeriveKey(string password, byte[]? salt = null)
{
salt ??= RandomNumberGenerator.GetBytes(SaltSize);
var key = Rfc2898DeriveBytes.Pbkdf2(
password: Encoding.UTF8.GetBytes(password),
salt: salt,
iterations: Iterations,
hashAlgorithm: HashAlgorithmName.SHA256,
outputLength: KeySize
);
return (key, salt); // 将 salt 与加密数据一起存储
}
}
using System.Security.Cryptography;
/// <summary>
/// 使用 OAEP 填充的 RSA 加密。
/// </summary>
public static class RsaEncryption
{
/// <summary>
/// 生成 RSA 密钥对。至少使用 2048 位;长期安全使用 4096 位。
/// </summary>
public static RSA GenerateKeyPair(int keySizeInBits = 2048)
{
return RSA.Create(keySizeInBits);
}
/// <summary>
/// 使用公钥通过 OAEP-SHA256 加密。
/// </summary>
public static byte[] Encrypt(byte[] plaintext, RSA publicKey)
{
return publicKey.Encrypt(plaintext, RSAEncryptionPadding.OaepSHA256);
}
/// <summary>
/// 使用私钥通过 OAEP-SHA256 解密。
/// </summary>
public static byte[] Decrypt(byte[] ciphertext, RSA privateKey)
{
return privateKey.Decrypt(ciphertext, RSAEncryptionPadding.OaepSHA256);
}
}
// 用法
using var rsa = RsaEncryption.GenerateKeyPair(4096);
var publicKey = rsa.ExportRSAPublicKey();
var ciphertext = RsaEncryption.Encrypt(plaintext, rsa);
var decrypted = RsaEncryption.Decrypt(ciphertext, rsa);
using System.Security.Cryptography;
/// <summary>
/// Ed25519 数字签名(通过带曲线的 ECDsa)。
/// 注意:.NET 10 具有原生 Ed25519 支持。
/// </summary>
public static class DigitalSignatures
{
/// <summary>
/// 创建 ECDSA 密钥对(P-256,广泛支持)。
/// </summary>
public static ECDsa CreateEcdsaKeyPair()
{
return ECDsa.Create(ECCurve.NamedCurves.nistP256);
}
/// <summary>
/// 使用 ECDSA-SHA256 签名消息。
/// </summary>
public static byte[] Sign(byte[] message, ECDsa privateKey)
{
return privateKey.SignData(message, HashAlgorithmName.SHA256);
}
/// <summary>
/// 验证签名。
/// </summary>
public static bool Verify(byte[] message, byte[] signature, ECDsa publicKey)
{
return publicKey.VerifyData(message, signature, HashAlgorithmName.SHA256);
}
}
// 用法
using var ecdsa = DigitalSignatures.CreateEcdsaKeyPair();
var signature = DigitalSignatures.Sign(message, ecdsa);
if (DigitalSignatures.Verify(message, signature, ecdsa))
{
Console.WriteLine("Signature valid");
}
else
{
Console.WriteLine("Signature invalid");
}
有关详细的算法选择指南: 请参阅 算法选择指南
# Nginx TLS 配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305;
ssl_prefer_server_ciphers off;
# HSTS(HTTP 严格传输安全)
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
# OCSP 装订
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4 valid=300s;
| 版本 | 状态 | 备注 |
|---|---|---|
| TLS 1.3 | ✅ 必需 | 最佳安全性,改进的性能 |
| TLS 1.2 | ✅ 可接受 | 使用适当的密码套件仍安全 |
| TLS 1.1 | ❌ 已弃用 | 自 2020 年起已禁用 |
| TLS 1.0 | ❌ 已弃用 | 存在重大漏洞 |
| SSL 3.0 | ❌ 已破解 | POODLE 攻击 |
| SSL 2.0 | ❌ 已破解 | 许多漏洞 |
有关详细的 TLS 配置: 请参阅 TLS 配置指南
┌─────────────────────────────────────┐
│ 主密钥 (KEK) │ <- 存储在 HSM 或 KMS 中
│ - 加密所有其他密钥 │
└──────────────────┬──────────────────┘
│
┌───────────┴───────────┐
▼ ▼
┌──────────────┐ ┌──────────────┐
│ 数据密钥 1 │ │ 数据密钥 2 │ <- 使用 KEK 加密
│ (DEK) │ │ (DEK) │
└──────────────┘ └──────────────┘
/// <summary>
/// 支持自动轮换的密钥管理器。
/// </summary>
public sealed class KeyManager(IKmsClient kmsClient) : IDisposable
{
private static readonly TimeSpan RotationPeriod = TimeSpan.FromDays(90);
private string? _currentKeyId;
private DateTime? _keyExpiry;
private readonly SemaphoreSlim _lock = new(1, 1);
/// <summary>
/// 获取当前加密密钥,如果需要则进行轮换。
/// </summary>
public async Task<string> GetCurrentKeyAsync(CancellationToken cancellationToken = default)
{
await _lock.WaitAsync(cancellationToken);
try
{
if (NeedsRotation())
{
await RotateKeyAsync(cancellationToken);
}
return _currentKeyId!;
}
finally
{
_lock.Release();
}
}
private bool NeedsRotation() =>
_keyExpiry is null || DateTime.UtcNow > _keyExpiry;
private async Task RotateKeyAsync(CancellationToken cancellationToken)
{
// 在 KMS 中创建新密钥
var newKey = await kmsClient.CreateKeyAsync(
description: $"Data key created {DateTime.UtcNow:O}",
keyUsage: KeyUsage.EncryptDecrypt,
cancellationToken: cancellationToken
);
_currentKeyId = newKey.KeyId;
_keyExpiry = DateTime.UtcNow.Add(RotationPeriod);
// 保留旧密钥用于解密(不要立即删除)
// 使用旧密钥加密的数据仍然可以解密
}
public void Dispose() => _lock.Dispose();
}
// KMS 客户端接口(为 Azure Key Vault、AWS KMS 等实现)
public interface IKmsClient
{
Task<KmsKey> CreateKeyAsync(string description, KeyUsage keyUsage, CancellationToken cancellationToken);
}
public enum KeyUsage { EncryptDecrypt, SignVerify }
public sealed record KmsKey(string KeyId, DateTime CreatedAt);
using System.Security.Cryptography;
// 用于密码学用途 - 始终使用这些
var secureRandomBytes = RandomNumberGenerator.GetBytes(32); // 32 个随机字节
var secureRandomHex = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)); // 64 个十六进制字符
var secureRandomUrl = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32))
.Replace('+', '-').Replace('/', '_').TrimEnd('='); // URL 安全的 base64
// 用于范围内的随机整数(例如,令牌、OTP)
var randomInt = RandomNumberGenerator.GetInt32(100000, 999999); // 6 位 OTP
// 切勿用于密码学
var random = new Random();
random.Next(); // 非密码学安全 - 仅用于游戏/模拟
当前的非对称算法(RSA、ECDSA、ECDH)易受量子计算机攻击。
| 算法 | 类型 | 状态 |
|---|---|---|
| ML-KEM (Kyber) | 密钥封装 | ✅ 已标准化 |
| ML-DSA (Dilithium) | 数字签名 | ✅ 已标准化 |
| SLH-DSA (SPHINCS+) | 数字签名 | ✅ 已标准化 |
// 结合经典和后量子算法
// 如果任一算法被破解,另一种仍能提供安全性
// 密钥交换:X25519 + ML-KEM-768
// 签名:ECDSA P-256 + ML-DSA-65
// .NET 10+ 将包含 ML-KEM 和 ML-DSA 支持
// 在此之前,使用 BouncyCastle 等库处理 PQ 算法
// 这在过渡期间提供了深度防御:
// 1. 经典算法处理当前威胁
// 2. PQ 算法防范未来的量子攻击
// 3. 组合密钥材料确保任一算法被攻破时的安全性
您需要什么密码学操作?
RandomNumberGenerator.GetBytes() 或 RandomNumberGenerator.GetInt32()| 技能 | 关系 |
|---|---|
authentication-patterns | 使用密码学处理 JWT、会话 |
secrets-management | 加密密钥的安全存储 |
secure-coding | 通用的安全实现模式 |
最后更新: 2025-12-26
每周安装数
53
仓库
GitHub 星标数
40
首次出现
Jan 24, 2026
安全审计
安装于
opencode44
codex42
claude-code36
github-copilot35
cursor35
gemini-cli35
Comprehensive guidance for implementing cryptographic operations securely, covering encryption algorithms, password hashing, TLS, and key management.
Use this skill when:
| Algorithm | Type | Key Size | Use Case | Status |
|---|---|---|---|---|
| AES-256-GCM | Symmetric | 256 bits | Data encryption | ✅ Recommended |
| ChaCha20-Poly1305 | Symmetric | 256 bits | Data encryption (mobile) | ✅ Recommended |
| RSA-OAEP | Asymmetric | 2048+ bits | Key exchange | ✅ Recommended |
| ECDH (P-256) | Asymmetric | 256 bits | Key agreement | ✅ Recommended |
| X25519 | Asymmetric | 256 bits | Key agreement | ✅ Recommended |
| DES | Symmetric | 56 bits | None | ❌ Deprecated |
| 3DES | Symmetric | 168 bits | Legacy only | ⚠️ Avoid |
| Blowfish | Symmetric | 32-448 bits | None | ⚠️ Avoid |
| Algorithm | Type | Key Size | Use Case | Status |
|---|---|---|---|---|
| Ed25519 | EdDSA | 256 bits | Signatures | ✅ Recommended |
| ECDSA (P-256) | ECC | 256 bits | Signatures, JWT | ✅ Recommended |
| RSA-PSS | RSA | 2048+ bits | Signatures | ✅ Recommended |
| RSA PKCS#1 v1.5 | RSA | 2048+ bits | Legacy signatures | ⚠️ Use PSS instead |
| Algorithm | Output Size | Use Case | Status |
|---|---|---|---|
| SHA-256 | 256 bits | General hashing | ✅ Recommended |
| SHA-384 | 384 bits | Higher security | ✅ Recommended |
| SHA-512 | 512 bits | Highest security | ✅ Recommended |
| SHA-3-256 | 256 bits | Alternative to SHA-2 | ✅ Recommended |
| BLAKE2b | 256-512 bits | Fast hashing | ✅ Recommended |
| MD5 | 128 bits | None (broken) | ❌ Never use |
| SHA-1 | 160 bits | None (broken) | ❌ Never use |
Never use general-purpose hash functions (SHA-256, MD5) for passwords.
| Algorithm | Recommended | Memory-Hard | Notes |
|---|---|---|---|
| Argon2id | ✅ Best | Yes | Winner of PHC, recommended for new systems |
| bcrypt | ✅ Good | No | Widely supported, proven |
| scrypt | ✅ Good | Yes | Good but complex to tune |
| PBKDF2 | ⚠️ Acceptable | No | NIST approved, but GPU-vulnerable |
using Konscious.Security.Cryptography;
using System.Security.Cryptography;
using System.Text;
/// <summary>
/// Argon2id password hasher with OWASP 2023 recommended parameters.
/// </summary>
public static class Argon2PasswordHasher
{
private const int DegreeOfParallelism = 4;
private const int MemorySize = 65536; // 64 MB
private const int Iterations = 3;
private const int HashLength = 32;
private const int SaltLength = 16;
/// <summary>
/// Hash password with Argon2id.
/// </summary>
public static string Hash(string password)
{
var salt = RandomNumberGenerator.GetBytes(SaltLength);
var hash = ComputeHash(password, salt);
// Return in PHC format: $argon2id$v=19$m=65536,t=3,p=4$salt$hash
return $"$argon2id$v=19$m={MemorySize},t={Iterations},p={DegreeOfParallelism}${Convert.ToBase64String(salt)}${Convert.ToBase64String(hash)}";
}
/// <summary>
/// Verify password against stored hash.
/// </summary>
public static bool Verify(string storedHash, string password)
{
var parts = ParseHash(storedHash);
if (parts is null) return false;
var computedHash = ComputeHash(password, parts.Value.Salt);
return CryptographicOperations.FixedTimeEquals(computedHash, parts.Value.Hash);
}
private static byte[] ComputeHash(string password, byte[] salt)
{
using var argon2 = new Argon2id(Encoding.UTF8.GetBytes(password))
{
Salt = salt,
DegreeOfParallelism = DegreeOfParallelism,
MemorySize = MemorySize,
Iterations = Iterations
};
return argon2.GetBytes(HashLength);
}
private static (byte[] Salt, byte[] Hash)? ParseHash(string storedHash)
{
// Parse PHC format: $argon2id$v=19$m=...,t=...,p=...$salt$hash
var parts = storedHash.Split('$');
if (parts.Length < 6) return null;
var salt = Convert.FromBase64String(parts[4]);
var hash = Convert.FromBase64String(parts[5]);
return (salt, hash);
}
}
// Usage
var hash = Argon2PasswordHasher.Hash("user_password");
// Returns: $argon2id$v=19$m=65536,t=3,p=4$...
if (Argon2PasswordHasher.Verify(hash, "user_password"))
{
// Password valid
}
using BCrypt.Net;
// Hash password (work factor 12 = 2^12 iterations)
var passwordHash = BCrypt.Net.BCrypt.HashPassword("user_password", workFactor: 12);
// Verify password
if (BCrypt.Net.BCrypt.Verify("user_password", passwordHash))
{
Console.WriteLine("Password valid");
}
| Algorithm | Minimum | Recommended | High Security |
|---|---|---|---|
| Argon2id | t=2, m=19MB | t=3, m=64MB | t=4, m=128MB |
| bcrypt | 10 | 12 | 14 |
| scrypt | N=2^14 | N=2^16 | N=2^18 |
| PBKDF2 | 310,000 | 600,000 | 1,000,000 |
For detailed password hashing guidance: See Password Hashing Reference
using System.Security.Cryptography;
/// <summary>
/// AES-256-GCM encryption utilities.
/// </summary>
public static class AesGcmEncryption
{
private const int NonceSize = 12; // 96 bits
private const int TagSize = 16; // 128 bits
private const int KeySize = 32; // 256 bits
/// <summary>
/// Encrypt data with AES-256-GCM. Returns nonce + ciphertext + tag.
/// </summary>
public static byte[] Encrypt(ReadOnlySpan<byte> plaintext, ReadOnlySpan<byte> key)
{
var nonce = RandomNumberGenerator.GetBytes(NonceSize);
var ciphertext = new byte[plaintext.Length];
var tag = new byte[TagSize];
using var aes = new AesGcm(key, TagSize);
aes.Encrypt(nonce, plaintext, ciphertext, tag);
// Combine: nonce + ciphertext + tag
var result = new byte[NonceSize + ciphertext.Length + TagSize];
nonce.CopyTo(result.AsSpan(0, NonceSize));
ciphertext.CopyTo(result.AsSpan(NonceSize));
tag.CopyTo(result.AsSpan(NonceSize + ciphertext.Length));
return result;
}
/// <summary>
/// Decrypt data with AES-256-GCM. Input is nonce + ciphertext + tag.
/// </summary>
public static byte[] Decrypt(ReadOnlySpan<byte> combined, ReadOnlySpan<byte> key)
{
var nonce = combined[..NonceSize];
var ciphertext = combined[NonceSize..^TagSize];
var tag = combined[^TagSize..];
var plaintext = new byte[ciphertext.Length];
using var aes = new AesGcm(key, TagSize);
aes.Decrypt(nonce, ciphertext, tag, plaintext);
return plaintext;
}
/// <summary>
/// Generate a secure 256-bit key.
/// </summary>
public static byte[] GenerateKey() => RandomNumberGenerator.GetBytes(KeySize);
}
// Usage
var key = AesGcmEncryption.GenerateKey();
var encrypted = AesGcmEncryption.Encrypt("sensitive data"u8, key);
var decrypted = AesGcmEncryption.Decrypt(encrypted, key);
using System.Security.Cryptography;
using System.Text;
/// <summary>
/// Derive encryption key from password using PBKDF2.
/// </summary>
public static class KeyDerivation
{
private const int SaltSize = 16;
private const int KeySize = 32; // 256 bits for AES-256
private const int Iterations = 600000; // OWASP 2023 recommendation
/// <summary>
/// Derive encryption key from password. Returns (key, salt).
/// </summary>
public static (byte[] Key, byte[] Salt) DeriveKey(string password, byte[]? salt = null)
{
salt ??= RandomNumberGenerator.GetBytes(SaltSize);
var key = Rfc2898DeriveBytes.Pbkdf2(
password: Encoding.UTF8.GetBytes(password),
salt: salt,
iterations: Iterations,
hashAlgorithm: HashAlgorithmName.SHA256,
outputLength: KeySize
);
return (key, salt); // Store salt with encrypted data
}
}
using System.Security.Cryptography;
/// <summary>
/// RSA encryption with OAEP padding.
/// </summary>
public static class RsaEncryption
{
/// <summary>
/// Generate RSA key pair. Use 2048 minimum; 4096 for long-term security.
/// </summary>
public static RSA GenerateKeyPair(int keySizeInBits = 2048)
{
return RSA.Create(keySizeInBits);
}
/// <summary>
/// Encrypt with public key using OAEP-SHA256.
/// </summary>
public static byte[] Encrypt(byte[] plaintext, RSA publicKey)
{
return publicKey.Encrypt(plaintext, RSAEncryptionPadding.OaepSHA256);
}
/// <summary>
/// Decrypt with private key using OAEP-SHA256.
/// </summary>
public static byte[] Decrypt(byte[] ciphertext, RSA privateKey)
{
return privateKey.Decrypt(ciphertext, RSAEncryptionPadding.OaepSHA256);
}
}
// Usage
using var rsa = RsaEncryption.GenerateKeyPair(4096);
var publicKey = rsa.ExportRSAPublicKey();
var ciphertext = RsaEncryption.Encrypt(plaintext, rsa);
var decrypted = RsaEncryption.Decrypt(ciphertext, rsa);
using System.Security.Cryptography;
/// <summary>
/// Ed25519 digital signatures (via ECDsa with curve).
/// Note: .NET 10 has native Ed25519 support.
/// </summary>
public static class DigitalSignatures
{
/// <summary>
/// Create ECDSA key pair (P-256, widely supported).
/// </summary>
public static ECDsa CreateEcdsaKeyPair()
{
return ECDsa.Create(ECCurve.NamedCurves.nistP256);
}
/// <summary>
/// Sign message with ECDSA-SHA256.
/// </summary>
public static byte[] Sign(byte[] message, ECDsa privateKey)
{
return privateKey.SignData(message, HashAlgorithmName.SHA256);
}
/// <summary>
/// Verify signature.
/// </summary>
public static bool Verify(byte[] message, byte[] signature, ECDsa publicKey)
{
return publicKey.VerifyData(message, signature, HashAlgorithmName.SHA256);
}
}
// Usage
using var ecdsa = DigitalSignatures.CreateEcdsaKeyPair();
var signature = DigitalSignatures.Sign(message, ecdsa);
if (DigitalSignatures.Verify(message, signature, ecdsa))
{
Console.WriteLine("Signature valid");
}
else
{
Console.WriteLine("Signature invalid");
}
For detailed algorithm selection guidance: See Algorithm Selection Guide
# Nginx TLS configuration
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305;
ssl_prefer_server_ciphers off;
# HSTS (HTTP Strict Transport Security)
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
# OCSP Stapling
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4 valid=300s;
| Version | Status | Notes |
|---|---|---|
| TLS 1.3 | ✅ Required | Best security, improved performance |
| TLS 1.2 | ✅ Acceptable | Still secure with proper ciphers |
| TLS 1.1 | ❌ Deprecated | Disabled since 2020 |
| TLS 1.0 | ❌ Deprecated | Major vulnerabilities |
| SSL 3.0 | ❌ Broken | POODLE attack |
| SSL 2.0 | ❌ Broken | Many vulnerabilities |
For detailed TLS configuration: See TLS Configuration Guide
┌─────────────────────────────────────┐
│ Master Key (KEK) │ <- Stored in HSM or KMS
│ - Encrypts all other keys │
└──────────────────┬──────────────────┘
│
┌───────────┴───────────┐
▼ ▼
┌──────────────┐ ┌──────────────┐
│ Data Key 1 │ │ Data Key 2 │ <- Encrypted with KEK
│ (DEK) │ │ (DEK) │
└──────────────┘ └──────────────┘
/// <summary>
/// Key manager with automatic rotation support.
/// </summary>
public sealed class KeyManager(IKmsClient kmsClient) : IDisposable
{
private static readonly TimeSpan RotationPeriod = TimeSpan.FromDays(90);
private string? _currentKeyId;
private DateTime? _keyExpiry;
private readonly SemaphoreSlim _lock = new(1, 1);
/// <summary>
/// Get current encryption key, rotating if needed.
/// </summary>
public async Task<string> GetCurrentKeyAsync(CancellationToken cancellationToken = default)
{
await _lock.WaitAsync(cancellationToken);
try
{
if (NeedsRotation())
{
await RotateKeyAsync(cancellationToken);
}
return _currentKeyId!;
}
finally
{
_lock.Release();
}
}
private bool NeedsRotation() =>
_keyExpiry is null || DateTime.UtcNow > _keyExpiry;
private async Task RotateKeyAsync(CancellationToken cancellationToken)
{
// Create new key in KMS
var newKey = await kmsClient.CreateKeyAsync(
description: $"Data key created {DateTime.UtcNow:O}",
keyUsage: KeyUsage.EncryptDecrypt,
cancellationToken: cancellationToken
);
_currentKeyId = newKey.KeyId;
_keyExpiry = DateTime.UtcNow.Add(RotationPeriod);
// Keep old keys for decryption (don't delete immediately)
// Data encrypted with old keys can still be decrypted
}
public void Dispose() => _lock.Dispose();
}
// KMS client interface (implement for Azure Key Vault, AWS KMS, etc.)
public interface IKmsClient
{
Task<KmsKey> CreateKeyAsync(string description, KeyUsage keyUsage, CancellationToken cancellationToken);
}
public enum KeyUsage { EncryptDecrypt, SignVerify }
public sealed record KmsKey(string KeyId, DateTime CreatedAt);
using System.Security.Cryptography;
// For cryptographic use - ALWAYS use these
var secureRandomBytes = RandomNumberGenerator.GetBytes(32); // 32 random bytes
var secureRandomHex = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)); // 64 hex chars
var secureRandomUrl = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32))
.Replace('+', '-').Replace('/', '_').TrimEnd('='); // URL-safe base64
// For random integers in a range (e.g., tokens, OTPs)
var randomInt = RandomNumberGenerator.GetInt32(100000, 999999); // 6-digit OTP
// NEVER use for cryptography
var random = new Random();
random.Next(); // NOT cryptographically secure - for games/simulations only
Current asymmetric algorithms (RSA, ECDSA, ECDH) are vulnerable to quantum computers.
| Algorithm | Type | Status |
|---|---|---|
| ML-KEM (Kyber) | Key Encapsulation | ✅ Standardized |
| ML-DSA (Dilithium) | Digital Signature | ✅ Standardized |
| SLH-DSA (SPHINCS+) | Digital Signature | ✅ Standardized |
// Combine classical and post-quantum algorithms
// If either is broken, the other still provides security
// Key exchange: X25519 + ML-KEM-768
// Signature: ECDSA P-256 + ML-DSA-65
// .NET 10+ will include ML-KEM and ML-DSA support
// Until then, use libraries like BouncyCastle for PQ algorithms
// This provides defense-in-depth during the transition period:
// 1. Classical algorithms handle today's threats
// 2. PQ algorithms protect against future quantum attacks
// 3. Combined key material ensures security if either is compromised
What cryptographic operation do you need?
RandomNumberGenerator.GetBytes() or RandomNumberGenerator.GetInt32()| Skill | Relationship |
|---|---|
authentication-patterns | Uses cryptography for JWT, sessions |
secrets-management | Secure storage of cryptographic keys |
secure-coding | General secure implementation patterns |
Last Updated: 2025-12-26
Weekly Installs
53
Repository
GitHub Stars
40
First Seen
Jan 24, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode44
codex42
claude-code36
github-copilot35
cursor35
gemini-cli35
Azure RBAC 权限管理工具:查找最小角色、创建自定义角色与自动化分配
154,300 周安装
OpenClaw 运维配置手册:AI助手网关诊断、修复与健康检查指南
2,400 周安装
Angular SSR 服务端渲染指南:v20+ 配置、水合与预渲染实战
2,400 周安装
TanStack Query v5 完全指南:React 数据管理、乐观更新、离线支持
2,500 周安装
LangGraph文档助手 - 智能获取LangChain文档索引,精准匹配实现指南与API参考
2,500 周安装
Replicas Agent 云工作空间编码代理指南:预览URL创建与跨服务配置
2,800 周安装
Hacker News API 使用指南:免费获取热门技术故事、评论和用户数据
2,600 周安装