Skip to content

Instantly share code, notes, and snippets.

@joby-lol
Last active August 29, 2015 14:05
Show Gist options
  • Save joby-lol/2d79ec68e0c47376991f to your computer and use it in GitHub Desktop.
Save joby-lol/2d79ec68e0c47376991f to your computer and use it in GitHub Desktop.
Example in C# of encoding a string with AES, then getting it and its IV and an HMAC hash as useful strings. It's pieced together from bits of an actual project, and probably won't work quite right just copied and pasted. It should point you in the right direction if you're curious though. It's also of note that this was written for .NET 2.0, so …
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
string encryptionKey = "01010101010101010101010101010101";
string hmacKey = "01010101010101010101010101010101";
/*
USAGE
*/
//say we're encrypting JSON
string plaintext = "{your JSON data}";
//generate 16 byte initialization vector
byte[] IV = new byte[16];
Random random = new Random();
for (int i = 0; i < 16; i++) {
random.NextBytes(IV);
}
//get an encrypted byte array from encryptStringToBytes with the plaintext, key and IV
//encryption key above is
byte[] encryptedBytes = encryptStringToBytes(plaintext,stringToByteArray_hex(encryptionKey),IV);
//convert encrypted bytes into a base-64 string
string b64ciphertext = Convert.ToBase64String(encryptedBytes);
//generate HMAC string
string hmac = calculateHMAC(b64ciphertext);
//you'll also need to send the initialization vector as a string
string stringIV = Convert.ToBase64String(IV);
/*
SAMPLE CODE
*/
//encrypts a string using a given key and IV, outputs a byte array
//uses Rijndael, configured to match the AES standard
byte[] encryptStringToBytes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
byte[] encrypted;
// Create an Rijndael object
// with the specified key and IV.
using (Rijndael rijAlg = Rijndael.Create())
{
rijAlg.KeySize = 128;
rijAlg.BlockSize = 128;
rijAlg.Mode = CipherMode.CBC;
rijAlg.Key = Key;
rijAlg.IV = IV;
rijAlg.Padding = PaddingMode.Zeros;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
//makes an HMAC string using the hmacKey variable defined at the top
string calculateHMAC(string message)
{
var encoding = new System.Text.ASCIIEncoding();
byte[] keyByte = encoding.GetBytes(hmacKey);
byte[] messageBytes = encoding.GetBytes(message);
using (var hmacsha256 = new HMACSHA256(keyByte))
{
byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
return ByteArrayToString(hashmessage).ToLower();
}
}
//takes a string and turns it into a byte array, interpreting each two-character chunk as a hex number
public static byte[] stringToByteArray_hex(String hex)
{
int NumberChars = hex.Length/2;
byte[] bytes = new byte[NumberChars];
using (var sr = new StringReader(hex))
{
for (int i = 0; i < NumberChars; i++)
bytes[i] =
Convert.ToByte(new string(new char[2]{(char)sr.Read(), (char)sr.Read()}), 16);
}
return bytes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment