Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A small program to encrypt/decrypt data from SmartStoreNET
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace SmartStoreCipher
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 3 && args[0].ToLower().Equals("decrypt"))
{
string encryptionPrivateKey = args[1];
string cipherText = args[2];
var tDESalg = new TripleDESCryptoServiceProvider();
tDESalg.Key = new ASCIIEncoding().GetBytes(encryptionPrivateKey.Substring(0, 16));
tDESalg.IV = new ASCIIEncoding().GetBytes(encryptionPrivateKey.Substring(8, 8));
byte[] buffer = Convert.FromBase64String(cipherText);
string plaintext = DecryptTextFromMemory(buffer, tDESalg.Key, tDESalg.IV);
Console.WriteLine("{0}", plaintext);
}
else if (args.Length == 3 && args[0].ToLower().Equals("encrypt"))
{
string encryptionPrivateKey = args[1];
string plaintext = args[2];
var tDESalg = new TripleDESCryptoServiceProvider();
tDESalg.Key = new ASCIIEncoding().GetBytes(encryptionPrivateKey.Substring(0, 16));
tDESalg.IV = new ASCIIEncoding().GetBytes(encryptionPrivateKey.Substring(8, 8));
byte[] cipherText = EncryptTextToMemory(plaintext, tDESalg.Key, tDESalg.IV);
Console.WriteLine("{0}", Convert.ToBase64String(cipherText));
}
else
{
Console.WriteLine("Usage:\nSmartStoreCipher.exe encrypt/decrypt key plaintext/ciphertext");
}
}
private static string DecryptTextFromMemory(byte[] data, byte[] key, byte[] iv)
{
using (var ms = new MemoryStream(data))
{
using (var cs = new CryptoStream(ms, new TripleDESCryptoServiceProvider().CreateDecryptor(key, iv), CryptoStreamMode.Read))
{
var sr = new StreamReader(cs, new UnicodeEncoding());
return sr.ReadLine();
}
}
}
private static byte[] EncryptTextToMemory(string data, byte[] key, byte[] iv)
{
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, new TripleDESCryptoServiceProvider().CreateEncryptor(key, iv), CryptoStreamMode.Write))
{
byte[] toEncrypt = new UnicodeEncoding().GetBytes(data);
cs.Write(toEncrypt, 0, toEncrypt.Length);
cs.FlushFinalBlock();
}
return ms.ToArray();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment