Skip to content

Instantly share code, notes, and snippets.

@CipherLab
Created July 11, 2014 13:10
Show Gist options
  • Save CipherLab/e63def9b4541dbbbc1e0 to your computer and use it in GitHub Desktop.
Save CipherLab/e63def9b4541dbbbc1e0 to your computer and use it in GitHub Desktop.
Simple encryption/decryption
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
public class Encryption
{
public static string hashpass(string password)
{
SHA1Managed hasher = new SHA1Managed();
byte[] passwordBytes = General.StringToByteArray(password);
byte[] passwordHash = hasher.ComputeHash(passwordBytes);
return Convert.ToBase64String(passwordHash, 0, passwordHash.Length);
}
public static string EncryptString(string Message, string Passphrase)
{
byte[] Results;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
// Step 1. We hash the passphrase using MD5
// We use the MD5 hash generator as the result is a 128 bit byte array
// which is a valid length for the TripleDES encoder we use below
//MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
SHA256CryptoServiceProvider HashProvider = new SHA256CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));
// Step 2. Create a new TripleDESCryptoServiceProvider object
AesCryptoServiceProvider TDESAlgorithm = new AesCryptoServiceProvider();
//TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
// Step 3. Setup the encoder
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
// Step 4. Convert the input string to a byte[]
byte[] DataToEncrypt = UTF8.GetBytes(Message);
// Step 5. Attempt to encrypt the string
try
{
ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
}
finally
{
// Clear the TripleDes and Hashprovider services of any sensitive information
TDESAlgorithm.Clear();
HashProvider.Clear();
}
// Step 6. Return the encrypted string as a base64 encoded string
string result = Convert.ToBase64String(Results);
Console.WriteLine(result.Length);
return result;
}
public static string DecryptString(string Message, string Passphrase)
{
byte[] Results;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
// Step 1. We hash the passphrase using MD5
// We use the MD5 hash generator as the result is a 128 bit byte array
// which is a valid length for the TripleDES encoder we use below
SHA256CryptoServiceProvider HashProvider = new SHA256CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));
// Step 2. Create a new TripleDESCryptoServiceProvider object
AesCryptoServiceProvider TDESAlgorithm = new AesCryptoServiceProvider();
// Step 3. Setup the decoder
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
// Step 4. Convert the input string to a byte[]
byte[] DataToDecrypt = Convert.FromBase64String(Message);
// Step 5. Attempt to decrypt the string
try
{
ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
}
catch
{
return ("Invalid Password");
}
finally
{
// Clear the TripleDes and Hashprovider services of any sensitive information
TDESAlgorithm.Clear();
HashProvider.Clear();
}
// Step 6. Return the decrypted string in UTF8 format
return UTF8.GetString(Results);
}
//ByteArrayToString
public static string encryptStringToString_AesManaged(string plainText, string password)
{
return General.ByteArrayToString(encryptStringToBytes_AesManaged(plainText, password));
}
public static byte[] encryptStringToBytes_AesManaged(string plainText, string password)
{
string hashedpass = hashpass(password);
if (hashedpass.Length < 48)
{
hashedpass = hashedpass.PadRight(48, '0');
}
byte[] byteHash = General.StringToByteArray(hashedpass);
byte[] Key = new byte[32];
byte[] IV = new byte[16];
for (int i = 0; i < 32; i++)
{
Key[i] = byteHash[i];
}
int x = 0;
for (int i = 32; i < 48; i++)
{
IV[x] = byteHash[i];
x++;
}
// Check arguments.
string key1 = System.Text.Encoding.UTF8.GetString(Key, 0, Key.Length);
string iv1 = System.Text.Encoding.UTF8.GetString(IV, 0, IV.Length);
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");
// Declare the streams used
// Declare the AesManaged object
// used to encrypt the data.
AesManaged AesManagedAlg = null;
// Declare the bytes used to hold the
// encrypted data.
byte[] encrypted = null;
try
{
// Create an AesManaged object
// with the specified key and IV.
AesManagedAlg = new AesManaged();
AesManagedAlg.Key = Key;
AesManagedAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = AesManagedAlg.CreateEncryptor(AesManagedAlg.Key, AesManagedAlg.IV);
// to encrypt to an in memory
// array of bytes.
//MemoryStream msEncrypt = null;
//CryptoStream csEncrypt = null;
//StreamWriter swEncrypt = null;
// 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);
// Clear the AesManaged object.
if (AesManagedAlg != null)
AesManagedAlg.Clear();
return msEncrypt.ToArray();
}
}
}
}
finally
{
// Clean things up.
// Close the streams.
//if (swEncrypt != null)
// swEncrypt.Close();
//if (csEncrypt != null)
// csEncrypt.Close();
//if (msEncrypt != null)
// msEncrypt.Close();
}
// Return the encrypted bytes from the memory stream.
}
public static string GetEncryptedPass(string Message, string Password, int length, bool allow_special)
{
string result = "";
result = hashpass(Message + Password);
if (!allow_special)
{
string temp = "";
for (int i = 0; i < result.Length; i++)
{
if (char.IsLetterOrDigit(result, i))
{
temp += result[i];
}
}
result = temp;
}
else
{
}
if (result.Length > length)
{
result = result.Substring(0, length);
}
return result;
}
//public static string GetEncryptedPass(string Message, string Password, int length, bool allow_special)
//{
// string result = "";
// byte[] encrypted = Encryption.encryptStringToBytes_AesManaged(Message, Password);
// bool second_run = false;
// for (int i = 0; i < encrypted.Length; i++)
// {
// int encval = encrypted[i];
// if (encval > 127)
// {
// encval = encval / 2;
// encrypted[i] = Convert.ToByte(encval);
// }
// if (encval < 33)
// {
// encval = encval * 2;
// encrypted[i] = Convert.ToByte(encval);
// }
// int num_min = 48;
// int num_max = 57;
// if (allow_special)
// {
// num_min = 33;
// num_max = 64;
// }
// if ((encrypted[i] >= num_min && encrypted[i] <= num_max) || (encrypted[i] >= 65 && encrypted[i] <= 90) || (encrypted[i] >= 97 && encrypted[i] <= 122))
// {
// result += System.Text.Encoding.UTF8.GetString(encrypted, i, 1);
// }
// else
// {
// if (second_run)
// {
// second_run = false;
// result += encrypted[i].ToString();
// }
// }
// if (i == encrypted.Length - 1)
// {
// if (result.Length < length)
// {
// second_run = true;
// i = 0;
// }
// }
// }
// if (result.Length > length)
// {
// result = result.Substring(0, length);
// }
// return result;
//}
public static string decryptStringFromBytes_AesManaged(string cipherText, string password)
{
return decryptStringFromBytes_AesManaged(General.StringToByteArray(cipherText), password);
}
public static string decryptStringFromBytes_AesManaged(byte[] cipherText, string password)
{
string hashedpass = hashpass(password);
if (hashedpass.Length < 48)
{
hashedpass = hashedpass.PadRight(48, '0');
}
byte[] byteHash = General.StringToByteArray(hashedpass);
byte[] Key = new byte[32];
byte[] IV = new byte[16];
for (int i = 0; i < 32; i++)
{
Key[i] = byteHash[i];
}
int x = 0;
for (int i = 32; i < 48; i++)
{
IV[x] = byteHash[i];
x++;
}
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
// TDeclare the streams used
// to decrypt to an in memory
// array of bytes.
MemoryStream msDecrypt = null;
CryptoStream csDecrypt = null;
StreamReader srDecrypt = null;
// Declare the AesManaged object
// used to decrypt the data.
AesManaged AesManagedAlg = null;
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
try
{
// Create an AesManaged object
// with the specified key and IV.
AesManagedAlg = new AesManaged();
AesManagedAlg.Key = Key;
AesManagedAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = AesManagedAlg.CreateDecryptor(AesManagedAlg.Key, AesManagedAlg.IV);
// Create the streams used for decryption.
msDecrypt = new MemoryStream(cipherText);
csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
srDecrypt = new StreamReader(csDecrypt);
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
catch
{
return "Invalid Password";
}
finally
{
// Clean things up.
// Close the streams.
if (srDecrypt != null)
srDecrypt.Close();
if (csDecrypt != null)
csDecrypt.Close();
if (msDecrypt != null)
msDecrypt.Close();
// Clear the AesManaged object.
if (AesManagedAlg != null)
AesManagedAlg.Clear();
}
return plaintext;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment