HttpCookie 클래스는 봉인되어 있으며 상속받을 수 없지만 사용하기 쉬운 연산자 오버로드로 암호화 된 쿠키 클래스를 작성하면 쉽게 상속받을 수 있습니다.
public class EncryptedCookie
{
public string Name { get; set; }
public string Value { get; set; }
private byte[] encryptionKey;
private byte[] hmacKey;
public EncryptedCookie()
{
// setup keys
encryptionKey = Convert.FromBase64String(ConfigurationManager.AppSettings["encryption-key"]);
this.hmacKey = Convert.FromBase64String(ConfigurationManager.AppSettings["hmac-key"]);
}
public static explicit operator HttpCookie(EncryptedCookie cookie)
{
if (string.IsNullOrEmpty(cookie.Name))
{
throw new ArgumentException("Encrypted cookie must have a name");
}
if (string.IsNullOrEmpty(cookie.Value))
{
throw new ArgumentException("Encrypted cookie must have a value");
}
return new HttpCookie(cookie.Name, cookie.Encrypt());
}
public static explicit operator EncryptedCookie(HttpCookie cookie)
{
if (cookie == null)
{
return null;
}
var result = new EncryptedCookie { Name = cookie.Name };
result.Decrypt(cookie.Value);
return result;
}
private string Encrypt()
{
var encryptor = new Encryptor<AesEngine, Sha256Digest>(Encoding.UTF8, this.encryptionKey, this.hmacKey);
return encryptor.Encrypt(this.Value);
}
private void Decrypt(string cookieValue)
{
var encryptor = new Encryptor<AesEngine, Sha256Digest>(Encoding.UTF8, this.encryptionKey, this.hmacKey);
string plainText = encryptor.Decrypt(cookieValue);
if (string.IsNullOrEmpty(plainText))
{
throw new ArgumentException();
}
this.Value = plainText;
}
}
이 클래스를 사용하려면 내 암호기 클래스와 bouncycastle이 필요합니다. 이 클래스는 사용자가 입력 한 값의 암호화를 수행하고 이미 응답에있는 http 쿠키에서 설정할 때 암호 해독을 수행합니다. HMAC는 쿠키 값을 변경하지 않았 음을 확인하기 위해 자동으로 IV를 생성합니다. 두 개의 별도 키가 필요합니다. 하나는 HMAC 용이고 다른 하나는 암호화 용입니다. 암호화 시스템에서 가장 중요한 부분이므로 현명하게 생성하십시오.
encryptor 클래스는 Encrypt and decrypt a string에서 찾을 수 있습니다. 또는 회사에서 특별히 사용하는 것이 있으면 무엇이든 사용할 수 있습니다. 마지막으로
단순히 사용하는 암호화 된 쿠키를 만들어 응답에 추가 :
EncryptedCookie cookie = new EncryptedCookie { Name = "MyCookie", Value = "Hide this!" };
Response.Cookies.Add((HttpCookie)cookie);
당신은 단순히 암호화 된 쿠키로 다시 쿠키를 캐스팅 해독 할 :
var cookie = (EncryptedCookie)Request.Cookies["MyCookie"];
Response.Write(cookie.Value);
당신은 할 수 기존의 Cookie 클래스에서 확장 메소드를 사용해보십시오. –
이것이 웹 API에 존재한다는 것을 알고 있습니다. 아마도 MVC에 맞게 조정할 수 있습니까? http://www.asp.net/web-api/overview/working-with-http/http-cookies –