AES 128 Encription in SQLSERVER OR ASP.Net - c#

i am trying to create a web service which needs to return data in AES 128 encryption format. Someone please help me, how can i achieve this.
thanks in advance.

public class EncryptionAES128
{
static public string EncryptString(string inputString, string key)
{
string output = "";
Rijndael encryption = new RijndaelManaged();
try
{
encryption.IV = GenerateIV();
encryption.Key = StringToByte(key);
ICryptoTransform encryptor = encryption.CreateEncryptor(encryption.Key, encryption.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(inputString);
}
byte[] cipherText = msEncrypt.ToArray();
byte[] encrypted = new byte[cipherText.Length + encryption.IV.Length];
encryption.IV.CopyTo(encrypted, 0);
cipherText.CopyTo(encrypted, IV_LENGTH);
output = ByteToString(encrypted);
}
}
}
catch (Exception ex)
{
throw ex;
}
return output;

Related

When decrypting an encrypted string in c#, only the first character is returned

I have an encryption algorithm and decryption algorithm used for a login page. When encrypting, everything seems fine and seems to encrypt everything as expected, but when the encrypted password is put back through my decryption algorithm, only the first character is returned.
Example
Here is the code:
public string encrypt(string key, string data)
{
byte[] clearBytes = Encoding.Unicode.GetBytes(data);
byte[] iv = new byte[16];
using (Aes encryptor = Aes.Create())
{
encryptor.Key = Encoding.UTF8.GetBytes(key);
encryptor.IV = iv;
encryptor.Padding = PaddingMode.PKCS7;
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
data = Convert.ToBase64String(ms.ToArray());
}
}
return data;
}
public static string decryptData(string key, string data)
{
byte[] iv = new byte[16];
byte[] clearBytes = Convert.FromBase64String(data);
using (Aes decrpytor = Aes.Create())
{
decrpytor.Key = Encoding.UTF8.GetBytes(key);
decrpytor.IV = iv;
ICryptoTransform decryptor = decrpytor.CreateDecryptor(decrpytor.Key, decrpytor.IV);
decrpytor.Padding = PaddingMode.PKCS7;
using (MemoryStream ms = new MemoryStream(clearBytes))
{
using (CryptoStream cs = new CryptoStream((Stream)ms, decryptor, CryptoStreamMode.Read))
{
using (StreamReader sr = new StreamReader((Stream)cs))
{
return sr.ReadToEnd();
}
}
}
}
}
public void button1_Click(object sender, EventArgs e)
{
var key = "b14ca5898a4e4133bbce2ea2315a1916";
var str = passWord.Text;
var encryptedPassword = encrypt(key, str);
var decrpted = decryptData(key, encryptedPassword);
passwordTest.Text = encryptedPassword;
decryptedtest.Text = decrpted;
}
the last 2 lines are purely for testing to see what they output.
Any help is appreciated.

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.

small file cause OutofMemoryException

I have an encrypted file which I decrypt first and then try to deserialize it using memorystream and binaryformatter but when I try to assign deserialized files to a list I catch OutOfMemoryException (file is really small - 17KB)
here is the code
byte[] encryptedData = File.ReadAllBytes(fileName);
byte[] result = Decrypt(Algo, key, vector, encryptedData) ;
BinaryFormatter ser = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream(result)) {
try {
files = ser.Deserialize(ms) as List<IItem>;
} catch (OutOfMemoryException) {
} catch (SerializationException) {
MessageBox.Show("Incorrect password!");
return;
}
}
files = ser.Deserialize(ms) as List<IItem>; - this what cause exception
encrypted file size 1696
after decryption 1691 - normal size.
here Decryption code
public byte[] Decode(byte[] data)
{
string key = ASCIIEncoding.ASCII.GetString(rc2.Key);
string IV = ASCIIEncoding.ASCII.GetString(rc2.IV);
ICryptoTransform decryptor = rc2.CreateDecryptor(rc2.Key,rc2.IV);
StringBuilder roundtrip = new StringBuilder();
using (MemoryStream msDecrypt = new MemoryStream(data))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
int b = 0;
do
{
b = csDecrypt.ReadByte();
if (b != -1)
{
roundtrip.Append((char) b);
}
} while (b != -1);
}
}
byte[] decrypted = ASCIIEncoding.ASCII.GetBytes(roundtrip.ToString());
return decrypted;
}
#MineR and #HansPassant was right problem was in using chars while decrypting)) i have changed my code
public byte[] Decode(byte[] data)
{
ICryptoTransform decryptor = rc2.CreateDecryptor(rc2.Key,rc2.IV);
byte[] decrypted = new byte[data.Length];
using (MemoryStream msDecrypt = new MemoryStream(data))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
csDecrypt.Read(decrypted, 0, data.Length);
}
}
return decrypted;
}
and now it works. Thx all for answers.

objective c aes 128 encryption for a c# web service

So I'm trying to figure out how to make an objective c version of this as it's part of a wcf service security that was implemented. My main issue here is Idk where to begin as some articles/tutorials would automatically pad 0 in the beginning (not sure if that's their IV) like so:
(a couple of replies down)
http://iphonedevsdk.com/forum/iphone-sdk-development/60926-aesencryption-in-objective-c-and-php.html
compared to this which doesn't use any padding:
Objective-C decrypt AES 128 cbc hex string
Anyway, this is how the wcf encrypts using AES 128. Any advice or nudge to the right direction is very much appreciated. Thanks!!!.
public class EncryptionAES128
{
static public string EncryptString(string inputString, string key)
{
string output = "";
Rijndael encryption = new RijndaelManaged();
try
{
encryption.IV = GenerateIV();
encryption.Key = StringToByte(key);
ICryptoTransform encryptor = encryption.CreateEncryptor(encryption.Key, encryption.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(inputString);
}
byte[] cipherText = msEncrypt.ToArray();
byte[] encrypted = new byte[cipherText.Length + encryption.IV.Length];
encryption.IV.CopyTo(encrypted, 0);
cipherText.CopyTo(encrypted, IV_LENGTH);
output = ByteToString(encrypted);
}
}
}
catch (Exception ex)
{
throw ex;
}
return output;
}

AeS encryption 'Value cannot be null'

I have recently been experimenting with the "CryptoStream", and ran into the idea of encrypting & decrypting a text via. the Aes class. 'Namespace: System.Security.Cryptography'
After making a function that succesfully encrypted a text using two input parameters: Text, Password
static byte[] Salt = { 18,39,27,48,82,32,12,92 };
public static string EncryptAES(string txt, string Password) {
Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(Password, Salt);
RijndaelManaged RJM = new RijndaelManaged();
RJM.Key = rfc.GetBytes(RJM.KeySize / 8);
ICryptoTransform ICT = Aes.Create().CreateEncryptor(RJM.Key, RJM.IV);
using (MemoryStream MS = new MemoryStream()) {
using (CryptoStream CS = new CryptoStream(MS, ICT, CryptoStreamMode.Write)) {
using (StreamWriter SW = new StreamWriter(CS)) {
SW.Write(txt);
}
}
return Convert.ToBase64String(MS.ToArray());
}
}
The issue of decrypting the text took place.
My attempt of decrypt the text was the following:
public static string DecryptAES(string EncryptedTxt, string Password) {
Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(EncryptedTxt, Salt);
RijndaelManaged RJM = new RijndaelManaged();
RJM.Key = rfc.GetBytes(RJM.KeySize / 8);
ICryptoTransform ICT = Aes.Create().CreateDecryptor(RJM.Key, RJM.IV);
using (MemoryStream MS = new MemoryStream(Convert.FromBase64String(EncryptedTxt))) {
using (CryptoStream CS = new CryptoStream(MS, ICT, CryptoStreamMode.Read)) {
using (StreamReader SR = new StreamReader(CS)) {
return SR.ReadToEnd();
}
}
}
However; it appears that my way of converting the memorystream to string and then back was invaild, as I get the following error: Error: Value cannot be null\nParameter name: inputBuffer
The error occurs at using (MemoryStream MS = new MemoryStream(Convert.FromBase64String(EncryptedTxt)))
How can I converter the MemoryStream into string and back?
Thanks in advance :-)

Categories

Resources