encryption in UWP cyclic redundency check - c#

I am making a security software which encrypt data using AES encryption
when I encrypt or decrypt using FileIO it works fine as all the bytes are read and fed to the encrypt function at once but that leads to problem for huge files as it loads a huge file into the ram.
So I used datareader and datawriter to load file partially and sent it to encrypt
but the problem is as I do this when I decrypt this file it throws cyclic redundancy error. I partially know the reason but don't know how to fix
here are my codes
New one using data reader and writer
public async void EncryptDecryptFileNew(StorageFile sourcefile, StorageFolder destinationfolder, string password, string username, bool IsEncrypt)
{
passwordstring = AES_Encrypt(StringToBytes(password), username);
if (sourcefile != null)
{
StorageFile sfile = null;
bool isCompletedSuccesfully = false;
try
{
if (StorageApplicationPermissions.FutureAccessList.CheckAccess(sourcefile))
{
var properties = await sourcefile.GetBasicPropertiesAsync();
string temp = destinationfolder.Path;
StorageFolder sf = await StorageFolder.GetFolderFromPathAsync(temp);
sfile = await sf.CreateFileAsync(sourcefile.Name, CreationCollisionOption.ReplaceExisting);
Debug.WriteLine(sourcefile.DisplayName + properties.Size, "FileStart");
if (properties.Size > 0)
{
using (Stream sstream = await sourcefile.OpenStreamForReadAsync())
{
using (DataReader sourceReader = new DataReader(sstream.AsInputStream()))
{
using (var dstream = await sfile.OpenAsync(FileAccessMode.ReadWrite))
{
using (var outputStream = dstream.GetOutputStreamAt(0))
{
using (DataWriter dWriter = new DataWriter(outputStream))
{
byte[] f;
for (ulong i = 0; i < (properties.Size / 64); i++)
{
await sourceReader.LoadAsync(64);
if (IsEncrypt)
f = AES_Encrypt(sourceReader.ReadBuffer(64).ToArray(), BytesToString(passwordstring));
else
f = AES_Decrypt(sourceReader.ReadBuffer(64).ToArray(), BytesToString(passwordstring));
dWriter.WriteBytes(f);
}
uint remaining = (uint)properties.Size % 64;
if ((remaining) != 0)
{
await sourceReader.LoadAsync(remaining);
if (IsEncrypt)
f = AES_Encrypt(sourceReader.ReadBuffer(remaining).ToArray(), BytesToString(passwordstring));
else
f = AES_Decrypt(sourceReader.ReadBuffer(remaining).ToArray(), BytesToString(passwordstring));
dWriter.WriteBytes(f);
}
await dWriter.StoreAsync();
}
}
}
}
}
isCompletedSuccesfully = true;
GC.Collect();
}
else
isCompletedSuccesfully = true;
Debug.WriteLine(sourcefile.DisplayName, "FileEnd");
}
}
catch (OutOfMemoryException y)
{
GC.Collect();
}
catch (Exception e)
{
Debug.WriteLine(e.Message, "Encryption File");
}
finally
{
System.GC.Collect();
if (isCompletedSuccesfully)
{
if (totalSize != 0)
{
Debug.WriteLine(sourcefile.DisplayName + " " + fileDictionary[sourcefile.Path] + " " + totalSize);
Percentage += fileDictionary[sourcefile.Path] / totalSize;
}
if (FEDD != null)
FEDD();
}
else
{
if (fileDictionary.Count != 0)
{
if (sfile != null)
{
await sfile.DeleteAsync();
}
EncryptDecryptFileNew(sourcefile, destinationfolder, password, username, IsEncrypt);
}
}
await Task.CompletedTask;
}
}
}
for encryption
public byte[] AES_Encrypt(byte[] input, string pass)
{
SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
CryptographicKey AES;
HashAlgorithmProvider HAP = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
CryptographicHash Hash_AES = HAP.CreateHash();
try
{
IBuffer Buffer = CryptographicBuffer.CreateFromByteArray(input);
byte[] encrypted;
byte[] hash = new byte[32];
Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(pass)));
byte[] temp;
CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out temp);
Array.Copy(temp, 0, hash, 0, 16);
Array.Copy(temp, 0, hash, 15, 16);
AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash));
encrypted= (CryptographicEngine.Encrypt(AES, Buffer, null)).ToArray();
//encrypted = CryptographicBuffer.EncodeToBase64String(CryptographicEngine.Encrypt(AES, Buffer, null));
return encrypted;
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message,"AES ENCRYPT");
return null;
}
}
for decryption
public byte[] AES_Decrypt(byte[] input, string pass)
{
SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
CryptographicKey AES;
HashAlgorithmProvider HAP = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
CryptographicHash Hash_AES = HAP.CreateHash();
try
{
byte[] hash = new byte[32];
Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(pass)));
byte[] temp;
CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out temp);
Array.Copy(temp, 0, hash, 0, 16);
Array.Copy(temp, 0, hash, 15, 16);
AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash));
IBuffer Buffer = GetBufferFromBytes(input);
byte[] Decrypted;
CryptographicBuffer.CopyToByteArray(CryptographicEngine.Decrypt(AES, Buffer, null), out Decrypted);
return Decrypted;
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return null;
}
}
and the old one that worked
public async void EncryptDecryptFile(StorageFile sourcefile,StorageFolder destinationfolder,string password,string username,bool IsEncrypt)
{
passwordstring = AES_Encrypt(StringToBytes(password), username);
if (sourcefile != null)
{
StorageFile sfile=null;
bool isCompletedSuccesfully = false;
try
{
if (StorageApplicationPermissions.FutureAccessList.CheckAccess(sourcefile))
{
var properties = await sourcefile.GetBasicPropertiesAsync();
string temp = destinationfolder.Path;
StorageFolder sf = await StorageFolder.GetFolderFromPathAsync(temp);
sfile = await sf.CreateFileAsync(sourcefile.Name, CreationCollisionOption.ReplaceExisting);
Debug.WriteLine(sourcefile.DisplayName+properties.Size,"FileStart");
if (properties.Size > 0)
{
IBuffer buffer = await FileIO.ReadBufferAsync(sourcefile);
byte[] f = null;
Debug.WriteLine("tw1", sourcefile.Name);
GC.Collect();
if (IsEncrypt)
f = AES_Encrypt(buffer.ToArray(), BytesToString(passwordstring));
else
f = AES_Decrypt(buffer.ToArray(), BytesToString(passwordstring));
Debug.WriteLine("tw2", sourcefile.Name);
GC.Collect();
var rt = FileIO.WriteBufferAsync(sfile, GetBufferFromBytes(f));
rt.AsTask().Wait();
isCompletedSuccesfully = true;
GC.Collect();
Debug.WriteLine("tw3", sourcefile.Name);
}
else
isCompletedSuccesfully = true;
Debug.WriteLine(sourcefile.DisplayName, "FileEnd");
}
}
catch (OutOfMemoryException y)
{
GC.Collect();
}
catch (Exception e)
{
Debug.WriteLine(e.Message,"Encryption File");
}
finally
{
System.GC.Collect();
if (isCompletedSuccesfully)
{
if (totalSize != 0)
{
Debug.WriteLine(sourcefile.DisplayName + " " + fileDictionary[sourcefile.Path] + " " + totalSize);
Percentage += fileDictionary[sourcefile.Path] / totalSize;
}
if(FEDD!=null)
FEDD();
}
else
{
if (fileDictionary.Count != 0)
{
if (sfile != null)
{
await sfile.DeleteAsync();
}
EncryptDecryptFile(sourcefile, destinationfolder, password, username, IsEncrypt);
}
}
await Task.CompletedTask;
}
}
}

Related

C# using Bouncy Castle to PGP Encrypt File causing double encryption?

We are trying to implement PGP encryption into one of our .net apps for the first time at the request of a vendor that we work with. Most of the examples I have found reference using Bouncy Castle so I have attempted to implement that. Everything seems to work fine and I end up with a .pgp file that looks correct. When I send it to the vendor, they say that it appears to be double-encrypted. They said they had to decrypt it twice to read it. Anyone have any ideas what may be going on here? I'll include the sample code that I am using below.
public class Pgp
{
public static void DecryptFile(
string inputFileName,
string keyFileName,
char[] passwd,
string defaultFileName)
{
using (Stream input = File.OpenRead(inputFileName),
keyIn = File.OpenRead(keyFileName))
{
DecryptFile(input, keyIn, passwd, defaultFileName);
}
}
/**
* decrypt the passed in message stream
*/
private static void DecryptFile(
Stream inputStream,
Stream keyIn,
char[] passwd,
string defaultFileName)
{
inputStream = PgpUtilities.GetDecoderStream(inputStream);
try
{
PgpObjectFactory pgpF = new PgpObjectFactory(inputStream);
PgpEncryptedDataList enc;
PgpObject o = pgpF.NextPgpObject();
//
// the first object might be a PGP marker packet.
//
if (o is PgpEncryptedDataList)
{
enc = (PgpEncryptedDataList)o;
}
else
{
enc = (PgpEncryptedDataList)pgpF.NextPgpObject();
}
//
// find the secret key
//
PgpPrivateKey sKey = null;
PgpPublicKeyEncryptedData pbe = null;
PgpSecretKeyRingBundle pgpSec = new PgpSecretKeyRingBundle(
PgpUtilities.GetDecoderStream(keyIn));
foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
{
sKey = PgpExampleUtilities.FindSecretKey(pgpSec, pked.KeyId, passwd);
if (sKey != null)
{
pbe = pked;
break;
}
}
if (sKey == null)
{
throw new ArgumentException("secret key for message not found.");
}
Stream clear = pbe.GetDataStream(sKey);
PgpObjectFactory plainFact = new PgpObjectFactory(clear);
PgpObject message = plainFact.NextPgpObject();
if (message is PgpCompressedData)
{
PgpCompressedData cData = (PgpCompressedData)message;
PgpObjectFactory pgpFact = new PgpObjectFactory(cData.GetDataStream());
message = pgpFact.NextPgpObject();
}
if (message is PgpLiteralData)
{
PgpLiteralData ld = (PgpLiteralData)message;
string outFileName = ld.FileName;
if (outFileName.Length == 0)
{
outFileName = defaultFileName;
}
Stream fOut = File.Create(outFileName);
Stream unc = ld.GetInputStream();
Streams.PipeAll(unc, fOut);
fOut.Close();
}
else if (message is PgpOnePassSignatureList)
{
throw new PgpException("encrypted message contains a signed message - not literal data.");
}
else
{
throw new PgpException("message is not a simple encrypted file - type unknown.");
}
if (pbe.IsIntegrityProtected())
{
if (!pbe.Verify())
{
Console.Error.WriteLine("message failed integrity check");
}
else
{
Console.Error.WriteLine("message integrity check passed");
}
}
else
{
Console.Error.WriteLine("no message integrity check");
}
}
catch (PgpException e)
{
Console.Error.WriteLine(e);
Exception underlyingException = e.InnerException;
if (underlyingException != null)
{
Console.Error.WriteLine(underlyingException.Message);
Console.Error.WriteLine(underlyingException.StackTrace);
}
}
}
public static void EncryptFile(
string outputFileName,
string inputFileName,
string encKeyFileName,
bool armor,
bool withIntegrityCheck)
{
PgpPublicKey encKey = PgpExampleUtilities.ReadPublicKey(encKeyFileName);
using (Stream output = File.Create(outputFileName))
{
EncryptFile(output, inputFileName, encKey, armor, withIntegrityCheck);
}
}
private static void EncryptFile(
Stream outputStream,
string fileName,
PgpPublicKey encKey,
bool armor,
bool withIntegrityCheck)
{
if (armor)
{
outputStream = new ArmoredOutputStream(outputStream);
}
try
{
byte[] bytes = PgpExampleUtilities.CompressFile(fileName, CompressionAlgorithmTag.Zip);
PgpEncryptedDataGenerator encGen = new PgpEncryptedDataGenerator(
SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom());
encGen.AddMethod(encKey);
Stream cOut = encGen.Open(outputStream, bytes.Length);
cOut.Write(bytes, 0, bytes.Length);
cOut.Close();
if (armor)
{
outputStream.Close();
}
}
catch (PgpException e)
{
Console.Error.WriteLine(e);
Exception underlyingException = e.InnerException;
if (underlyingException != null)
{
Console.Error.WriteLine(underlyingException.Message);
Console.Error.WriteLine(underlyingException.StackTrace);
}
}
}
}
public class PgpExampleUtilities
{
/**
* Search a secret key ring collection for a secret key corresponding to keyID if it
* exists.
*
* #param pgpSec a secret key ring collection.
* #param keyID keyID we want.
* #param pass passphrase to decrypt secret key with.
* #return
* #throws PGPException
* #throws NoSuchProviderException
*/
internal static PgpPrivateKey FindSecretKey(PgpSecretKeyRingBundle pgpSec, long keyID, char[] pass)
{
PgpSecretKey pgpSecKey = pgpSec.GetSecretKey(keyID);
if (pgpSecKey == null)
{
return null;
}
return pgpSecKey.ExtractPrivateKey(pass);
}
internal static PgpPublicKey ReadPublicKey(string fileName)
{
using (Stream keyIn = File.OpenRead(fileName))
{
return ReadPublicKey(keyIn);
}
}
internal static PgpPublicKey ReadPublicKey(Stream input)
{
PgpPublicKeyRingBundle pgpPub = new PgpPublicKeyRingBundle(
PgpUtilities.GetDecoderStream(input));
//
// we just loop through the collection till we find a key suitable for encryption, in the real
// world you would probably want to be a bit smarter about this.
//
foreach (PgpPublicKeyRing keyRing in pgpPub.GetKeyRings())
{
foreach (PgpPublicKey key in keyRing.GetPublicKeys())
{
if (key.IsEncryptionKey)
{
return key;
}
}
}
throw new ArgumentException("Can't find encryption key in key ring.");
}
internal static byte[] CompressFile(string fileName, CompressionAlgorithmTag algorithm)
{
MemoryStream bOut = new MemoryStream();
PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(algorithm);
PgpUtilities.WriteFileToLiteralData(comData.Open(bOut), PgpLiteralData.Binary,
new FileInfo(fileName));
comData.Close();
return bOut.ToArray();
}
}
public class Streams
{
private const int BufferSize = 512;
public static void PipeAll(Stream inStr, Stream outStr)
{
byte[] bs = new byte[BufferSize];
int numRead;
while ((numRead = inStr.Read(bs, 0, bs.Length)) > 0)
{
outStr.Write(bs, 0, numRead);
}
}
}
}
I then call the EncryptFile Method as below:
public void EncryptMyFile()
{
Pgp.EncryptFile(#"C:\ ... Output.pgp", #"C:\ ... Input.txt", #"C:\ ... pubkey.txt", false, false);
}
Used code above and it properly generated a file, but the vendor says that it is "double encrypted".

Decryption Exception - length of the data to decrypt is invalid When add more data

I am trying to decrypt that from the database. The Data is encrypted from the SQL Server
reportItems.DisabilityGroup = Cryptography.ASPEncrypter(reportItems.DisabilityGroup, true);
The above code is when I invoke the decryption method. It works for small data but fails for more data. I get the following order
System.Security.Cryptography.CryptographicException: 'Length of the data to decrypt is invalid.'
private static string DoEncrypt(string Message)
{
// Encrypt string
byte[] Results;
var UTF8 = new UTF8Encoding();
using (var HashProvider = new MD5CryptoServiceProvider())
{
var TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(PassPhrase));
//var TDESAlgorithm = new TripleDESCryptoServiceProvider()
//{
// Key = TDESKey,
// Mode = CipherMode.ECB,
// Padding = PaddingMode.PKCS7
//};
using (var TDESAlgorithm = new TripleDESCryptoServiceProvider())
{
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
if (Message == null)
return "";
var DataToEncrypt = UTF8.GetBytes(Message);
try
{
var Encryptor = TDESAlgorithm.CreateEncryptor();
Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
}
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
}
}
return Convert.ToBase64String(Results);
}
private static string DoDecrypt(string Message)
{
// Decrypt string
byte[] Results;
var UTF8 = new UTF8Encoding();
using (var HashProvider = new MD5CryptoServiceProvider())
{
var TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(PassPhrase));
using (var TDESAlgorithm = new TripleDESCryptoServiceProvider())
{
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
//var DataToDecrypt = Convert.FromBase64String(Message);
var DataToDecrypt = new byte[0];
if (!IsBase64String(Message, out DataToDecrypt))
{
return Message;
}
try
{
var Decryptor = TDESAlgorithm.CreateDecryptor();
Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
}
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
}
}
return UTF8.GetString(Results);
}
public static bool IsBase64String(string base64String, out byte[] bytes)
{
bytes = null;
if (string.IsNullOrEmpty(base64String) || base64String.Length % 4 != 0
|| base64String.Contains(" ") || base64String.Contains("\t") || base64String.Contains("\r") || base64String.Contains("\n"))
return false;
try
{
bytes = Convert.FromBase64String(base64String);
return true;
}
catch (Exception)
{
// Handle the exception
}
return false;
}
public static string ASPEncrypter(string PriorValue, bool Decrypt)
{
// Public function to encrypt/decrypt string
if (String.IsNullOrWhiteSpace(PriorValue))
return "";
var Result = string.Empty;
if (Decrypt)
Result = DoDecrypt(PriorValue);
else
Result = DoEncrypt(PriorValue);
return Result;
}

Cannot get link from file sent up to dropbox getting message WaitingForActivation

I'm attempting to upload a file and then get a link for it once it has been uploaded.
I seem to be sending up the file without a problem but when I go to obtain a link to the file, it sends back WaitingForActivation.
Here's my code:
private async Task ChunkUpload2(DropboxClient client, string folder, string fileName)
{
try
{
Console.WriteLine("Starting file upload...");
var path = $"{folder}/{Path.GetFileName(fileName)}";
// Chunk size is 128KB.
const int chunkSize = 4096 * 1024;
if (!File.Exists(fileName))
{
Console.WriteLine();
Console.WriteLine($"File does not exist: {fileName}");
Console.WriteLine();
return;
}
using (var stream = new MemoryStream(File.ReadAllBytes(fileName)))
{
int numChunks = (int) Math.Ceiling((double) stream.Length / chunkSize);
byte[] buffer = new byte[chunkSize];
string sessionId = null;
if (numChunks == 1)
{
using (var memStream = new MemoryStream(buffer, 0, chunkSize))
{
Console.WriteLine($"Sending file: {path}");
var tst = await client.Files.UploadAsync(path, WriteMode.Overwrite.Instance, body: memStream);
//Console.WriteLine(updated.Result);
}
}
else
{
for (var idx = 0; idx < numChunks; idx++)
{
Console.WriteLine($"Uploading chunk {idx + 1} / {numChunks}.");
var byteRead = stream.Read(buffer, 0, chunkSize);
using (MemoryStream memStream = new MemoryStream(buffer, 0, byteRead))
{
var cursor = new UploadSessionCursor(sessionId, (ulong) (chunkSize * idx));
if (idx == numChunks - 1)
{
Console.WriteLine($"Finalizing file: {path}");
var response = await client.Files.UploadSessionFinishAsync(cursor, new CommitInfo(path), memStream);
}
else
{
await client.Files.UploadSessionAppendV2Async(cursor, body: memStream);
}
}
}
}
var url = string.Empty;
var link = await client.Sharing.ListSharedLinksAsync(path);
if (link.Links.Count == 0)
{
var result = client.Sharing.CreateSharedLinkWithSettingsAsync(path);
url = result.Result.Url;
}
else
{
url = link.Links[0].Url;
}
Console.WriteLine();
Console.WriteLine("Dropbox Download Link:");
Console.WriteLine(url);
Console.WriteLine();
//Console.ReadKey();
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
The last portion, at CreateSharedLinkWithSettingsAsync is where it's giving me back no share urls. Instead it returns the code above.
I'm getting this message:
Any suggestions on how to 'Active' this file? I'm assuming I'm missing something?

Error getting the File download when Multiple User at same time and same file

Getting the following error on file download by multiple users at the same time.
The process cannot access the file
'C:\ Document Repository\354\Calibration\ffc26999-4a5a-44df-9e00-fcaa3e70570c # file_example_JPG_500kB.jpg_enc' because it is being used by another process.
How to resolve this issue in a C# MVC web application?
public ActionResult GetDRFileDownload(long lng_DocRepositoryID = 0, long lng_OrganizationClinicFolderID = 0, long lng_DocRepositoryFolderID = 0, string flag = "", HttpPostedFileBase file = null) /// We can use the over all project for download the documents /images
{
string DatabasePath = "";
string filename = "";
long _UserId = GetUserId();
// string folderName = "";
string pathString = "";
string pathFileName = pathString + "\\" + filename;
string FileDownloadName = "";
if (flag == "ClinicDocument")
{
HttpResponseMessage response = serviceObj.GetResponse("api/JDocumentUpdate/RepDocumentDetails?lng_DocID=" + lng_OrganizationClinicFolderID);
response.EnsureSuccessStatusCode();
var GetData = response.Content.ReadAsAsync<DocumentClass>().Result;
//var GetData = unitofwork.DRRepository.GetRepositoryFolderDocumentById(lng_OrganizationClinicFolderID);
if (GetData == null || GetData.str_Path == null || GetData.str_Path == "")
return Json(new { result = false, strMsg = "File not found" }, JsonRequestBehavior.AllowGet);
FileDownloadName = GetData.str_Name;
DatabasePath = GetData.str_Path;
}
// var fileContents = System.IO.File.ReadAllText(Server.MapPath(Newpath + "_enc"));
// UploadDocument obj = new UploadDocument();
string DatabasePathEnc = DatabasePath + "_enc";
string input = ""; string output = "";
//string filePath = Server.MapPath(Url.Content(input1));
input = System.IO.Path.Combine(System.Environment.CurrentDirectory, DatabasePathEnc);
output = System.IO.Path.Combine(System.Environment.CurrentDirectory, DatabasePath);
FileInfo opath1 = new FileInfo(output);
output = opath1.Directory + "/" + _UserId + opath1.Name;
string Message = this.DecryptFile(input, output);// To decrypt the file
output = opath1.Directory + "/" + _UserId + opath1.Name;
opath1 = new FileInfo(output);
if (opath1.Exists)
{
byte[] bytes = System.IO.File.ReadAllBytes(opath1.FullName);
if (opath1.Extension == ".pdf")
{
System.IO.File.Delete(output);
return File(bytes, "application/pdf");
}
else if (opath1.Extension == ".png")
{
Image img = Image.FromFile(opath1.FullName);
byte[] arr;
using (MemoryStream ms = new MemoryStream())
{
img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
arr = ms.ToArray();
}
img.Dispose();
System.IO.File.Delete(output);
return File(arr, "image/png");
}
else if (opath1.Extension == ".jpeg" || opath1.Extension == ".jpg_enc")
{
Image img = Image.FromFile(opath1.FullName);
byte[] arr;
using (MemoryStream ms = new MemoryStream())
{
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
arr = ms.ToArray();
}
img.Dispose();
System.IO.File.Delete(output);
return File(arr, "image/jpeg");
}
else if (opath1.Extension == ".jpg")
{
Image img = Image.FromFile(opath1.FullName);
byte[] arr;
using (MemoryStream ms = new MemoryStream())
{
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
arr = ms.ToArray();
}
img.Dispose();
System.IO.File.Delete(output);
return File(arr, "image/jpg");
}
else
{
System.IO.File.Delete(output);
}
return File(bytes, System.Net.Mime.MediaTypeNames.Application.Octet, FileDownloadName);
}
else
{
return Json(new { result = false, strMsg = "File not found" }, JsonRequestBehavior.AllowGet);
}
}
This for Decrypt the File
public string DecryptFile(string inputFilePath, string outputfilePath)
{
string s = "Success";
try
{
string EncryptionKey = "MAKV2SPBNI99212";
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
FileInfo opath1 = new FileInfo(inputFilePath);
if (opath1.Exists)
{
using (FileStream fsInput = new FileStream(inputFilePath, FileMode.Open))
{
using (CryptoStream cs = new CryptoStream(fsInput, encryptor.CreateDecryptor(), CryptoStreamMode.Read))
{
opath1 = new FileInfo(outputfilePath);
if (opath1.Exists)
{
opath1.Refresh();
opath1.Delete();
}
using (FileStream fsOutput = new FileStream(outputfilePath, FileMode.Create))
{
int data;
while ((data = cs.ReadByte()) != -1)
{
fsOutput.WriteByte((byte)data);
}
fsOutput.Close();
}
}
}
}
}
}
catch (Exception e)
{
s = e.Message;
}
return s;
}
Get the File Name and Path from Database
Download the file based on the format

C# UWP File output for encryption and decryption code seems to stop working for files over 128 MB

Wrote some C# UWP code to encrypt files using the new encryption engine, and recently added code to make it be able to handle more bulky files by splitting the files up into parts and encrypting each part seperately since the libraries encrypt and decrypt functions won't take gigantic buffers. Now, it seems to be in some cases either outputting nothing to the file or giving a "system.exception" error in the Visual Studio debugger, which as you can imagine, isn't very helpful. Here's the code for this part of the program:
private async System.Threading.Tasks.Task encryptFile(StorageFile file, string key)
{
Loading.IsActive = true;
string HashAlgorithmName = HashAlgorithmNames.Md5;
HashAlgorithmProvider HashProvider = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmName);
CryptographicHash HashObject = HashProvider.CreateHash();
Windows.Storage.Streams.IBuffer keyAsBuffer = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf16BE);
HashObject.Append(keyAsBuffer);
Windows.Storage.Streams.IBuffer hashedKeyAsBuffer = HashObject.GetValueAndReset();
string hashedKey = CryptographicBuffer.EncodeToBase64String(hashedKeyAsBuffer);
key = hashedKey;
string algorithmName = SymmetricAlgorithmNames.AesEcbPkcs7;
SymmetricKeyAlgorithmProvider encryptionProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(algorithmName);
Windows.Storage.Streams.IBuffer keyBuffer = CryptographicBuffer.CreateFromByteArray(Encoding.ASCII.GetBytes(key));
CryptographicKey fullKey = encryptionProvider.CreateSymmetricKey(keyBuffer);
Stream fileStream = await file.OpenStreamForReadAsync();
byte[] fileBytes = ReadToEnd(fileStream);
Stream writeFileStream = await file.OpenStreamForWriteAsync();
IEnumerable<byte[]> splitFileBytes = ArraySplit(fileBytes, 100000000);
writeFileStream.Seek(0, SeekOrigin.Begin);
foreach (byte[] fileBytesFor in splitFileBytes)
{
Windows.Storage.Streams.IBuffer fileBuffer = fileBytesFor.AsBuffer();
Windows.Storage.Streams.IBuffer encryptedFileBuffer = CryptographicEngine.Encrypt(fullKey, fileBuffer, null);
Stream encryptedFileStream = encryptedFileBuffer.AsStream();
byte[] encryptedFileBytes = ReadToEnd(encryptedFileStream);
await writeFileStream.WriteAsync(encryptedFileBytes, 0, encryptedFileBytes.Length);
writeFileStream.Seek(0, SeekOrigin.End);
}
fileStream.Dispose();
writeFileStream.Dispose();
Loading.IsActive = false;
}
private async System.Threading.Tasks.Task decryptFile(StorageFile file, string key)
{
string HashAlgorithmName = HashAlgorithmNames.Md5;
HashAlgorithmProvider HashProvider = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmName);
CryptographicHash HashObject = HashProvider.CreateHash();
Windows.Storage.Streams.IBuffer keyAsBuffer = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf16BE);
HashObject.Append(keyAsBuffer);
Windows.Storage.Streams.IBuffer hashedKeyAsBuffer = HashObject.GetValueAndReset();
string hashedKey = CryptographicBuffer.EncodeToBase64String(hashedKeyAsBuffer);
key = hashedKey;
string algorithmName = SymmetricAlgorithmNames.AesEcbPkcs7;
SymmetricKeyAlgorithmProvider encryptionProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(algorithmName);
Windows.Storage.Streams.IBuffer keyBuffer = CryptographicBuffer.CreateFromByteArray(Encoding.ASCII.GetBytes(key));
CryptographicKey fullKey = encryptionProvider.CreateSymmetricKey(keyBuffer);
Stream fileStream = await file.OpenStreamForReadAsync();
byte[] fileBytes = ReadToEnd(fileStream);
Stream writeFileStream = await file.OpenStreamForWriteAsync();
Loading.IsActive = true;
writeFileStream.SetLength(0);
IEnumerable<byte[]> splitFileBytes = ArraySplit(fileBytes, 100000000);
writeFileStream.Seek(0, SeekOrigin.Begin);
foreach (byte[] fileBytesFor in splitFileBytes)
{
Windows.Storage.Streams.IBuffer fileBuffer = fileBytesFor.AsBuffer();
Windows.Storage.Streams.IBuffer decryptedFileBuffer = CryptographicEngine.Decrypt(fullKey, fileBuffer, null);
Stream decryptedFileStream = decryptedFileBuffer.AsStream();
byte[] decryptedFileBytes = ReadToEnd(decryptedFileStream);
await writeFileStream.WriteAsync(decryptedFileBytes, 0, decryptedFileBytes.Length);
writeFileStream.Seek(0, SeekOrigin.End);
}
fileStream.Dispose();
writeFileStream.Dispose();
Loading.IsActive = false;
}
public static byte[] StreamToByteArray(Stream inputStream)
{
byte[] bytes = new byte[375000000000000000];
using (MemoryStream memoryStream = new MemoryStream())
{
int count;
while ((count = inputStream.Read(bytes, 0, bytes.Length)) > 0)
{
memoryStream.Write(bytes, 0, count);
}
return memoryStream.ToArray();
}
}
public static byte[] ReadToEnd(System.IO.Stream stream)
{
long originalPosition = 0;
if (stream.CanSeek)
{
originalPosition = stream.Position;
stream.Position = 0;
}
try
{
byte[] readBuffer = new byte[4096];
int totalBytesRead = 0;
int bytesRead;
while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
{
totalBytesRead += bytesRead;
if (totalBytesRead == readBuffer.Length)
{
int nextByte = stream.ReadByte();
if (nextByte != -1)
{
byte[] temp = new byte[readBuffer.Length * 2];
Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
readBuffer = temp;
totalBytesRead++;
}
}
}
byte[] buffer = readBuffer;
if (readBuffer.Length != totalBytesRead)
{
buffer = new byte[totalBytesRead];
Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
}
return buffer;
}
finally
{
if (stream.CanSeek)
{
stream.Position = originalPosition;
}
}
}
private IEnumerable<byte[]> ArraySplit(byte[] bArray, int intBufforLengt)
{
int bArrayLenght = bArray.Length;
byte[] bReturn = null;
int i = 0;
for (; bArrayLenght > (i + 1) * intBufforLengt; i++)
{
bReturn = new byte[intBufforLengt];
Array.Copy(bArray, i * intBufforLengt, bReturn, 0, intBufforLengt);
yield return bReturn;
}
int intBufforLeft = bArrayLenght - i * intBufforLengt;
if (intBufforLeft > 0)
{
bReturn = new byte[intBufforLeft];
Array.Copy(bArray, i * intBufforLengt, bReturn, 0, intBufforLeft);
yield return bReturn;
}
}

Categories