Skip to content

Instantly share code, notes, and snippets.

@dukz

dukz/TripleDES Secret

Created September 26, 2013 12:59
Show Gist options
  • Save dukz/7cc5121f04371bb4d9ee to your computer and use it in GitHub Desktop.
Save dukz/7cc5121f04371bb4d9ee to your computer and use it in GitHub Desktop.
public static string Encrypt(string input, string key)
{
byte[] inputArray = UTF8Encoding.UTF8.GetBytes(input);
TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key);
tripleDES.Mode = CipherMode.ECB;
tripleDES.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tripleDES.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
tripleDES.Clear();
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
public static string Decrypt(string input, string key)
{
byte[] inputArray = Convert.FromBase64String(input);
TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key);
tripleDES.Mode = CipherMode.ECB;
tripleDES.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tripleDES.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
tripleDES.Clear();
return UTF8Encoding.UTF8.GetString(resultArray);
}
@dukz
Copy link
Author

dukz commented Sep 26, 2013

I tried doing this, but I'm always getting a "OpenSSL::Cipher::CipherError: key length too short" error.

def encrypt(input, enc_key)
  cipher = OpenSSL::Cipher::Cipher.new("des-ede3")
  cipher.encrypt
  cipher.key = enc_key
  result = cipher.update(input) + cipher.final
  Base64.encode64(result)
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment