C# Using a Class In My Winforms Application - c#

Hello everyone I am developing a chat application for school. Its in C#, a language I have never worked with before. Now I have a winform that needs to encrypt some data, I have the encryption code in is own class but for some reason I can't use any of the functions in the cipher class.
Here is a very simplified version of the code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data;
using System.Security.Cryptography;
namespace WindowsFormsApplication2
{
public class SimpleAES
{
// Change these keys
private byte[] Key = { 123, 217, 19, 11, 24, 26, 85, 45, 114, 184, 27, 162, 37, 112, 222, 209, 241, 24, 175, 144, 173, 53, 196, 29, 24, 26, 17, 218, 131, 236, 53, 209 };
private byte[] Vector = { 146, 64, 191, 111, 23, 3, 113, 119, 231, 121, 252, 112, 79, 32, 114, 156 };
private ICryptoTransform EncryptorTransform, DecryptorTransform;
private System.Text.UTF8Encoding UTFEncoder;
public SimpleAES()
{
//This is our encryption method
RijndaelManaged rm = new RijndaelManaged();
//Create an encryptor and a decryptor using our encryption method, key, and vector.
EncryptorTransform = rm.CreateEncryptor(this.Key, this.Vector);
DecryptorTransform = rm.CreateDecryptor(this.Key, this.Vector);
//Used to translate bytes to text and vice versa
UTFEncoder = new System.Text.UTF8Encoding();
}
/// -------------- Two Utility Methods (not used but may be useful) -----------
/// Generates an encryption key.
public byte[] Encrypt(string TextValue)
{
//Translates our text value into a byte array.
Byte[] bytes = UTFEncoder.GetBytes(TextValue);
//Used to stream the data in and out of the CryptoStream.
MemoryStream memoryStream = new MemoryStream();
/*
* We will have to write the unencrypted bytes to the stream,
* then read the encrypted result back from the stream.
*/
#region Write the decrypted value to the encryption stream
CryptoStream cs = new CryptoStream(memoryStream, EncryptorTransform, CryptoStreamMode.Write);
cs.Write(bytes, 0, bytes.Length);
cs.FlushFinalBlock();
#endregion
#region Read encrypted value back out of the stream
memoryStream.Position = 0;
byte[] encrypted = new byte[memoryStream.Length];
memoryStream.Read(encrypted, 0, encrypted.Length);
#endregion
//Clean up.
cs.Close();
memoryStream.Close();
return encrypted;
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
byte[] result = Encrypt(textBox1.Text);
}
}
}
When I throw this into visual studio the function call to Encrypt() is highlighted in red and the description it gives is the Encrypt does not exist in the current context.
I am much more experienced with C++ and I figured something like what I have would work, but I guess thats incorrect.
Any help would be most appreciated.

SimpleAES is not a static class, so you'll need to create an instance of it before you can call methods on it:
private void button1_Click(object sender, EventArgs e)
{
SimpleAES simpleAes = new SimpleAES();
byte[] result = simpleAes.Encrypt(textBox1.Text);
}

Make instance of SimpleAES like answer in #PoweredByOrange or change to static like #Bob or make extenstion method on a string like mine answer:
private void button1_Click(object sender, EventArgs e)
{
byte[] result = textBox1.Text.Encrypt();
}
public class Extensionmethods
{
public static byte[] Encrypt(this string TextValue)
{
//Your code here
}
}

Related

BouncyCastle: "mac check in GCM failed"

Throws exception: Org.BouncyCastle.Crypto.InvalidCipherTextException: "mac check in GCM failed"
I am taring to decode metamask vault an sure that everithing with it must be OK
I can't find what's wrong
using System.Security.Cryptography;
using Org.BouncyCastle.Crypto.Parameters;
using System.Text;
using Jose;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
namespace net6metachecker
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void startbtn_Click(object sender, EventArgs e)
{
Decrypt1();
}
public void Decrypt1()
{
byte[] salt = Convert.FromBase64String("RXoBv+8Yu/nQhmj+nXMp8Rf57VLT8aYu5rvP5LEcq7Y=");
byte[] data = Convert.FromBase64String("cVZeRBJI7yzsN6lM9LS6tNSVYTU7IFy+UMAVsZjHa+/nGvXirE99pILb4+VdYANkEg05kbeoYgLwacqUNfZc+9llePvcLkVmzFtye4pYbVSkHtaGCKfFMb0gQxJb2xJz7Br4MHNzGEY7aZAkrWpx1KhIghA3uZBE5sjZ+vjw/aFg3w51xGBMgzwLdMcr8+Fru5Kyb5p1dVXSsMt7AFIQFg1BsOcbEiDNf/jkigxuJpILVYUY3qrUJmYh500frohZnxoh8fSPSWcyLbl08TKGE4DQuBeJ7cMcmmHnpvJ166BK1roOni4CMRIn84BBUr5DEW36+22i52vfPCvzgNUierIBoh3wUTZI/trHozXSLYg8t86XwLIzwNq4H08Ctss/Daivta/7mgE5KC7gesRoda6OLJ5XldxeibdtOprq1v+teeNVaZRRYTKs+cCUkrwxZVrjqzmnVMBxDegR3/gjchZRszm4hOWDfVR8JRhjpCKQmrLkOno=");
byte[] iv = Convert.FromBase64String("beg6WtZTF82na0IKb5Juhw==");
byte[] password = Encoding.UTF8.GetBytes("11111111");
byte[] key = PBKDF2.DeriveKey(password, salt, 10000, 256, HMAC.Create("HMACSHA256"));
GcmBlockCipher gcmBlockCipher = new GcmBlockCipher(new AesFastEngine());
AeadParameters parameters = new AeadParameters(new KeyParameter(key), 128, iv, null);
gcmBlockCipher.Init(false, parameters);
byte[] plainBytes = new byte[gcmBlockCipher.GetOutputSize(data.Length)];
int retLen = gcmBlockCipher.ProcessBytes(data, 0, data.Length, plainBytes, 0);
byte[] cc = gcmBlockCipher.GetMac();
int xx = gcmBlockCipher.DoFinal(plainBytes, retLen); // Exception is here
string x = Encoding.UTF8.GetString(plainBytes).TrimEnd("\r\n\0".ToCharArray());
MessageBox.Show(x);
}
}
}

Extra 16 bytes generated by C# AES encryption

I am using the following code to test the C# AES encryption and the output is 32 bytes instead of 16. I'd like to understand what is the extra 16 bytes. Thank you very much for any help.
using System;
using System.IO;
using System.IO.Compression;
using System.Security.Cryptography;
using System.Text;
namespace TestEnc
{
class Program
{
static void Main(string[] args)
{
byte[] key = { 50, 41, 132,234,143,17,
89, 74, 2, 56, 36,87,
54, 87, 88, 28};
byte[] iv = { 45, 241,153,24,14,17,
8, 57,32,5,96,47,
54,87,88,8};
using (Rijndael algorithm = Rijndael.Create())
{
algorithm.Padding = PaddingMode.PKCS7;
using (ICryptoTransform encryptor = algorithm.CreateEncryptor(key, iv))
{
string fullpath = #"c:\test.txt";
using (Stream FileOutStream = File.Open(fullpath, FileMode.Create))
{
using (Stream encStream = new CryptoStream(FileOutStream, encryptor, CryptoStreamMode.Write))
{
string s = "hello world 1234";
for (int i = 0; i < 1; i++)
{
encStream.Write(Encoding.ASCII.GetBytes(s), 0, (int)s.Length);
}
}
}
}
}
}
}
}

Why is this AES code producing the same encrypted output?

While playing with some AES C# wrappers found on SO and msdn (most notable here and here and here) I wrote the following code and I made the mistake of writing the IV to the CryptoStream.
What I noticed is that the output byte array contains the same values when the IV is written to the CryptoStream. If I comment out the line cryptoStream.Write(aes.IV, 0, aes.IV.Length);, it's fine, the output will be different.
My question is why in this case the output is the same? I realize that writing the IV to the CryptoStream is not what I am supposed to do but I find it odd especially given that the IV is different every time the function executes.
TestEncryption.cs:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
public class TestEncryption
{
public static readonly int KeyBitSize = 256;
private static readonly int BlockBitSize = 128;
public static readonly byte[] _salt = new byte[] { 23, 13, 23, 213, 15, 193, 134, 147, 223, 151 };
const int Iterations = 10000;
public static string Encrypt(byte[] inputBytes, string password)
{
using (var aes = new AesManaged
{
KeySize = KeyBitSize,
BlockSize = BlockBitSize,
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7,
})
{
var cryptKey = CreateKey(password);
aes.GenerateIV();
Console.WriteLine("IV={0}", string.Join(", ", aes.IV.Select(b => b.ToString())));
using (var encrypter = aes.CreateEncryptor(cryptKey, aes.IV))
using (var output = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(output, encrypter, CryptoStreamMode.Write))
{
cryptoStream.Write(aes.IV, 0, aes.IV.Length);
cryptoStream.Write(inputBytes, 0, inputBytes.Length);
cryptoStream.FlushFinalBlock();
}
Console.WriteLine("Output={0}", string.Join(", ", output.ToArray().Select(b => b.ToString())));
return Convert.ToBase64String(output.ToArray());
}
}
}
public static string Encrypt(string input, string password)
{
return Encrypt(Encoding.UTF8.GetBytes(input), password);
}
public static byte[] CreateKey(string password)
{
using (var rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, _salt, Iterations))
return rfc2898DeriveBytes.GetBytes(32);
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
class Program
{
static void Main(string[] args)
{
//Test1();
Test2();
Console.ReadLine();
}
private static void Test2()
{
string text = "some longer text";
string pwd = "test2";
String encrypt1 = TestEncryption.Encrypt(text, pwd);
String encrypt2 = TestEncryption.Encrypt(text, pwd);
Console.WriteLine(encrypt1 == encrypt2);
}
}
}

c# shorten query string parameter

I need to pass a URL as a parameter into my querystring, since the URLs can be long I need to shorten the URL while passing and then be able to decrypt them on server side.
The URL that I am trying to pass does not contain sensitive information so string encryption techniques are not required, I am just looking to convert a long string to a short string and be able to reconstruct it back to a string.
I have tried AES encryption and it works but the resulting string is sometimes longer than the URL value itself.
Example of what I've tried so far :
private static byte[] key = { 252, 217, 19, 11, 24, 26, 85, 45, 114, 184, 27, 162, 37, 112, 222, 209, 241, 24, 175, 144, 173, 53, 196, 29, 24, 26, 17, 218, 131, 236, 53, 209 };
private static byte[] vector = { 152, 64, 191, 111, 23, 3, 113, 119, 231, 121, 221, 112, 79, 32, 114, 156 };
private ICryptoTransform encryptor, decryptor;
private UTF8Encoding encoder;
public SimpleAES()
{
RijndaelManaged rm = new RijndaelManaged();
encryptor = rm.CreateEncryptor(key, vector);
decryptor = rm.CreateDecryptor(key, vector);
encoder = new UTF8Encoding();
}
public string Encrypt(string unencrypted)
{
return Convert.ToBase64String(Encrypt(encoder.GetBytes(unencrypted)));
}
public string Decrypt(string encrypted)
{
return encoder.GetString(Decrypt(Convert.FromBase64String(encrypted)));
}
public string EncryptToUrl(string unencrypted)
{
return HttpUtility.UrlEncode(Encrypt(unencrypted));
}
public string DecryptFromUrl(string encrypted)
{
return Decrypt(HttpUtility.UrlDecode(encrypted));
}
public byte[] Encrypt(byte[] buffer)
{
return Transform(buffer, encryptor);
}
public byte[] Decrypt(byte[] buffer)
{
return Transform(buffer, decryptor);
}
protected byte[] Transform(byte[] buffer, ICryptoTransform transform)
{
MemoryStream stream = new MemoryStream();
using (CryptoStream cs = new CryptoStream(stream, transform, CryptoStreamMode.Write))
{
cs.Write(buffer, 0, buffer.Length);
}
return stream.ToArray();
}
Example TEST :
string unencrypted = "/exampleurl/this_is_a_long_string_the_length_of_this_url_is_112_charachters_/this_string_needs_to_be-shortened/";
var result = EncryptToUrl(unencrypted);
"MHMyQdwbJpw8ah%2fbhAr2eJwTFa%2fyupemjuOVcBJmxTIdzcR0PZKCNSa5Fvi7kNrY3Kxlk5KWqAAEspWVtJfNjwwPs%2bCDGpC9Fn8CeGezWhXEbLT6CST2v%2fKpvptHVi3fBYSk1w3q1FYMx3C5DdKueQ%3d%3d"
The actual string is 112 charachters long and the result is 165 charahcters long.
The following code is taken verbatim from here. I duplicated this because the question is not a duplicate but the answer solves the problem this question poses. When you call Zip you will need to base64 encode the result to make it friendly for a browser if you plan to include it in a URL or something.
public static void CopyTo(Stream src, Stream dest) {
byte[] bytes = new byte[4096];
int cnt;
while ((cnt = src.Read(bytes, 0, bytes.Length)) != 0) {
dest.Write(bytes, 0, cnt);
}
}
public static byte[] Zip(string str) {
var bytes = Encoding.UTF8.GetBytes(str);
using (var msi = new MemoryStream(bytes))
using (var mso = new MemoryStream()) {
using (var gs = new GZipStream(mso, CompressionMode.Compress)) {
//msi.CopyTo(gs);
CopyTo(msi, gs);
}
return mso.ToArray();
}
}
public static string Unzip(byte[] bytes) {
using (var msi = new MemoryStream(bytes))
using (var mso = new MemoryStream()) {
using (var gs = new GZipStream(msi, CompressionMode.Decompress)) {
//gs.CopyTo(mso);
CopyTo(gs, mso);
}
return Encoding.UTF8.GetString(mso.ToArray());
}
}
static void Main(string[] args) {
byte[] r1 = Zip("StringStringStringStringStringStringStringStringStringStringStringStringStringString");
string r2 = Unzip(r1);
}
This might sound strange, but can you store the querystring in a database and reference it by some primary key? That might be similar to using some third party URL shortening service.

prevent DESCryptoServiceProvider to generate special characters

i am using following encryption method to encrypt a string
private static byte[] mKey = { };
private static byte[] mIV = { 89, 23, 13, 17, 69, 32, 02, 79 };
private static string mStringKey = "lkj#788*";
private static string Encrypt(string pText)
{
try
{
mKey = Encoding.UTF8.GetBytes(mStringKey.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
Byte[] byteArray = Encoding.UTF8.GetBytes(pText);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream,
des.CreateEncryptor(mKey, mIV), CryptoStreamMode.Write);
cryptoStream.Write(byteArray, 0, byteArray.Length);
cryptoStream.FlushFinalBlock();
return Convert.ToBase64String(memoryStream.ToArray());
}
catch (Exception ex)
{
return string.Empty;
}
}
I want to build a discount code for customers with this format "CustomerId-PurchasedItem-DiscountValue" and encrypt these (CustomerId,PurchasedItem,DiscountValue) strings individually and combine encrypted values adding "-" char between them to build discount code .while decrypting above encoded string ,i will split it with "-" char,and decode individually ,but i am afraid that while encrypting if it get "-" char then my logic will fail..is this method is safe or can any one suggest me another trick?or is there any trick that encryption of a string result to fixed length?
I believe that .NET's base64 encoding will never contain a '-' character, so you should be okay.

Categories