Simple example of image encryption and decryption in c# and save to different server.
////////////////////////////// Form Code ///////////////////////////////////////////////////////////////////
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//define in web.config file
string BaseAddress = ConfigurationManager.AppSettings["BaseAddress"];
string SyncPath= ConfigurationManager.AppSettings["SyncPath"];
private void button1_Click(object sender, EventArgs e)
{
try
{
btnSavePic.Enabled = false;
button1.Enabled = false;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(BaseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = new HttpResponseMessage();
byte[] mybytearray = null;
response = client.GetAsync("api/employee?EmployeeNo=" + textBox1.Text.Trim() + "&SyncPath=" + SyncPath).Result;
if (response.IsSuccessStatusCode)
{
mybytearray =
response.Content.ReadAsAsync<byte[]>().Result;
if (mybytearray.Count() > 0)
{
byte[] DecryPic =
DecryptBytes(mybytearray, "2BeMy", "EmpPicUpdate");
Image img1 =
byteArrayToImage(DecryPic);
pictureBox1.Image =
img1;
}
}
btnSavePic.Enabled = true;
button1.Enabled = true;
}
catch
{
btnSavePic.Enabled = true;
button1.Enabled = true;
}
}
public Image byteArrayToImage(byte[] byteArrayIn)
{
using (MemoryStream mStream = new MemoryStream(byteArrayIn))
{
return Image.FromStream(mStream);
}
}
public static byte[] DecryptBytes(byte[] encryptedBytes, string passPhrase, string saltValue)
{
RijndaelManaged RijndaelCipher = new RijndaelManaged();
RijndaelCipher.Mode = CipherMode.CBC;
byte[] salt = Encoding.ASCII.GetBytes(saltValue);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, salt, "SHA1", 2);
ICryptoTransform Decryptor =
RijndaelCipher.CreateDecryptor(password.GetBytes(32), password.GetBytes(16));
MemoryStream memoryStream = new MemoryStream(encryptedBytes);
CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
byte[] plainBytes = new byte[encryptedBytes.Length];
int DecryptedCount = cryptoStream.Read(plainBytes, 0,
plainBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return plainBytes;
}
public static byte[] EncryptBytes(byte[] inputBytes, string passPhrase, string saltValue)
{
RijndaelManaged RijndaelCipher = new RijndaelManaged();
RijndaelCipher.Mode = CipherMode.CBC;
byte[] salt = Encoding.ASCII.GetBytes(saltValue);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, salt, "SHA1", 2);
ICryptoTransform Encryptor =
RijndaelCipher.CreateEncryptor(password.GetBytes(32), password.GetBytes(16));
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);
cryptoStream.Write(inputBytes, 0,
inputBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] CipherBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
return CipherBytes;
}
public class Param
{
public byte[] EmpPic { get; set; }
public int EmpId { get; set; }
public string SyncParam { get; set; }
}
private void btnSavePic_Click(object sender, EventArgs e)
{
int employeeNo = 0;
if (!string.IsNullOrEmpty(textBox1.Text.Trim()))
{
employeeNo = Convert.ToInt32(textBox1.Text.Trim());
}
if (employeeNo > 0)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(BaseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = new HttpResponseMessage();
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "Images
(*.BMP;*.JPG;*.GIF,*.PNG,*.TIFF)|*.BMP;*.JPG;*.GIF;*.PNG;*.TIFF| All files
(*.*)|*.*";
openFileDialog1.FilterIndex =
2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream =
openFileDialog1.OpenFile()) != null)
{
btnSavePic.Enabled
= false;
button1.Enabled = false;
using (myStream)
{
// Insert code to read the stream here.
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read =
myStream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
byte[] EncyPic =
EncryptBytes(ms.ToArray(), "2BeMy", "EmpPicUpdate");
Param prm = new Param();
prm.EmpPic
= EncyPic;
prm.EmpId =
employeeNo;
prm.SyncParam = SyncPath;
response =
client.PostAsJsonAsync("api/employee", prm).Result;
if (response.IsSuccessStatusCode)
{
Image img1 =
byteArrayToImage(ms.ToArray());
pictureBox1.Image = img1;
}
btnSavePic.Enabled = true;
button1.Enabled = true;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original
error: " + ex.Message);
}
}
}
else
{
MessageBox.Show("EmployeeNo
is Required");
}
}
}
///////////////////////////////////////////// End Form Code /////////////////////////////////////////////////
///////////////////////////////////EmployeeController : ApiController/////////////////////////////////////
[HttpPost]
public bool SaveEmployeeImage(Param ms)
{
SQL obj = new SQL();
DataSet ds = new DataSet();
try
{
byte[] DecryPic = DecryptBytes(ms.EmpPic, "2BeMy", "EmpPicUpdate");
MemoryStream ms1 = new MemoryStream(DecryPic);
SaveFileOnDisk(ms1, ms.EmpId.ToString(),ms.SyncParam);
}
catch (Exception s)
{ throw (s); }
return true;
}
////////////////////////////////End////////////////////////////////////////////////
No comments:
Post a Comment