Need help T_T
I'm running the code below to Decrypt an exe File I'm trying to Run it and Automatically execute the Decrypted file would it be possible to execute it without saving it's data to the disk?
I'm also trying to run it without the need of specifying the encrypted file name but have no idea what changes need to be done for this to happen or if it's even possible.
FileInfo encFile = new FileInfo("7GNTBBASDADASDASDASDASDASDASDASDSW7VBKGUX5TB5XBXDG3W4DWC6K6JBMTG7C2OYEHNPSN4PE6JYLJDUA"); // < File name in the current directory
const int ReadBufferSize = 64 * 1024;
static void Main(string[] args)
{
{
// DECRYPTION
FileInfo encFile = new FileInfo("7GNTBBASDADASDASDASDASDASDASDASDSW7VBKGUX5TB5XBXDG3W4DWC6K6JBMTG7C2OYEHNPSN4PE6JYLJDUA"); // < File name in the current directory
byte[] iv = Convert.FromBase64String("SWW/HAWEWQF/F2d/WrSSA==");
byte[] key = Convert.FromBase64String("ASDSADSAwwqIM221vASXG1221nqk=");
// DECRYPTION
// DECRYPTION
using (FileStream inp = encFile.OpenRead())
using (AesManaged aes = new AesManaged())
{
aes.KeySize = 256;
aes.Mode = CipherMode.CBC;
aes.IV = iv;
aes.Key = key;
using (CryptoStream cs = new CryptoStream(inp, aes.CreateDecryptor(), CryptoStreamMode.Read))
{
// crypted file structure: {name length x4}{full file name}{data length x8}{data}{sha512 hash of data x64}
byte[] nameLengthBits = new byte[2];
if (cs.Read(nameLengthBits, 0, 2) != 2)
{
Console.Error.WriteLine("ERROR: Failed reading file name size");
return;
}
ushort nameLength = BitConverter.ToUInt16(nameLengthBits, 0);
byte[] originalName = new byte[nameLength];
if (cs.Read(originalName, 0, nameLength) != nameLength)
{
Console.Error.WriteLine("ERROR: Failed reading file name");
return;
}
string fileName = Encoding.UTF8.GetString(originalName);
byte[] dataLengthBits = new byte[8];
if (cs.Read(dataLengthBits, 0, dataLengthBits.Length) != dataLengthBits.Length)
{
Console.Error.WriteLine("ERROR: Failed reading data length");
return;
}
long dataLength = BitConverter.ToInt64(dataLengthBits, 0);
string outputFileName = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(fileName));
if (File.Exists(outputFileName))
{
}
byte[] decryptedHash;
long totalRead = 0;
using (FileStream outputStream = new FileStream(outputFileName, FileMode.CreateNew, FileAccess.Write, FileShare.Read))
using (SHA512Managed hasher = new SHA512Managed())
{
byte[] buffer = new byte[ReadBufferSize];
long bytesRemaining = dataLength;
while (bytesRemaining > 0)
{
int readingThisRound = ReadBufferSize < bytesRemaining ? ReadBufferSize : (int)bytesRemaining;
int bytesRead = cs.Read(buffer, 0, readingThisRound);
totalRead += bytesRead;
// dump decrypted data to file
outputStream.Write(buffer, 0, bytesRead); }
//
//
hasher.TransformFinalBlock(buffer, 0, 0);
decryptedHash = hasher.Hash;}
byte[] originalHashBits = new byte[64];
if (cs.Read(originalHashBits, 0, originalHashBits.Length) != originalHashBits.Length) using (FileStream outputStream = new FileStream(outputFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
}
if (originalHashBits.SequenceEqual(decryptedHash))
Related
I'm getting the infamous "Padding is invalid and cannot be removed." error. However, despite ensuring the padding mode is set as well as verifying the key is the same on both encrypt and decrypt. I can't get past the issue.
What am I doing wrong o' great sages of the internet?
//Targeting .Net 4.5.2
//Key is hard coded, ONLY while working through this error in a minimum repo.
byte[] testKey = Convert.FromBase64String("KN1df3fOkLmSPyOP4r+grlVFDC/JVlWuew1u/hDGvUU=");
//Called to Encrypt ("D:\\Assets\\", "Test.txt")
public void DoWork(string filePath, string fileName){
CryptographyUtil crypto = new CryptographyUtil(testKey);
crypto.EncryptFile(filePath, fileName));
}
//Called to Decrypt ("D:\\Assets\\", "Test.txt.dat")
public void UnDoWork(string filePath, string fileName){
CryptographyUtil crypto = new CryptographyUtil(testKey);
crypto.DecryptFile(filePath, fileName));
}
public class CryptographyUtil(){
RijndaelManaged rjndl;
RNGCryptoServiceProvider cRng;
public CryptographyUtil(byte[] key, int keySize = 256, int blockSize = 256) {
cRng = new RNGCryptoServiceProvider();
rjndl = new RijndaelManaged();
rjndl.Key = key;
rjndl.KeySize = keySize;
rjndl.BlockSize = blockSize;
rjndl.Mode = CipherMode.CBC;
rjndl.Padding = PaddingMode.PKCS7;
}
public void EncryptFile(string filePath, string fileName) {
string inputFilePath = Path.Combine(filePath, fileName);
if(!File.Exists(inputFilePath)) {
throw new FileLoadException("Unable to locate or open file.", inputFilePath);
}
string outputDirectory = Path.Combine(filePath, "Encrypted");
if(!Directory.Exists(outputDirectory)){
Directory.CreateDirectory(outputDirectory);
}
string outputPath = Path.Combine(outputDirectory, fileName + ".dat");
//Create a unique IV each time
byte[] iv = new byte[rjndl.BlockSize / 8]
cRng.GetBytes(iv);
byte[] ivSize = BitConverter.GetBytes(iv.Length);
ICryptoTransform encryptor = rjndl.CreateEncryptor(rjndl.Key, iv);
using(FileStream readStream = File.OpenRead(inputFilePath)) {
using(FileStream writeStream = new FileStream(outputPath, FileMode.Create)) {
using(CryptoStream encryptStream = new CryptoStream(writeStream, encryptor, CryptoStreamMode.Write)) {
//Write the following to the file before the encrypted data:
// - length of the IV
// - the IV
writeStream.Write(ivSize, 0, ivSize.Length);
writeStream.Write(iv, 0, iv.Length);
readStream.CopyTo(encryptStream);
readStream.Flush();
encryptStream.FlushFinalBlock();
encryptStream.Close();
}
writeStream.Close();
}
readStream.Close();
}
}
public void DecryptFile(string filePath, string fileName) {
string outputDirectory = Path.Combine(filePath, "Decrypted");
if(!Directory.Exists(outputDirectory)){
Directory.CreateDirectory(outputDirectory);
}
//Remove the ".dat" from the end of the file
string outputFilePath = Path.Combine(outputDirectory, fileName.Substring(0, fileName.LastIndexOf('.')));
if(File.Exists(outputFilePath)){
File.Delete(outputFilePath);
}
using(FileStream readStream = File.OpenRead(Path.Combine(filePath, fileName))) {
//Size buffer for IV Length (int = 4 bytes)
byte[] buffer = new byte[4];
readStream.Read(buffer, 0, buffer.Length);
int ivLength = BitConverter.ToUInt16(buffer, 0);
//Re-size buffer for IV
buffer = new byte[ivLength];
//Read IV to buffer and use to create decryptor
readStream.Read(buffer, 0, ivLength);
//Use IV in buffer to create decryptor
ICryptoTransform decryptor = rjndl.CreateDecryptor(rjndl.Key, buffer);
buffer = new byte[1024];
using(FileStream writeStream = new FileStream(outputFilePath, FileMode.Create)) {
using(CryptoStream decryptStream = new CryptoStream(readStream, decryptor, CryptoStreamMode.Read)) {
//FIXME: Padding Error
int readIdx = decryptStream.Read(buffer, 0, buffer.Length);
while(readIdx > 0) {
writeStream.Write(buffer, 0, readIdx);
readIdx = decryptStream.Read(buffer, 0, buffer.Length);
}
decryptStream.Flush();
decryptStream.Close();
}
writeStream.Close();
}
readStream.Close();
}
}
}
Using RijndaelManaged as I have to create encrypted packages for legacy software that uses it to decrypt.
I have ASP .NET C# project and I want to encrypt file with multiple public keys from certificates using X509Store and I am using this function to encrypt the file its fine but I need it for group of certificates:
private static void EncryptFile(string inFile, RSACryptoServiceProvider rsaPublicKey)
{
using (AesManaged aesManaged = new AesManaged())
{
// Create instance of AesManaged for
// symetric encryption of the data.
aesManaged.KeySize = 256;
aesManaged.BlockSize = 128;
aesManaged.Mode = CipherMode.CBC;
using (ICryptoTransform transform = aesManaged.CreateEncryptor())
{
RSAPKCS1KeyExchangeFormatter keyFormatter = new RSAPKCS1KeyExchangeFormatter(rsaPublicKey);
byte[] keyEncrypted = keyFormatter.CreateKeyExchange(aesManaged.Key, aesManaged.GetType());
// Create byte arrays to contain
// the length values of the key and IV.
byte[] LenK = new byte[4];
byte[] LenIV = new byte[4];
int lKey = keyEncrypted.Length;
LenK = BitConverter.GetBytes(lKey);
int lIV = aesManaged.IV.Length;
LenIV = BitConverter.GetBytes(lIV);
// Write the following to the FileStream
// for the encrypted file (outFs):
// - length of the key
// - length of the IV
// - ecrypted key
// - the IV
// - the encrypted cipher content
int startFileName = inFile.LastIndexOf("\\") + 1;
// Change the file's extension to ".enc"
string outFile = encrFolder + inFile.Substring(startFileName, inFile.LastIndexOf(".") - startFileName) + ".enc";
Directory.CreateDirectory(encrFolder);
using (FileStream outFs = new FileStream(outFile, FileMode.Create))
{
outFs.Write(LenK, 0, 4);
outFs.Write(LenIV, 0, 4);
outFs.Write(keyEncrypted, 0, lKey);
outFs.Write(aesManaged.IV, 0, lIV);
// Now write the cipher text using
// a CryptoStream for encrypting.
using (CryptoStream outStreamEncrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write))
{
// By encrypting a chunk at
// a time, you can save memory
// and accommodate large files.
int count = 0;
int offset = 0;
// blockSizeBytes can be any arbitrary size.
int blockSizeBytes = aesManaged.BlockSize / 8;
byte[] data = new byte[blockSizeBytes];
int bytesRead = 0;
using (FileStream inFs = new FileStream(inFile, FileMode.Open))
{
do
{
count = inFs.Read(data, 0, blockSizeBytes);
offset += count;
outStreamEncrypted.Write(data, 0, count);
bytesRead += blockSizeBytes;
}
while (count > 0);
inFs.Close();
}
outStreamEncrypted.FlushFinalBlock();
outStreamEncrypted.Close();
}
outFs.Close();
}
}
}
}
my goal is to encrypt large (cca 10 GB) input file and append it to an existing System.IO.Packaging Package. I can use .NET Framework 3.5 only and no third-party libraries.
I tried maybee ten methods with no success. I tried to read the input to Stream, encrypt it and save to PackagePart. I tried to read the input file byte after byte, then encrypt byte read and append it to Stream from PackagePart too. Everytime I found a new issue (e.g. CryptoStream does not supports seeking and so on).
Could you show me the right way, please?
//method to create zip file (just a sample)
public static void AppendToZip(SomeType encryptedData)
{
using (Package zip = Package.Open(#"C:\myarchive.zip", FileMode.OpenOrCreate))
{
Uri uri = PackUriHelper.CreatePartUri(new Uri("/files/test.enc", UriKind.Relative));
try
{
part = zip.GetPart(uri);
}
catch
{
}
if (part == null)
{
part = zip.CreatePart(uri, "", CompressionOption.Maximum);
}
using (Stream dest = part.GetStream())
{
//how to write encryptedData to destination stream?
}
}
}
//sample method for encrypting a file
private static void Encrypt(string inputFile, string cryptFile, byte[] passwordBytes, byte[] saltBytes)
{
FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);
RijndaelManaged AES = new RijndaelManaged();
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Padding = PaddingMode.Zeros;
AES.Mode = CipherMode.CBC;
CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateEncryptor(), 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();
}
Try this out - play around with block size for performance. I did this with a 3.5 GB ISO successfully. However the zip file is much larger compressing encrypted content, so as the other guy said you're better compressing the file FIRST and then encrypting it. But I don't know your requirements, so here's this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Packaging;
namespace ZipTest
{
class Program
{
static void Main(string[] args)
{
// Block size we apply to all reads / writes
const int BLOCK_SIZE = 65536;
// The zip file we're using
var zipFileName = #"C:\temp\ZipSO\MyZip.zip";
// Password for encryption
var password = "ThisIsMyPassword";
// Name of temp file where we'll encrypt the file first
var intermediateFile = #"C:\temp\ZipSO\Intermediate_" + Guid.NewGuid().ToString();
// File we're encrypting / adding to archive
var inputFile = #"C:\temp\ZipSO\InputFile.txt";
// Salt for encryption
var salt = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
// For the new / existing package part
PackagePart part = null;
// Open the archive
using (var zip = Package.Open(zipFileName, System.IO.FileMode.OpenOrCreate))
{
// Uri for the part
var uri = PackUriHelper.CreatePartUri(new Uri("/files/test.enc", UriKind.Relative));
// Get existing part if found, or create new
if (zip.PartExists(uri))
part = zip.GetPart(uri);
else
part = zip.CreatePart(uri, "", CompressionOption.Maximum);
// Encrypt the file first
var passBytes = System.Text.Encoding.ASCII.GetBytes(password);
using (var fs = new System.IO.FileStream(intermediateFile, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write))
{
var key = new System.Security.Cryptography.Rfc2898DeriveBytes(passBytes, salt, 1000);
var keySize = 256;
var blockSize = 128;
var aes = new System.Security.Cryptography.RijndaelManaged()
{
KeySize = keySize,
BlockSize = blockSize,
Key = key.GetBytes(keySize / 8),
IV = key.GetBytes(blockSize / 8),
Padding = System.Security.Cryptography.PaddingMode.Zeros,
Mode = System.Security.Cryptography.CipherMode.CBC
};
using (var fsSource = new System.IO.FileStream(inputFile, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
using (var cs = new System.Security.Cryptography.CryptoStream(fs, aes.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
{
var readBytes = new byte[BLOCK_SIZE];
int read;
while ((read = fsSource.Read(readBytes, 0, BLOCK_SIZE)) != 0)
{
cs.Write(readBytes, 0, read);
}
cs.Close();
}
fsSource.Close();
}
fs.Close();
}
// Now add it to the archive
using (var p = part.GetStream(System.IO.FileMode.OpenOrCreate))
{
using (var source = new System.IO.FileStream(intermediateFile, System.IO.FileMode.Open, System.IO.FileAccess.Read))
using (var bw = new System.IO.BinaryWriter(p))
{
var readBytes = new byte[BLOCK_SIZE];
int read;
while ((read = source.Read(readBytes, 0, BLOCK_SIZE)) != 0)
{
bw.Write(readBytes.Take(read).ToArray());
}
}
}
// Clean up the intermediate
System.IO.File.Delete(intermediateFile);
}
}
}
}
I was encrypting and decrypting the SQL Server database .mdf and .ldf files after detach and while attaching the decrypted files I was getting the following error message
The header for file 'C:\DB\Test.mdf' is not a valid database file header. The FILE SIZE property is incorrect .
Please find my below C# code I was using for .mdf, the same applies for my .ldf files too
private const int KEY_SIZE_BYTES = 32;
private const int IV_SIZE_BYTES = 16;
private const string DBFILENAME = #"C:\DB\Test.mdf"; ;
public void EncryptandDecrypt()
{
var rand = new Random();
using (var fs = File.Open(DBFILENAME, FileMode.Create, FileAccess.Write, FileShare.None))
{
byte[] buffer = new byte[10000];
for (int i = 0; i < 100; ++i)
{
rand.NextBytes(buffer);
fs.Write(buffer, 0, buffer.Length);
}
}
string key = GenerateRandomKey();
Encrypt(DBFILENAME, #"C:\DB\temp\Test.mdf", key);
Decrypt(#"C:\DB\temp\Test.mdf", DBFILENAME, key);
}
public string GenerateRandomKey()
{
byte[] key = new byte[KEY_SIZE_BYTES];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(key);
}
return Convert.ToBase64String(key);
}
public void Encrypt(string inputFile, string outputFile, string key)
{
const int BUFFER_SIZE = 8192;
byte[] buffer = new byte[BUFFER_SIZE];
byte[] keyBytes = Convert.FromBase64String(key);
byte[] ivBytes = new byte[IV_SIZE_BYTES];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(ivBytes);
}
using (var inputStream = File.Open(inputFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (var outputStream = File.Open(outputFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
outputStream.Write(ivBytes, 0, ivBytes.Length);
using (var cryptoAlgo = Aes.Create())
{
using (var encryptor = cryptoAlgo.CreateEncryptor(keyBytes, ivBytes))
{
using (var cryptoStream = new CryptoStream(outputStream, encryptor, CryptoStreamMode.Write))
{
int count;
while ((count = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
cryptoStream.Write(buffer, 0, count);
}
}
}
}
}
}
}
public void Decrypt(string inputFile, string outputFile, string key)
{
const int BUFFER_SIZE = 8192;
byte[] buffer = new byte[BUFFER_SIZE];
byte[] keyBytes = Convert.FromBase64String(key);
byte[] ivBytes = new byte[IV_SIZE_BYTES];
using (var inputStream = File.Open(inputFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
inputStream.Read(ivBytes, 0, ivBytes.Length);
using (var outputStream = File.Open(outputFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (var cryptoAlgo = Aes.Create())
{
using (var decryptor = cryptoAlgo.CreateDecryptor(keyBytes, ivBytes))
{
using (var cryptoStream = new CryptoStream(inputStream, decryptor, CryptoStreamMode.Read))
{
int count;
while ((count = cryptoStream.Read(buffer, 0, buffer.Length)) > 0)
{
outputStream.Write(buffer, 0, count);
}
}
}
}
}
}
}
I have tested this code and it was ok. I think you probably get the wrong file from temp folder or something like that for header exception. if you get the access error when you're putting back the file then you have to set the proper permissions for the decrypted file.
Also you need to remove the following code from your EncryptDecrypt method and test a real database file:
var rand = new Random();
using (var fs = File.Open(DBFILENAME, FileMode.Create, FileAccess.Write, FileShare.None))
{
byte[] buffer = new byte[10000];
for (int i = 0; i < 100; ++i)
{
rand.NextBytes(buffer);
fs.Write(buffer, 0, buffer.Length);
}
}
It makes a dummy file that server can not read.
I am having some trouble getting a asp.net C# file encryption / decryption process to work. I can get the file uploaded and ecrypted, but cannot get the decryption to work.
I get the error: Exception Details: System.Security.Cryptography.CryptographicException: Bad Data. on the decryption line:
byte[] KeyDecrypted = rsa.Decrypt(KeyEncrypted, false);
Here is my encrypt function:
private void EncryptFile(string inFile)
{
RijndaelManaged rjndl = new RijndaelManaged();
rjndl.KeySize = 256;
rjndl.BlockSize = 256;
rjndl.Mode = CipherMode.CBC;
ICryptoTransform transform = rjndl.CreateEncryptor();
byte[] keyEncrypted = rsa.Encrypt(rjndl.Key, false);
byte[] LenK = new byte[4];
byte[] LenIV = new byte[4];
int lKey = keyEncrypted.Length;
LenK = BitConverter.GetBytes(lKey);
int lIV = rjndl.IV.Length;
LenIV = BitConverter.GetBytes(lIV);
int startFileName = inFile.LastIndexOf("\\") + 1;
// Change the file's extension to ".enc"
string outFile = EncrFolder + inFile.Substring(startFileName, inFile.LastIndexOf(".") - startFileName) + ".enc";
lblDecryptFileName.Text = outFile;
using (FileStream outFs = new FileStream(outFile, FileMode.Create))
{
outFs.Write(LenK, 0, 4);
outFs.Write(LenIV, 0, 4);
outFs.Write(keyEncrypted, 0, lKey);
outFs.Write(rjndl.IV, 0, lIV);
using (CryptoStream outStreamEncrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write))
{
int count = 0;
int offset = 0;
int blockSizeBytes = rjndl.BlockSize / 8;
byte[] data = new byte[blockSizeBytes];
int bytesRead = 0;
using (FileStream inFs = new FileStream(inFile, FileMode.Open))
{
do
{
count = inFs.Read(data, 0, blockSizeBytes);
offset += count;
outStreamEncrypted.Write(data, 0, count);
bytesRead += blockSizeBytes;
}
while (count > 0);
inFs.Close();
}
outStreamEncrypted.FlushFinalBlock();
outStreamEncrypted.Close();
}
outFs.Close();
}
}
And here is the decrypt function where the error occurs.
private void DecryptFile(string inFile)
{
// Create instance of Rijndael for
// symetric decryption of the data.
RijndaelManaged rjndl = new RijndaelManaged();
rjndl.KeySize = 256;
rjndl.BlockSize = 256;
rjndl.Mode = CipherMode.CBC;
byte[] LenK = new byte[4];
byte[] LenIV = new byte[4];
string outFile = DecrFolder + inFile.Substring(0, inFile.LastIndexOf(".")) + ".txt";
using (FileStream inFs = new FileStream(EncrFolder + inFile, FileMode.Open))
{
inFs.Seek(0, SeekOrigin.Begin);
inFs.Seek(0, SeekOrigin.Begin);
inFs.Read(LenK, 0, 3);
inFs.Seek(4, SeekOrigin.Begin);
inFs.Read(LenIV, 0, 3);
int lenK = BitConverter.ToInt32(LenK, 0);
int lenIV = BitConverter.ToInt32(LenIV, 0);
int startC = lenK + lenIV + 8;
int lenC = (int)inFs.Length - startC;
// Create the byte arrays for
// the encrypted Rijndael key,
// the IV, and the cipher text.
byte[] KeyEncrypted = new byte[lenK];
byte[] IV = new byte[lenIV];
// Extract the key and IV
// starting from index 8
// after the length values.
inFs.Seek(8, SeekOrigin.Begin);
inFs.Read(KeyEncrypted, 0, lenK);
inFs.Seek(8 + lenK, SeekOrigin.Begin);
inFs.Read(IV, 0, lenIV);
Directory.CreateDirectory(DecrFolder);
byte[] KeyDecrypted = rsa.Decrypt(KeyEncrypted, false);
ICryptoTransform transform = rjndl.CreateDecryptor(KeyDecrypted, IV);
using (FileStream outFs = new FileStream(outFile, FileMode.Create))
{
int count = 0;
int offset = 0;
int blockSizeBytes = rjndl.BlockSize / 8;
byte[] data = new byte[blockSizeBytes];
inFs.Seek(startC, SeekOrigin.Begin);
using (CryptoStream outStreamDecrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write))
{
do
{
count = inFs.Read(data, 0, blockSizeBytes);
offset += count;
outStreamDecrypted.Write(data, 0, count);
}
while (count > 0);
outStreamDecrypted.FlushFinalBlock();
outStreamDecrypted.Close();
}
outFs.Close();
}
inFs.Close();
}
}
Any help on this would be great! I am not an RSA encryption expert and have been reading a lot of posts but still not able to come up with a solution.
I have finally figured this out. The code worked well in a desktop application when I tried it there. It just didn't work in the asp.net 4 web application I was trying to write. The issue was the RSA object wasn't persisted through the session. So, the RSA object was created okay. The file was encrypted okay. But when I went to decrypt the file the RSA object was not there. The error message of System.Security.Cryptography.CryptographicException: Bad Data is misleading as that wasn't really the issue, the data was fine.
So, when creating the key and the RSA object I used the following:
rsa = new RSACryptoServiceProvider(cspp);
Session["rsa"] = rsa;
Next, when the decryption function is called I added in:
if (rsa == null)
rsa = (RSACryptoServiceProvider)Session["rsa"];
Of course, there is a little more code around this also so catch if there is no key for the RSA session, but this is the high level solution for the issue I was having.
If anyone is looking for this let me know and I can share more of the code.