Connection String Decryption First 8 character has not decrypting true - c#

I have connection string encryption/decryption code in c#.net. But when i decrypt the encrypted string just first 8 character decrypting wrong the others are true. What can be the problem ?
I used that codes without Initialization Vector.
https://msdn.microsoft.com/en-us/library/ff649224.aspx
İts the DecryptTransformer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
namespace Encryption
{
internal class DecryptTransformer
{
private EncryptionAlgorithm algorithmID;
private byte[] initVec;
internal DecryptTransformer(EncryptionAlgorithm deCryptId)
{
algorithmID = deCryptId;
}
internal ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey/*,
byte[] initVec*/)
{
// Pick the provider.
switch (algorithmID)
{
case EncryptionAlgorithm.Des:
{
DES des = new DESCryptoServiceProvider();
des.Mode = CipherMode.CBC;
des.Key = bytesKey;
// des.IV = initVec;
return des.CreateDecryptor();
}
case EncryptionAlgorithm.TripleDes:
{
TripleDES des3 = new TripleDESCryptoServiceProvider();
des3.Mode = CipherMode.CBC;
return des3.CreateDecryptor(bytesKey, initVec);
}
case EncryptionAlgorithm.Rc2:
{
RC2 rc2 = new RC2CryptoServiceProvider();
rc2.Mode = CipherMode.CBC;
return rc2.CreateDecryptor(bytesKey, initVec);
}
case EncryptionAlgorithm.Rijndael:
{
Rijndael rijndael = new RijndaelManaged();
rijndael.Mode = CipherMode.CBC;
return rijndael.CreateDecryptor(bytesKey, initVec);
}
default:
{
throw new CryptographicException("Algorithm ID '" +
algorithmID +
"' not supported.");
}
}
} //end GetCryptoServiceProvider
internal byte[] IV
{
set { initVec = value; }
}
}
}
its Decryptor.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.IO;
namespace Encryption
{
public class Decryptor
{
private DecryptTransformer transformer;
private byte[] initVec;
public Decryptor(EncryptionAlgorithm algId)
{
transformer = new DecryptTransformer(algId);
}
public byte[] Decrypt(byte[] bytesData, byte[] bytesKey/*,
byte[] initVec*/)
{
//Set up the memory stream for the decrypted data.
MemoryStream memStreamDecryptedData = new MemoryStream();
//Pass in the initialization vector.
//transformer.IV = initVec;
ICryptoTransform transform =
transformer.GetCryptoServiceProvider(bytesKey/*,initVec*/);
CryptoStream decStream = new CryptoStream(memStreamDecryptedData,
transform,
CryptoStreamMode.Write);
try
{
decStream.Write(bytesData, 0, bytesData.Length);
}
catch(Exception ex)
{
throw new Exception("Error while writing encrypted data to the stream: \n"
+ ex.Message);
}
decStream.FlushFinalBlock();
decStream.Close();
// Send the data back.
return memStreamDecryptedData.ToArray();
} //end Decrypt
public byte[] IV
{
set { initVec = value; }
}
}
}
and Form part
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Encryption;
using System.Text;
using Microsoft.Win32;
namespace datareg
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
try
{
// Create the encryptor object, specifying 3DES as the
// encryption algorithm
Encryptor enc = new Encryptor(EncryptionAlgorithm.TripleDes);
// Get the connection string as a byte array
byte[] plainText =
Encoding.ASCII.GetBytes(txtConnectionString.Text);
byte[] key = Encoding.ASCII.GetBytes(txtKey.Text);
// Perform the encryption
byte[] cipherText = enc.Encrypt(plainText, key/*,enc.IV*/);
// Store the intialization vector, as this will be required
// for decryption
// txtInitializationVector.Text = Encoding.ASCII.GetString(enc.IV);
// Display the encrypted string
txtEncryptedString.Text = Convert.ToBase64String(cipherText);
}
catch (Exception ex)
{
MessageBox.Show("Exception encrypting: " + ex.Message,
"Encryption ");
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
// Set up the Decryptor object
Decryptor dec = new Decryptor(EncryptionAlgorithm.TripleDes);
// Set the Initialization Vector
dec.IV = Encoding.ASCII.GetBytes(txtInitializationVector.Text);
byte[] key = Encoding.ASCII.GetBytes(txtKey.Text);
// Perform the decryption
byte[] plainText = dec.Decrypt(Convert.FromBase64String(
txtEncryptedString.Text),
key/*,dec.IV*/);
// Display the decrypted string.
txtDecryptedString.Text = Encoding.ASCII.GetString(plainText);
}
catch (Exception ex)
{
MessageBox.Show("Exception decrypting. " + ex.Message,
"Encryption Test Harness");
}
}
private void button4_Click(object sender, EventArgs e)
{
// Create registry key and named values
RegistryKey rk = Registry.CurrentUser.OpenSubKey("Software",true);
rk = rk.CreateSubKey("TestApplication");
// Write encrypted string, initialization vector and key to the registry
rk.SetValue("connectionString",txtEncryptedString.Text);
//rk.SetValue("initVector",
// Encoding.ASCII.GetBytes(txtInitializationVector.Text));
rk.SetValue("key", Encoding.ASCII.GetBytes(txtKey.Text));
MessageBox.Show("The data has been successfully written to the registry");
}
}
}
its the ss

Related

AES decryption returning incorrect result

I'm trying to encrypt/decrypt Password , encrypt Password is work Fine
but decrypt Password returned wrong result.....
example:
password input : P#ssword
Password Encrypt : V????0B??y+?Em
Password Decrypt : �/T:/�b,<AI�)6 ... Here it should appear\ P#ssword
I get class from
https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.aesmanaged?view=netcore-3.1
my Code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Solution_Report
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
byte[] IV = Encoding.ASCII.GetBytes("9316FF86D31244AC");
byte[] Key = Encoding.ASCII.GetBytes("28FDDEF86DA4244ACCC0A4FE3B316F26");
private void Form1_Load(object sender, EventArgs e)
{
}
private void btn_Encrypt_Click(object sender, EventArgs e)
{
byte [] Encrypted_Pass_byte = AesExample.EncryptStringToBytes_Aes(txt_Password.Text, Key , IV);
txt_Password_Encrypted.Text = Encoding.ASCII.GetString(Encrypted_Pass_byte);
}
private void btn_decrypt_Click(object sender, EventArgs e)
{
byte[] Encrypted_Password = Encoding.ASCII.GetBytes(txt_Password_Encrypted.Text);
txt_Password_Decrpted.Text = AesExample.DecryptStringFromBytes_Aes(Encrypted_Password, Key, IV);
}
}
}
AesManaged Class
class AesExample
{
public static void en()
{
string original = "Here is some data to encrypt!";
// Create a new instance of the Aes
// class. This generates a new key and initialization
// vector (IV).
using (Aes myAes = Aes.Create())
{
// Encrypt the string to an array of bytes.
byte[] encrypted = EncryptStringToBytes_Aes(original, myAes.Key, myAes.IV);
// Decrypt the bytes to a string.
string roundtrip = DecryptStringFromBytes_Aes(encrypted, myAes.Key, myAes.IV);
//Display the original data and the decrypted data.
Console.WriteLine("Original: {0}", original);
Console.WriteLine("Round Trip: {0}", roundtrip);
}
}
public static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
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("IV");
byte[] encrypted;
// Create an Aes object
// with the specified key and IV.
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
aesAlg.Padding = PaddingMode.Zeros;
// Create an encryptor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (BinaryWriter swEncrypt = new BinaryWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
public static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
{
// 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("IV");
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an Aes object
// with the specified key and IV.
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
aesAlg.Padding = PaddingMode.Zeros;
// Create a decryptor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
}
display the encrypted bytes
private void btn_Encrypt_Click(object sender, EventArgs e)
{
byte [] Encrypted_Pass_byte = AesExample.EncryptStringToBytes_Aes(txt_Password.Text, Key , IV);
txt_Password_Encrypted.Text = Convert.ToBase64String(Encrypted_Pass_byte);
}
display the decrypted String
private void btn_decrypt_Click(object sender, EventArgs e)
{
var Encrypted_Password = Convert.FromBase64String(txt_Password_Encrypted.Text);
txt_Password_Decrpted.Text = AesExample.DecryptStringFromBytes_Aes(Encrypted_Password, Key, IV);
}
and using StreamWriter/Reader in Encrypting And Decrypting
Thanks for who helped me ..

C# - Problem with AES Decryption - always get null

I am trying to implement image steganography with LSB and everything works except decrypting.
There is my class responsible for encryption and decryption of strings below. Encrypting works fine but Decrypt method always returns null:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApp1
{
class Encryptor {
//text to encrypt or already decrypted
private String decryptedText = "";
//text to decrypt or already encrypted
private String encryptedText = "";
private String key = "";
public Encryptor setDecryptedText(String text)
{
decryptedText = text;
return this;
}
public Encryptor setEncryptedText(String text)
{
encryptedText = text;
return this;
}
public Encryptor setKey(String text)
{
key = text;
return this;
}
Byte[] getHash(Byte[] hash)
{
Byte[] newHash = new Byte[32];
for (int i = 0; i < 32; i++)
{
newHash[i] = hash[i];
}
return newHash;
}
Byte[] getIV(Byte[] hash)
{
Byte[] newHash = new Byte[16];
int j = 0;
for (int i = 32; i < 48; i++)
{
newHash[j++] = hash[i];
}
return newHash;
}
String EncryptAesManaged()
{
SHA512 shaM = new SHA512Managed();
Byte[] data = Encoding.UTF8.GetBytes(key);
Byte[] hash = shaM.ComputeHash(data);
try
{
return Encrypt(decryptedText, getHash(hash), getIV(hash));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return null;
}
String DecryptAesManaged()
{
SHA512 shaM = new SHA512Managed();
var data = Encoding.UTF8.GetBytes(key);
Byte[] hash = shaM.ComputeHash(data);
try
{
return Decrypt(Convert.FromBase64String(encryptedText), getHash(hash), getIV(hash));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return "";
}
String Encrypt(string plainText, byte[] Key, byte[] IV)
{
Byte[] encrypted;
using (RijndaelManaged aes = new RijndaelManaged())
{
aes.Mode = CipherMode.CBC;
aes.BlockSize = 128;
aes.KeySize = 256;
ICryptoTransform encryptor = aes.CreateEncryptor(Key, IV);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter sw = new StreamWriter(cs)) {
sw.Write(Encoding.UTF8.GetBytes(plainText));
cs.FlushFinalBlock();
encrypted = ms.ToArray();
}
}
}
aes.Clear();
}
return Convert.ToBase64String(encrypted);
}
string Decrypt(byte[] cipherText, byte[] Key, byte[] IV)
{
string plaintext = null;
using (RijndaelManaged aes = new RijndaelManaged())
{
aes.Mode = CipherMode.CBC;
aes.BlockSize = 128;
aes.KeySize = 256;
ICryptoTransform decryptor = aes.CreateDecryptor(Key, IV);
try
{
using (MemoryStream ms = new MemoryStream(cipherText))
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
using (StreamReader reader = new StreamReader(cs))
{
plaintext = reader.ReadToEnd(); //Here get null
}
aes.Clear();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return plaintext;
}
public String getEncrypted()
{
return EncryptAesManaged();
}
public String getDecrypted()
{
return DecryptAesManaged();
}
}
}
Why is Decrypt() returning null rather than the originally encrypted string?
You don't show how you use your Encryptor class, so your question doesn't quite include a Minimal, Complete, and Verifiable example. I was able to reproduce the problem with the following test harness:
public static void Test()
{
var key = "my key";
var plainText = "hello";
var encryptor = new Encryptor();
encryptor.setDecryptedText(plainText);
encryptor.setKey(key);
var encrypted = encryptor.getEncrypted();
Console.WriteLine(encrypted);
var deecryptor = new Encryptor();
deecryptor.setEncryptedText(encrypted);
deecryptor.setKey(key);
var decrypted = deecryptor.getDecrypted();
Console.WriteLine(decrypted);
Assert.IsTrue(plainText == decrypted);
}
Demo fiddle #1 here.
Given that, your code has 2 problems, both of which are actually in encryption rather than decryption.
Firstly, in Encrypt(string plainText, byte[] Key, byte[] IV), you are writing to the StreamWriter sw, then flushing the CryptoStream and returning the MemoryStream contents -- but you never flush or dispose sw, so its buffered contents are never forwarded to the underlying stream(s).
To fix this, your code should looks something like:
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter sw = new StreamWriter(cs))
{
sw.Write(Encoding.UTF8.GetBytes(plainText));
}
}
encrypted = ms.ToArray();
}
Now getDecrypted() no longer returns a null result -- but instead returns a wrong result of "System.Byte[]", as shown in demo fiddle #2 here.
Secondly, again in Encrypt(...), you are effectively encoding your plainText twice at this line:
sw.Write(Encoding.UTF8.GetBytes(plainText));
Encoding.UTF8.GetBytes(plainText) converts the plain text to a byte array, but the StreamWriter is also intended to do this job, converting strings to bytes and passing them to the underlying stream. So, since you are not passing a string to Write(), the overload that gets called is StreamWriter.Write(Object):
Writes the text representation of an object to the text string or stream by calling the ToString() method on that object.
Thus what actually gets encrypted is the ToString() value of a byte array, which is "System.Byte[]".
To fix this, simply remove the call to Encoding.UTF8.GetBytes(plainText) and write the string directly. Thus your Encrypt() method should now look like:
static String Encrypt(string plainText, byte[] Key, byte[] IV)
{
string encrypted;
using (var aes = new RijndaelManaged())
{
aes.Mode = CipherMode.CBC;
aes.BlockSize = 128;
aes.KeySize = 256;
ICryptoTransform encryptor = aes.CreateEncryptor(Key, IV);
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write, true))
{
using (var sw = new StreamWriter(cs))
{
sw.Write(plainText);
}
}
// Calling GetBuffer() avoids the extra allocation of ToArray().
encrypted = Convert.ToBase64String(ms.GetBuffer(), 0, checked((int)ms.Length));
}
aes.Clear();
}
return encrypted;
}
Demo fiddle #3 here that now passes successfully.
Disclaimer: this answer does not attempt to to review your code for security best practices such as secure setup of salt and IV.

3DES : Receive Different Byte Array of encoding String from Registry

Tool : Visual Studio 2012. Windows 7 64bit.
Keywords : C#,registry,Triple DES Encryption Decryption.
I have created one demo program to read and write (Encrypted string) to registry.
Concept behind this program is : I want to Encrypt and Decrypt Data using Triple DES(I have Used TripleDESCryptoServiceProvider Class.).After Encryption, encrypted byte array is stored in Registry as a string. Upto this, it work perfectly. But when I get this string from registry and convert it in byte array for decryption, the size of array is different and during encryption it display error :
Length of the data to decrypt is invalid.
Below is my code :
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;
namespace TripleDES_in_Memory
{
class Program
{
static void Main(string[] args)
{
try
{
using (RegistryKey key = Registry.CurrentUser.OpenSubKey("MyCompanyName\\"))
{
if (key != null)
{
object o = key.GetValue("TrialPeriod");
if (o != null)
{
string result = Convert.ToString(o);
byte[] Data = Encoding.UTF8.GetBytes(result);
BinaryFormatter bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, o);
byte[] narray = ms.ToArray();
}
TripleDESCryptoServiceProvider tDESalg = new TripleDESCryptoServiceProvider();
string keybyjaimesh = "MyEncryptKey";
tDESalg.Key = Encoding.UTF8.GetBytes(keybyjaimesh.PadRight(24, ' '));
string ipmanual = "ivmanual";
tDESalg.IV = Encoding.UTF8.GetBytes(ipmanual.PadRight(8, ' '));
byte[] iv = tDESalg.IV;
tDESalg.IV = iv;
string Final = DecryptTextFromMemory(Data, tDESalg.Key, tDESalg.IV); //decrypt
Console.WriteLine(Final);
}
}
else
{
TripleDESCryptoServiceProvider tDESalg = new TripleDESCryptoServiceProvider();
string sData = "aaaaaaaaaaaaaaaaaaaaaaaa";
DateTime today = DateTime.Today;
DateTime answer = today.AddDays(1);
string keybyjaimesh = "MyEncryptKey";
tDESalg.Key = Encoding.UTF8.GetBytes(keybyjaimesh.PadRight(24, ' '));
string ipmanual = "ivmanual";
tDESalg.IV = Encoding.UTF8.GetBytes(ipmanual.PadRight(8, ' '));
byte[] iv = tDESalg.IV;
byte[] Data = EncryptTextToMemory(sData, tDESalg.Key, tDESalg.IV);
Console.WriteLine("Encrypted data main function : " + System.Text.Encoding.UTF8.GetString(Data));
Microsoft.Win32.RegistryKey key1;
key1 = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("MyCompanyName");
key1.SetValue("TrialPeriod", System.Text.Encoding.UTF8.GetString(Data));
key1.SetValue("IV", System.Text.Encoding.UTF8.GetString(iv));
key1.Close();
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public static byte[] EncryptTextToMemory(string Data, byte[] Key, byte[] IV)
{
try
{
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream,
new TripleDESCryptoServiceProvider().CreateEncryptor(Key, IV),
CryptoStreamMode.Write);
byte[] toEncrypt = new ASCIIEncoding().GetBytes(Data);
string result = System.Text.Encoding.UTF8.GetString(toEncrypt);
Console.WriteLine("byte to array : " + result);
cStream.Write(toEncrypt, 0, toEncrypt.Length);
cStream.FlushFinalBlock();
byte[] ret = mStream.ToArray();
Console.WriteLine("Encrypted data : " + System.Text.Encoding.UTF8.GetString(ret));
cStream.Close();
mStream.Close();
return ret;
}
catch (CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
return null;
}
}
public static string DecryptTextFromMemory(byte[] Data, byte[] Key, byte[] IV)
{
try
{
MemoryStream msDecrypt = new MemoryStream(Data);
CryptoStream csDecrypt = new CryptoStream(msDecrypt,
new TripleDESCryptoServiceProvider().CreateDecryptor(Key, IV),
CryptoStreamMode.Read);
byte[] fromEncrypt = new byte[Data.Length];
csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
return new ASCIIEncoding().GetString(fromEncrypt);
}
catch (CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
return null;
}
}
}
}
Encrypted String in registry :
Please suggest your opinion on this.
How can I solve this?
I have Solved it.
I have store Encrypted string in registry after convert it in TOBase64String.
string base64 = Convert.ToBase64String(encrypted string);
For Decrypt, Get string using :
string encrypteddatafromregistry = (string)key.GetValue("TrialPeriod",typeof(String));
And then convert to 64 base string :
byte[] encoded = Convert.FromBase64String(encrypteddatafromregistry );
And apply this array to Decryption.

C# Rijndael Encryption not accepting any Key except "mykey123"

I found this script on http://www.codeproject.com/Articles/26085/File-Encryption-and-Decryption-in-C. It works fine when I use the static key // string password = #"myKey1234"; // Your Key Here. when I pass in a different key, it doesn't work string password = #keyPwd;. You can see in my code I'm passing key to function it is not working.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CSVEncrypts
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string inputFile = "";
string outputFilePath = "";
string oFilePathName = "";
// EncryptFile
private void EncryptFile(string inputFile, string outputFile,string keyPwd )
{
try
{
// string password = #"myKey123"; // Your Key Here
string password = #keyPwd;
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
string cryptFile = outputFile;
FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsCrypt,RMCrypto.CreateEncryptor(key, key),CryptoStreamMode.Write);
FileStream fsIn = new FileStream(inputFile, FileMode.Open);
int data;
while ((data = fsIn.ReadByte()) != -1)
cs.WriteByte((byte)data);
fsIn.Close();
cs.Close();
fsCrypt.Close();
}
catch
{
MessageBox.Show("Encryption failed!", "Error");
}
}
// Decrypt
private void DecryptFile(string inputFile, string outputFile, string keyPwd)
{
{
//string password = #"myKey123"; // Your Key Here
string password = #keyPwd; // Your Key Here
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateDecryptor(key, key),CryptoStreamMode.Read);
FileStream fsOut = new FileStream(outputFile, FileMode.Create);
int data;
while ((data = cs.ReadByte()) != -1)
fsOut.WriteByte((byte)data);
fsOut.Close();
cs.Close();
fsCrypt.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
if (inputFile != "")
{
oFilePathName = outputFilePath + "\\" + textBox1.Text;
EncryptFile(inputFile, oFilePathName,keytextBox.Text);
}
}
private void button2_Click(object sender, EventArgs e)
{
if (inputFile != "") ;
{
oFilePathName = outputFilePath + "\\" + textBox1.Text;
DecryptFile(inputFile, oFilePathName, keytextBox.Text);
}
}
private void button3_Click(object sender, EventArgs e)
{
OpenFileDialog InputOpenFileDialog1 = new OpenFileDialog();
if (InputOpenFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string strInfilename = InputOpenFileDialog1.FileName;
button3.Text = strInfilename;
inputFile = strInfilename;
outputFilePath = Path.GetDirectoryName(inputFile);
}
}
}
}
A key should only contain bits that are indistinguishable from random. An password encoded to bytes is not a key. Especially when using Unicode encoding (which should have been named UTF16LE) many of the bits are set to zero. That means that the "key" doesn't contain enough entropy as well.
To create a key from a password you should derive it using a Password Based Key Derivation Function (PBKDF). Probably the best way to do this in the current .NET Crypto API is to use the class Rfc2898DeriveBytes which implements PBKDF2. PBKDF2 is defined in RFC 2898: PKCS #5: Password-Based Cryptography Specification V2.0. You may want to read that if you want to do, well, password based encryption.
By Rijndael I assume you really mean AES (Advanced Encryption Standard), AES is a subset of Rijndael with a block size of 128-bits, that is what you need.
AES keys are 128, 192 or 256 bits, it is best not to use a string, if you have a string first run it through a key derivation function such as PBKDF2. Keys really should be a byte array, not a character string. Make the keys the exactly correct size, this is probably your problem.
CreateDecryptor takes two arguments, the key and the iv, don't also use the key for the iv, the iv is considered public.
It is not clear from the code, you will need to consult the documentation to see if the default mode is CBC and that PKCS#7 (PKCS#5 padding is used interchangeably) padding is enabled.
If you want a secure encryption "out of the box: use RNCryptor, there is a C# version. you will also get multi-language/platform interoperability.
Getting encryption security correct is not easy and it is easy to make a mistake that ruins the security.

Error on encrypt a message using Elliptic curve

when I encrypt a message using Elliptic curve by clicking on button1 several times (more than 10 times), I get the following error
index was outside the bounds of the array.
Code is given below:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DiffieHellmanMerkle;
using System.Security.Cryptography;
using System.IO;
namespace TestEllipticCurveDiffieHellman
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
byte[] SecretA = null;
byte[] SecretB = null;
try
{
ECDiffieHellmanMerkle A = new ECDiffieHellmanMerkle(ECDHAlgorithm.ECDH_384);
ECDiffieHellmanMerkle B = new ECDiffieHellmanMerkle(ECDHAlgorithm.ECDH_384);
A.KeyDerivationFunction = ECDHKeyDerivationFunction.HASH;
B.KeyDerivationFunction = ECDHKeyDerivationFunction.HASH;
A.HashAlgorithm = DerivedKeyHashAlgorithm.SHA256_ALGORITHM;
B.HashAlgorithm = DerivedKeyHashAlgorithm.SHA256_ALGORITHM;
SecretA = A.RetrieveSecretKey(B.PublicKey);
SecretB = B.RetrieveSecretKey(A.PublicKey);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message,"Win32 Error Message");
}
//Alice encrypts the message with her secret key
string SecretMessage = plain.Text;// "The owl of Minerva only flies at dusk.";
byte[] SecretMessageByteArray = Encoding.Unicode.GetBytes(SecretMessage);
string IVString = "initialV";
byte[] IVByteArray = Encoding.Unicode.GetBytes(IVString);
RijndaelManaged rijndael = new RijndaelManaged();
ICryptoTransform encryptor = rijndael.CreateEncryptor(SecretA, IVByteArray);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor,CryptoStreamMode.Write);
cryptoStream.Write(SecretMessageByteArray, 0, SecretMessageByteArray.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherText = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
Encrypted.Text = Encoding.Unicode.GetString(cipherText);
/* string strcipherTextUni = Encoding.Unicode.GetString(cipherText);
MessageBox.Show("Encrypted Unicode = " + strcipherTextUni.ToString());*/
//Bob decrypts the message with his secret key
ICryptoTransform decryptor = rijndael.CreateDecryptor(SecretB, IVByteArray);
memoryStream = new MemoryStream(cipherText);
cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
byte[] clearText = new byte[cipherText.Length];
int clearTextByteSize = cryptoStream.Read(clearText, 0, clearText.Length);
memoryStream.Close();
cryptoStream.Close();
this.Decrypted.Text = Encoding.Unicode.GetString(clearText, 0, clearTextByteSize);
}
}
}
Encrypted.Text = Encoding.Unicode.GetString(cipherText); is likely the culprit.
Random bytes are not character encoding. It might be that an unknown encoding is translated into a substitution or no character at all here. This will happen now and then (as encrypted text is indistinguishable from random).
Use base 64 encoding of the ciphertext instead, there are oodles of examples of how to do this on stackoverflow. Luckily for you the base 64 encoding/decoding is build into the .net API (are you receiving that, Oracle?).

Categories

Resources