Last active
December 28, 2015 16:59
-
-
Save jkuemerle/7532705 to your computer and use it in GitHub Desktop.
Method to encrypt data and optionally HMAC it.
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
| public string Encrypt(string Data, string KeyName, Func<string> IntegrityFunction) | |
| { | |
| if (null != IntegrityFunction) | |
| Data = AddHMAC(Data, IntegrityFunction); | |
| var val = System.Text.UnicodeEncoding.Unicode.GetBytes(Data); | |
| using (var crypter = new System.Security.Cryptography.RijndaelManaged()) | |
| { | |
| var iv = new byte[crypter.BlockSize / 8].FillWithEntropy(); | |
| KeyInfo key = GetKeyInfo(KeyName, iv, crypter); | |
| byte[] encrypted; | |
| crypter.IV = iv; | |
| crypter.Key = key.KeyBytes; | |
| crypter.Mode = CipherMode.CBC; | |
| using (var encrypter = crypter.CreateEncryptor()) | |
| { | |
| using (var to = new MemoryStream()) | |
| { | |
| using (var writer = new CryptoStream(to, encrypter, CryptoStreamMode.Write)) | |
| { | |
| writer.Write(val, 0, val.Length); | |
| writer.FlushFinalBlock(); | |
| encrypted = to.ToArray(); | |
| } | |
| } | |
| } | |
| return string.Format("{0}\0{1}\0{2}", Convert.ToBase64String(iv), Convert.ToBase64String(encrypted), ComputeHMAC(encrypted,key.SecretBytes)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment