Created
May 2, 2013 20:06
-
-
Save Eibwen/5504981 to your computer and use it in GitHub Desktop.
Trying to make a nicer interface for obtaining encryption/hash stream
This file contains hidden or 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
void Main() | |
{ | |
Guid UserGuid = new Guid("99a2caf0-0c9b-4452-9313-ff6a1d9786fa"); | |
using (MemoryStream ms = new MemoryStream()) | |
using (Stream cs = BasicGoodEncrypt(UserGuid, "imalittleteapot", ms)) | |
{ | |
} | |
} | |
public Stream BasicGoodEncrypt(Guid UserGuid, string password, Stream outStream) | |
{ | |
SymmetricAlgorithm cryptoAlgo = GetCryptoAlgorithm<AesManaged>(password, UserGuid.ToByteArray()); | |
CryptoStream cs = new CryptoStream(outStream, cryptoAlgo.CreateEncryptor(), CryptoStreamMode.Write); | |
//TODO add HMAC stuff? | |
return cs; | |
} | |
public SymmetricAlgorithm GetCryptoAlgorithm<T>(string password, byte[] salt) | |
where T : SymmetricAlgorithm, new() | |
{ | |
SymmetricAlgorithm cryptAlgo = new T(); | |
//Use the UserGuid as the salt | |
DeriveBytes pdb = new Rfc2898DeriveBytes(password, salt); | |
// cryptAlgo.LegalKeySizes.Dump(); | |
// cryptAlgo.LegalBlockSizes.Dump(); | |
// cryptAlgo.Key.Dump(); | |
cryptAlgo.Key = pdb.GetBytes(cryptAlgo.LegalKeySizes[0].MaxSize / 8); | |
cryptAlgo.IV = pdb.GetBytes(cryptAlgo.LegalBlockSizes[0].MaxSize / 8); | |
return cryptAlgo; | |
} | |
public string SecureHash(Guid UserGuid, string plainText) | |
{ | |
return Convert.ToBase64String(SecureHash<SHA256Managed>(plainText, UserGuid.ToByteArray())); | |
} | |
public byte[] SecureHash<T>(string plainText, byte[] salt) | |
where T : HashAlgorithm, new() | |
{ | |
//Use a derive bytes algorithm to apply the salt | |
// I figure this should be far more secure than concatination, and slow down the process | |
// I have read debate on if this is secure enough to use as a stored password hash alone or not, | |
// I'll lean on the other side and also hash one specificly studied for that | |
DeriveBytes pdb = new Rfc2898DeriveBytes(plainText, salt); | |
HashAlgorithm hash = new T(); | |
//Get some number of bytes from the derived bytes | |
//TODO put this number, or some version identifyer into the output string somehow | |
byte[] saltedText = pdb.GetBytes(hash.HashSize / 8 * 4); //Get 4 times the length of the hash for the hell of it | |
//Then hash it with the chosen algorithm for good measure | |
return hash.ComputeHash(saltedText); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment