decryption of mysql column in .net - mysql

I have a column in mysql called reference column which is encrypted. I have the key for decryption. I am retriving the data using entityframework and need to decryption the column and push it to a csv file. can some one help me with the decryption code using c#
public string DecryptStringFromBytes(string value)
{
String encryptKey = "Youare#IsBe$t";
byte[] key = Encoding.UTF8.GetBytes(encryptKey);
byte[] cipherText = Encoding.UTF8.GetBytes(value);
string plaintext = null;
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.GenerateIV();
ICryptoTransform decryptor = rijAlg.CreateDecryptor(key, rijAlg.IV);
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}

Related

How encrypt and decrypt integer value in linq devexpress blazor

public string GetQCAsync(string UserLimit)
{
var DSet1 = _context.test.Where(x => x.Uid == 1).FirstOrDefault();
var provider = new System.Security.Cryptography.RSACryptoServiceProvider();
//provider.ImportParameters("aXb2uy4z");
DSet1.NoOfUsers = provider.Encrypt(
System.Text.Encoding.UTF8.GetBytes(UserLimit), true);
string decryptedTest = System.Text.Encoding.UTF8.GetString(
provider.Decrypt(DSet1.NoOfUsers, true));
return decryptedTest;
}
i tried this but this won't work
i want to get integer value and to encrypt it and save the encrypted value in sql while saving and i have to get the actual[decrypted] value when edit

JSON.NET: getting json from external source with streams, how to get just one value?

I have the following code:
static void Main(string[] args)
{
HttpClient client = new HttpClient();
using (Stream stream = client.GetStreamAsync("https://opendata.rdw.nl/resource/8ys7-d773.json?kenteken=61SFSL").Result)
using (StreamReader streamReader = new StreamReader(stream))
using (JsonReader reader = new JsonTextReader(streamReader))
{
JsonSerializer serializer = new JsonSerializer();
// read the json from a stream
// json size doesn't matter because only a small piece is read at a time from the HTTP request
//What do I do here to get my one value?
}
Console.WriteLine("Press any key to continue...");
Console.Read();
}
I got this from the documentation over at the JSON.NET website. The reason being that I don't want to load the whole string, but piece by piece. The response is as follows:
[{"brandstof_omschrijving":"Benzine","brandstof_volgnummer":"1","brandstofverbruik_buiten":"6.60","brandstofverbruik_gecombineerd":"8.20","brandstofverbruik_stad":"11.10","co2_uitstoot_gecombineerd":"196","emissiecode_omschrijving":"Euro 4","geluidsniveau_rijdend":"71","geluidsniveau_stationair":"82","kenteken":"61SFSL","milieuklasse_eg_goedkeuring_licht":"70/220*2001/100B","nettomaximumvermogen":"99.00","toerental_geluidsniveau":"4125"}]
I.e., it returns an array with one json object, and I want to retrieve just one value in there, using a stream. How might I do this?
You could try the following
using System;
using System.Net.Http;
using Newtonsoft;
public class Program {
public static void Main() {
var client = new HttpClient();
var json = client.GetStringAsync("https://opendata.rdw.nl/resource/8ys7-d773.json?kenteken=61SFSL").Result;
var data = JsonConvert.DeserializeObject<dynamic>(json);
string value = data[0].co2_uitstoot_gecombineerd;
Console.WriteLine(value);
Console.WriteLine("Press any key to continue...");
Console.Read();
}
}

How to insert uploaded image into varbinary(max) database column

I want process form submit and save jpg image into varbinary sql column.
I have code but it does not work properly, it is saving only empty bytes like 0x00...0000. So no errors are raised and database row is inserted successfully, but varbinary column seems to me corrupted.
The code is following
Models
public class FrontendModel
{
public HttpPostedFileBase Photo1 { get; set; }
}
public class SubmitModel
{
public byte[] ImageData { get; set; }
public decimal ImageSizeB { get; set; }
public SubmitModel
(
HttpPostedFileBase Photo
)
{
this.ImageData = new byte[Photo.ContentLength];
Photo.InputStream.Read(ImageData, 0, Convert.ToInt32(Photo.ContentLength));
this.ImageSizeB = Photo.ContentLength;
}
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(FrontendModel m)
{
using (var db = new ABC.Models.ABCDBContext())
{
using (var scope = new TransactionScope())
{
if (m.Photo1 != null && m.Photo1.ContentLength > 0)
db.InsertSubmit(new SubmitModel(m.Photo1));
scope.Complete();
}
}
return View(new FrontendModel());
}
DB Insert Function
public void InsertSubmit(SubmitModel m)
{
Database.ExecuteSqlCommand(
"spInsertSubmit #p1",
new SqlParameter("p1", m.ImageData),
);
}
SQL DB Procedure
CREATE PROCEDURE [dbo].[spInsertSubmit]
#ImageData VARBINARY(max)
AS
INSERT INTO dbo.Images (Image)
VALUES (#ImageData)
what am I doing wrong ? Thank you
PS:
I also tried something like this but it behave the same
using (var binaryReader = new BinaryReader(Photo.InputStream))
{
this.ImageData = binaryReader.ReadBytes(Photo.ContentLength);
}
then I tried
using (Stream inputStream = Photo.InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}
ImageData = memoryStream.ToArray();
}
but error shows in calling DB function with error message, Parameter is not valid
i have the same problem as is mentioned here
File uploading and saving to database incorrectly
I found that when i assign Input stream to memory stream, the memory stream is empty ?!
Your procedure specifies that the parameter is called #ImageData but your code
Database.ExecuteSqlCommand(
"spInsertSubmit #p1",
new SqlParameter("p1", m.ImageData),
);
seems to be passing a parameter called #p1
Edit
Also I think that you have to specify the type explicitly when working with a byte array larger than 8k. See this link: Inserting a byte array larger than 8k bytes
Database.ExecuteSqlCommand(
"spInsertSubmit #p1",
new SqlParameter("#p1", SqlDbType.VarBinary) { Value = m.ImageData },
);
Ok i found a solution. This code works!
this.ImageData = new byte[streamLength];
Photo.InputStream.Position = 0;
Photo.InputStream.Read(this.ImageData, 0, this.ImageData.Length);
The line added is Photo.InputStream.Position = 0;

How to implement AES Encrypt (AesManaged Rfc2898DeriveBytes) in Windows Runtime

I met a blocking issue when I tried to immigrate my project from Windows Phone Silverlight 8.1 to Windows Runtime.
In Windows Runtime the AES-encrypted string is not the same as the one on Silverlight before.
In Silverlight:
public static string EncryptAES(string encryptString)
{
AesManaged aes = null;
MemoryStream ms = null;
CryptoStream cs = null;
string encryptKey = "testtest123";
string salt = "abcabcabcd";
try
{
Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(encryptKey, Encoding.UTF8.GetBytes(salt));
aes = new AesManaged();
aes.Key = rfc2898.GetBytes(aes.KeySize / 8);
aes.IV = rfc2898.GetBytes(aes.BlockSize / 8);
ms = new MemoryStream();
cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write);
byte[] data = Encoding.UTF8.GetBytes(encryptString);
cs.Write(data, 0, data.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
catch
{
return encryptString;
}
finally
{
if (cs != null)
cs.Close();
if (ms != null)
ms.Close();
if (aes != null)
aes.Clear();
}
}
In Windows Runtime:
public static string EncryptAES(string plainText)
{
string pw = "testtest123";
string salt = "abcabcabcd";
IBuffer plainBuffer = CryptographicBuffer.ConvertStringToBinary(plainText, BinaryStringEncoding.Utf8);
IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf8);
IBuffer pwBuffer = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf8);
KeyDerivationAlgorithmProvider keyDerivationProvider = Windows.Security.Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha256);
// using salt and 1000 iterations
KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000);
// create a key based on original key and derivation parmaters
CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(pwBuffer);
IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32);
CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer);
// derive buffer to be used for encryption salt from derived password key
IBuffer saltMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16);
// display the buffers - because KeyDerivationProvider always gets cleared after each use, they are very similar unforunately
string keyMaterialString = CryptographicBuffer.EncodeToBase64String(keyMaterial);
string saltMaterialString = CryptographicBuffer.EncodeToBase64String(saltMaterial);
//AES_CBC_PKCS7
SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7");
// create symmetric key from derived password key
CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial);
// encrypt data buffer using symmetric key and derived salt material
IBuffer resultBuffer = CryptographicEngine.Encrypt(symmKey, plainBuffer, saltMaterial);
string result = CryptographicBuffer.EncodeToBase64String(resultBuffer);
return result;
}
In Silverlight Project, string "123456" encrypted by AES is "4UfdhC/0MFQlMhl7N7gqLg==";
While in Windows Runtime Project, the AES-encrypted string is "jxsR5EuhPXgRsHLs4N3EGQ=="
So how can I get the same string on WinRT as the one on Silverlight ?
The AES classes default to a random IV on the Microsoft runtimes. To get the same ciphertext you'll need to use a static IV. That's however not secure. Instead you should just check if you get the same key bytes and let the ciphertext differ for each run. Otherwise you can clearly distinguish identical plaintext.
You also seem to be using the wrong hash algorithm, Rfc2898DeriveBytes uses SHA-1 instead of SHA-256 as underlying hash function.
I've created class which works for me as replacement for System.Security.Cryptography.Rfc2898DeriveBytes:
public class Rfc2898DeriveBytes
{
private readonly string _password;
private readonly byte[] _salt;
public Rfc2898DeriveBytes(string password, byte[] salt)
{
_password = password;
_salt = salt;
IterationCount = 1000;
}
public uint IterationCount { get; set; }
public byte[] GetBytes(uint cb)
{
var provider = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha1);
var buffSecret = CryptographicBuffer.ConvertStringToBinary(_password, BinaryStringEncoding.Utf8);
var buffsalt = CryptographicBuffer.CreateFromByteArray(_salt);
var keyOriginal = provider.CreateKey(buffSecret);
var par = KeyDerivationParameters.BuildForPbkdf2(buffsalt, IterationCount);
var keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, par, cb);
byte[] result;
CryptographicBuffer.CopyToByteArray(keyMaterial, out result);
return result;
}
}

"Length of the data to decrypt is invalid." exception during Rijndael decryption

I get "Length of the data to decrypt is invalid." exception when i try to decrypt a memory stream. I am beginner, cant figure out whats wrong. whats wrong?
public bool EncryptStream()
{
string password = #"myKey123"; // Your Key Here
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
s_EncryptedStream = new MemoryStream();
int NoOfBytes;
byte[] b_Buffer = new byte[8192];
s_MemoryStream.Seek(0, SeekOrigin.Begin);
RijndaelManaged RMCrypto = new RijndaelManaged();
s_CrytpoStream = new CryptoStream(s_EncryptedStream,
RMCrypto.CreateEncryptor(key, key),
CryptoStreamMode.Write);
while (s_MemoryStream.Length < s_MemoryStream.Position)
{
NoOfBytes = s_MemoryStream.Read(b_Buffer, 0, 8192);
s_CrytpoStream.Write(b_Buffer, 0, NoOfBytes);
}
s_MemoryStream.Seek(0, SeekOrigin.Begin);
while (s_EncryptedStream.Position < s_EncryptedStream.Length)
{
NoOfBytes = s_EncryptedStream.Read(b_Buffer, 0, 8192);
s_MemoryStream.Write(b_Buffer, 0, NoOfBytes);
}
s_CrytpoStream.Flush();
s_CrytpoStream.Close();
return true;
}
public bool DecryptStream()
{
string password = #"myKey123"; // Your Key Here
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
int NoOfBytes;
byte[] b_Buffer = new byte[8192];
s_DecryptedStream = new MemoryStream();
RijndaelManaged RMCrypto = new RijndaelManaged();
s_CrytpoStream = new CryptoStream(s_MemoryStream,
RMCrypto.CreateDecryptor(key, key),
CryptoStreamMode.Read);
s_MemoryStream.Seek(0, SeekOrigin.Begin);
while (s_MemoryStream.Length > s_MemoryStream.Position)
{
NoOfBytes = s_CrytpoStream.Read(b_Buffer, 0, 8192);
s_DecryptedStream.Write(b_Buffer, 0, NoOfBytes);
}
s_DecryptedStream.Seek(0, SeekOrigin.Begin);
s_MemoryStream.Seek(0, SeekOrigin.Begin);
while (s_DecryptedStream.Position < s_DecryptedStream.Length)
{
NoOfBytes = s_DecryptedStream.Read(b_Buffer, 0, 8192);
s_MemoryStream.Write(b_Buffer, 0, NoOfBytes);
}
s_CrytpoStream.Flush();
s_CrytpoStream.Close();
return true;
}
For a start, this while loop condition is never right:
while (s_MemoryStream.Length < s_MemoryStream.Position)
How can the position be beyond the length?
Rather than using the length of a stream, the usual pattern to copy a stream is to read repeatedly until the value returned isn't positive. As you're doing that twice in this code anyway, you might as well encapsulate it:
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[8192];
int read;
while ( (read = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
}
}
It's also best to use using statements to clean up strings. Additionally, the Encoding.Unicode property means you don't have to create a new UnicodeEncoding yourself. Also, I generally find that setting the Position property is more readable than using Seek. Finally, there's no point in a method returning a value if it's always going to be true. So, your code would become:
public void EncryptStream()
{
string password = #"myKey123"; // Your Key Here
byte[] key = Encoding.Unicode.GetBytes(password);
s_EncryptedStream = new MemoryStream();
s_MemoryStream.Position = 0;
RijndaelManaged RMCrypto = new RijndaelManaged();
using (Stream crytpoStream = new CryptoStream(s_EncryptedStream,
RMCrypto.CreateEncryptor(key, key),
CryptoStreamMode.Write))
{
CopyStream(s_MemoryStream, cryptoStream);
}
s_MemoryStream.Position = 0;
s_EncryptedStream.Position = 0;
CopyStream(s_EncryptedStream, s_MemoryStream);
}
public void DecryptStream()
{
string password = #"myKey123"; // Your Key Here
byte[] key = Encoding.Unicode.GetBytes(password);
s_DecryptedStream = new MemoryStream();
s_MemoryStream.Position = 0;
RijndaelManaged RMCrypto = new RijndaelManaged();
using (Stream crytpoStream = new CryptoStream(s_MemoryStream,
RMCrypto.CreateDecryptor(key, key),
CryptoStreamMode.Read))
{
CopyStream(cryptoStream, s_DecryptedStream);
}
s_DecryptedStream.Position = 0;
s_MemoryStream.Position = 0;
CopyStream(s_DecryptedStream, s_MemoryStream);
}
Even after amending this code, it feels like you've got way too many non-local variables here. I can't see why any of this should be in instance variables. Make the stream to be encrypted or decrypted a parameter (along with the password) and return a memory stream with the encrypted/decrypted data in, or just a byte array.
You may need to call the FlushFinalBlock method on the CryptoStream after you have finished reading the input data. (ie. crytpoStream.FlushFinalBlock() after CopyStream)
I have come up with a solution and I have it posted on my new Blog
constotech.blogspot.com/2009/05/net-encryption-using-symmetricalgorithm.html