Created
November 16, 2015 13:49
-
-
Save lukasz-madon/53a4a89a738ffb7c85e7 to your computer and use it in GitHub Desktop.
Generate CSRF token
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Generates AntiForgery Tokens | |
/// </summary> | |
public static class AntiForgeryTokensGenerator | |
{ | |
private const string ConstantSalt = "b8YagDpYwB"; | |
private static readonly RandomNumberGenerator CryptoRandomDataGenerator = new RNGCryptoServiceProvider(); | |
// buffer for random string with 32 bytes of entropy | |
private static readonly int Length = 32; | |
/// <summary> | |
/// Generates token from seed. If seed is null, random string us used. | |
/// </summary> | |
/// <param name="seed"></param> | |
/// <returns></returns> | |
public static string GenerateToken(string seed) | |
{ | |
if (seed == null) | |
{ | |
var buffer = new byte[Length]; | |
CryptoRandomDataGenerator.GetBytes(buffer); | |
seed = Convert.ToBase64String(buffer); | |
} | |
using (var sha = SHA256.Create()) | |
{ | |
var computedHash = sha.ComputeHash(Encoding.Unicode.GetBytes(seed + ConstantSalt)); | |
var cookieFriendlyHash = Convert.ToBase64String(computedHash); | |
return cookieFriendlyHash; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment