您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在C# Web API中处理数据加密和解密,可以使用多种加密算法。以下是一个使用AES加密和解密的示例:
System.Security.Cryptography
命名空间中的Aes
类:using System.Security.Cryptography;
public static string Encrypt(string data, string key)
{
byte[] clearBytes = Encoding.Unicode.GetBytes(data);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes("YourSalt", new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
data = Convert.ToBase64String(ms.ToArray());
}
}
return data;
}
public static string Decrypt(string data, string key)
{
byte[] cipherBytes = Convert.FromBase64String(data);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes("YourSalt", new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
data = Encoding.Unicode.GetString(ms.ToArray());
}
}
return data;
}
[HttpPost]
public IHttpActionResult EncryptData([FromBody] string data)
{
string encryptedData = Encrypt(data, "YourKey");
return Ok(encryptedData);
}
[HttpPost]
public IHttpActionResult DecryptData([FromBody] string data)
{
string decryptedData = Decrypt(data, "YourKey");
return Ok(decryptedData);
}
请注意,这个示例使用了AES加密算法和Rfc2898DeriveBytes类来生成密钥和初始化向量(IV)。你可以根据需要选择其他加密算法。同时,确保在实际应用中使用安全的密钥和盐值。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。