【问题标题】:How can I encrypt the returned Json from an WebAPI controller如何加密从 WebAPI 控制器返回的 Json
【发布时间】:2012-09-11 13:14:10
【问题描述】:
我想在我的 asp.net MVC3 中开发一个 WebAPI 控制器,当它被调用时发送密码,它看起来类似于:
public string GetPasswordByUserId(int id)
{
var password = user.password.FirstOrDefault((u) => u.Id == id);
if (password == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return password;
}
但是如何加密返回的密码呢?
第二个问题:如果上面的action方法是在一个APIController里面,那么这是否意味着返回的字符串默认会被序列化为Json格式呢?
【问题讨论】:
标签:
asp.net-mvc-4
asp.net-web-api
【解决方案1】:
对于密码加密,您可以使用 RC2 的对称密钥,它使用 System.Security.Cryptography 命名空间/程序集。
byte[] toEncryptPwd = ASCIIEncoding.ASCII.GetBytes(strToEncrypt);
RC2 encPwd = RC2.Create("RC2");
strToEncrypt = Convert.ToBase64String(encPwd.CreateEncryptor(Key, rgbIV).TransformFinalBlock(toEncryptPwd, 0, toEncryptPwd.Length)); // strToEncrypt is now encrypted
encPwd.Clear();
// 您必须在代码或数据库中的某处硬编码密钥和 rgbIV。
为什么要以 json 格式返回密码?我没有按照设计和需要。
返回类型是否为json?
web-API 支持自动内容协商,这意味着如果使用 HTTP 请求 API 的客户端将接受标头设置为 Accept: application/json,则发送 json 响应,否则如果客户端将 Accept: application/xml 放入标头,则 API 返回xml 响应。
【解决方案2】:
我认为它需要在客户端解密?然后使用 HTTPS/SSL。
字符串不会自动序列化,或者至少序列化为您想要的对象。返回你想要序列化的类型,Web API 会自动序列化它。