Skip to content

Instantly share code, notes, and snippets.

@corytodd
Last active August 29, 2015 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save corytodd/8726512 to your computer and use it in GitHub Desktop.
Save corytodd/8726512 to your computer and use it in GitHub Desktop.
internal static string Decrypt(byte[] key,string input)
{
if (input == null || input.Length <= 0)
throw new ArgumentNullException("input");
if (key == null || key.Length <= 0)
throw new ArgumentNullException("Key");
var un64byte = Convert.FromBase64String(input);
if (un64byte.Length < 16)
return ""; // Too short
//Pluck out the IV bytes (first 16 bytes)
var IV = un64byte.Take(16).ToArray();
//All that remains is the actual data
var cipherText = un64byte.Skip(16).Take(un64byte.Length - 16).ToArray();
using (RijndaelManaged aes = new RijndaelManaged())
{
aes.Key = Key;
aes.IV = IV;
aes.Mode = CipherMode.CBC;
//!!!Note that you have to have knowledge of the original length to strip padding
aes.Padding = PaddingMode.Zeros;
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
string plaintext = "";
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
func encrypt(key []byte, text string) string {
blockSize := aes.BlockSize
if len(text)%blockSize != 0 {
text += strings.Repeat("0", blockSize-len(text)%blockSize)
}
plaintext := []byte(text)
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
panic(err)
}
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)
return base64.StdEncoding.EncodeToString(ciphertext)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment