How to convert this file to top-level statement? - c#

I am using .NET 6 , Visual Studio 2022 Preview on Windows 11 pro x64.
using System;
using System.IO;
using System.Security.Cryptography;
public class HMACSHA512example
{
public static void Main(string[] Fileargs)
{
string dataFile;
string signedFile;
//If no file names are specified, create them.
if (Fileargs.Length < 2)
{
dataFile = #"text.txt";
signedFile = "signedFile.enc";
if (!File.Exists(dataFile))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(dataFile))
{
sw.WriteLine("Here is a message to sign");
}
}
}
else
{
dataFile = Fileargs[0];
signedFile = Fileargs[1];
}
try
{
// Create a random key using a random number generator. This would be the
// secret key shared by sender and receiver.
byte[] secretkey = new Byte[64];
//RNGCryptoServiceProvider is an implementation of a random number generator.
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
// The array is now filled with cryptographically strong random bytes.
rng.GetBytes(secretkey);
// Use the secret key to sign the message file.
SignFile(secretkey, dataFile, signedFile);
// Verify the signed file
VerifyFile(secretkey, signedFile);
}
}
catch (IOException e)
{
Console.WriteLine("Error: File not found", e);
}
} //end main
// Computes a keyed hash for a source file and creates a target file with the keyed hash
// prepended to the contents of the source file.
public static void SignFile(byte[] key, String sourceFile, String destFile)
{
// Initialize the keyed hash object.
using (HMACSHA512 hmac = new HMACSHA512(key))
{
using (FileStream inStream = new FileStream(sourceFile, FileMode.Open))
{
using (FileStream outStream = new FileStream(destFile, FileMode.Create))
{
// Compute the hash of the input file.
byte[] hashValue = hmac.ComputeHash(inStream);
// Reset inStream to the beginning of the file.
inStream.Position = 0;
// Write the computed hash value to the output file.
outStream.Write(hashValue, 0, hashValue.Length);
// Copy the contents of the sourceFile to the destFile.
int bytesRead;
// read 1K at a time
byte[] buffer = new byte[1024];
do
{
// Read from the wrapping CryptoStream.
bytesRead = inStream.Read(buffer, 0, 1024);
outStream.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
}
}
}
return;
} // end SignFile
// Compares the key in the source file with a new key created for the data portion of the file. If the keys
// compare the data has not been tampered with.
public static bool VerifyFile(byte[] key, String sourceFile)
{
bool err = false;
// Initialize the keyed hash object.
using (HMACSHA512 hmac = new HMACSHA512(key))
{
// Create an array to hold the keyed hash value read from the file.
byte[] storedHash = new byte[hmac.HashSize / 8];
// Create a FileStream for the source file.
using (FileStream inStream = new FileStream(sourceFile, FileMode.Open))
{
// Read in the storedHash.
inStream.Read(storedHash, 0, storedHash.Length);
// Compute the hash of the remaining contents of the file.
// The stream is properly positioned at the beginning of the content,
// immediately after the stored hash value.
byte[] computedHash = hmac.ComputeHash(inStream);
// compare the computed hash with the stored value
for (int i = 0; i < storedHash.Length; i++)
{
if (computedHash[i] != storedHash[i])
{
err = true;
}
}
}
}
if (err)
{
Console.WriteLine("Hash values differ! Signed file has been tampered with!");
return false;
}
else
{
Console.WriteLine("Hash values agree -- no tampering occurred.");
return true;
}
} //end VerifyFile
} //end class
Source: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.hmacsha512?view=net-6.0
How to convert this file to top-level statement?

You just have to move your main to the top level, and keep the methods.
using System.Security.Cryptography;
string dataFile;
string signedFile;
//If no file names are specified, create them.
if (args.Length < 2)
{
dataFile = #"text.txt";
signedFile = "signedFile.enc";
if (!File.Exists(dataFile))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(dataFile))
{
sw.WriteLine("Here is a message to sign");
}
}
}
else
{
dataFile = args[0];
signedFile = args[1];
}
try
{
// Create a random key using a random number generator. This would be the
// secret key shared by sender and receiver.
byte[] secretkey = new Byte[64];
//RNGCryptoServiceProvider is an implementation of a random number generator.
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
// The array is now filled with cryptographically strong random bytes.
rng.GetBytes(secretkey);
// Use the secret key to sign the message file.
SignFile(secretkey, dataFile, signedFile);
// Verify the signed file
VerifyFile(secretkey, signedFile);
}
}
catch (IOException e)
{
Console.WriteLine("Error: File not found", e);
}
// Computes a keyed hash for a source file and creates a target file with the keyed hash
// prepended to the contents of the source file.
static void SignFile(byte[] key, String sourceFile, String destFile)
{
// Initialize the keyed hash object.
using (HMACSHA512 hmac = new HMACSHA512(key))
{
using (FileStream inStream = new FileStream(sourceFile, FileMode.Open))
{
using (FileStream outStream = new FileStream(destFile, FileMode.Create))
{
// Compute the hash of the input file.
byte[] hashValue = hmac.ComputeHash(inStream);
// Reset inStream to the beginning of the file.
inStream.Position = 0;
// Write the computed hash value to the output file.
outStream.Write(hashValue, 0, hashValue.Length);
// Copy the contents of the sourceFile to the destFile.
int bytesRead;
// read 1K at a time
byte[] buffer = new byte[1024];
do
{
// Read from the wrapping CryptoStream.
bytesRead = inStream.Read(buffer, 0, 1024);
outStream.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
}
}
}
return;
} // end SignFile
// Compares the key in the source file with a new key created for the data portion of the file. If the keys
// compare the data has not been tampered with.
static bool VerifyFile(byte[] key, String sourceFile)
{
bool err = false;
// Initialize the keyed hash object.
using (HMACSHA512 hmac = new HMACSHA512(key))
{
// Create an array to hold the keyed hash value read from the file.
byte[] storedHash = new byte[hmac.HashSize / 8];
// Create a FileStream for the source file.
using (FileStream inStream = new FileStream(sourceFile, FileMode.Open))
{
// Read in the storedHash.
inStream.Read(storedHash, 0, storedHash.Length);
// Compute the hash of the remaining contents of the file.
// The stream is properly positioned at the beginning of the content,
// immediately after the stored hash value.
byte[] computedHash = hmac.ComputeHash(inStream);
// compare the computed hash with the stored value
for (int i = 0; i < storedHash.Length; i++)
{
if (computedHash[i] != storedHash[i])
{
err = true;
}
}
}
}
if (err)
{
Console.WriteLine("Hash values differ! Signed file has been tampered with!");
return false;
}
else
{
Console.WriteLine("Hash values agree -- no tampering occurred.");
return true;
}
} //end VerifyFile

Related

Encrypting and decrypting audio clip to file unity

I'm using AES for encrypting and decrypting, I can write it to a file and when I try to read the file back to audio clip, I'm getting input exception
I tried to convert the audio file to base64 byte array while saving in file so that when I read the file I can read it as byte array which is required for creating audio clip
I have attached the code below
private float[] ConvertByteToFloat(byte[] array)
{
float[] floatArr = new float[array.Length / 4];
for (int i = 0; i < floatArr.Length; i++)
{
if (BitConverter.IsLittleEndian)
{
Array.Reverse(array, i * 4, 4);
}
floatArr[i] = BitConverter.ToSingle(array, i * 4) / 0x80000000;
}
return floatArr;
}
public void ReadFile()
{
// Does the file exist AND does the "key" preference exist?
if (File.Exists(saveFile) && PlayerPrefs.HasKey("Key"))
{
// Update key based on PlayerPrefs
// (Convert the String into a Base64 byte[] array.)
byte[] savedKey = Convert.FromBase64String(PlayerPrefs.GetString("Key"));
byte[] savedIV = Convert.FromBase64String(PlayerPrefs.GetString("IV"));
// Create FileStream for opening files.
dataStream = new FileStream(saveFile, FileMode.Open);
Debug.Log(PlayerPrefs.GetString("Key"));
// Create new AES instance.
Aes oAes = Aes.Create();
// Create an array of correct size based on AES IV.
byte[] outputIV = new byte[savedIV.Length];
// Read the IV from the file.
dataStream.Read(savedIV, 0, outputIV.Length);
// Create CryptoStream, wrapping FileStream
CryptoStream oStream = new CryptoStream(dataStream, oAes.CreateDecryptor(savedKey, outputIV), CryptoStreamMode.Read);
// Create a StreamReader, wrapping CryptoStream
StreamReader reader = new StreamReader(oStream);
// Read the entire file into a String value.
string text = reader.ReadToEnd();
byte[] songDataBytes = Convert.FromBase64String(text);
AudioClip audioClip = AudioClip.Create("SongName", songDataBytes.Length, 1, 48000, false);
float[] f = ConvertByteToFloat(songDataBytes);
audioClip.SetData(f, 0);
ass.clip = audioClip;
ass.Play();
Debug.Log("C");
// Deserialize the JSON data
// into a pattern matching the GameData class.
//gameData = JsonUtility.FromJson<GameData>(text);
}
Debug.Log("D");
}
public void WriteFile()
{
string songLoc = Application.persistentDataPath + "/song.mp3";
// Create new AES instance.
Aes iAes = Aes.Create();
// Update the internal key.
string key = PlayerPrefs.GetString("Key");
string IV = PlayerPrefs.GetString("Key");
byte[] savedKey;
byte[] savedIV;
if (key == "")
{
iAes.GenerateIV();
savedKey = iAes.Key;
savedIV = iAes.IV;
key = Convert.ToBase64String(savedKey);
IV = Convert.ToBase64String(savedIV);
}
else
{
savedIV = Convert.FromBase64String(PlayerPrefs.GetString("IV"));
savedKey = Convert.FromBase64String(PlayerPrefs.GetString("Key"));
}
Debug.Log(key);
// Convert the byte[] into a Base64 String.
//string key = System.Convert.ToBase64String(savedKey);
// Update the PlayerPrefs
PlayerPrefs.SetString("Key", key);
PlayerPrefs.SetString("IV", IV);
// Create a FileStream for creating files.
dataStream = new FileStream(saveFile, FileMode.Create);
// Save the new generated IV.
byte[] inputIV = savedIV;
// Write the IV to the FileStream unencrypted.
dataStream.Write(inputIV, 0, inputIV.Length);
// Create CryptoStream, wrapping FileStream.
CryptoStream iStream = new CryptoStream(dataStream, iAes.CreateEncryptor(savedKey, savedIV), CryptoStreamMode.Write);
// Create StreamWriter, wrapping CryptoStream.
StreamWriter sWriter = new StreamWriter(iStream);
// Serialize the object into JSON and save string.
byte[] songData = File.ReadAllBytes(songLoc);
//string songString = Convert.ToBase64String(songData);
//File.WriteAllBytes(saveFile, songData);
// Write to the innermost stream (which will encrypt).
sWriter.BaseStream.Write(songData, 0, songData.Length);
// Close StreamWriter.
sWriter.Close();
// Close CryptoStream.
iStream.Close();
// Close FileStream.
dataStream.Close();
}

Testing checksum by modifying a file

A program in C# which copy a file or whole folders to another folder is made and in that application checksum SHA-512 has been used to verify that input and output of the copy process is/are identical, the program works fine but I need to test the whole program and especially test or verify the checksum. how can I, give the program an input e.g. a file and in the process modify the file somehow in order to see that checksum detect that error? thanks for your suggestions
Here's a simple example of testing the SHA512 hash. Here we have two tests, TestSHA512Modify and TestSHA512Append. One modifies bytes within the file, open appends bytes to the file. Both are useful tests of the Hash.
static void TestSHA512Modify()
{
var testFile = Path.GetTempFileName();
CreateRandomFile(testFile, 1024);
var sha12 = GetFileSHA512(testFile);
Console.WriteLine("TestSHA12Modify: Original file SHA512: " + ToHexString(sha12));
// Modify file bytes. Here we set byte offset [100] [101] [102]
WriteBytes(testFile, 100, new byte[] { 1, 2, 3 });
var modifiedSha12 = GetFileSHA512(testFile);
Console.WriteLine("TestSHA12Modify: Updated file SHA512: " + ToHexString(modifiedSha12));
Console.WriteLine("TestSHA12Modify: SHA12 Hashes are: " + (sha12.SequenceEqual(modifiedSha12) ? "EQUAL" : "NOT EQUAL"));
}
static void TestSHA512Append()
{
var testFile = Path.GetTempFileName();
CreateRandomFile(testFile, 1024);
var sha12 = GetFileSHA512(testFile);
Console.WriteLine("TestSHA12Append: Original file SHA512: " + ToHexString(sha12));
// Append bytes to the end of a file
AppendBytes(testFile, new byte[] { 1 });
var modifiedSha12 = GetFileSHA512(testFile);
Console.WriteLine("TestSHA12Append: Updated file SHA512: " + ToHexString(modifiedSha12));
Console.WriteLine("TestSHA12Append: SHA12 Hashes are: " + (sha12.SequenceEqual(modifiedSha12) ? "EQUAL" : "NOT EQUAL"));
}
static void CreateRandomFile(string path, int length)
{
// Make some random bytes.
var randomData = new byte[1024];
RNGCryptoServiceProvider p = new RNGCryptoServiceProvider();
p.GetBytes(randomData);
File.WriteAllBytes(path, randomData);
}
static void WriteBytes(string path, int fileOffset, byte[] data)
{
using (var fileStream = new FileStream(path, FileMode.Open))
{
fileStream.Seek(fileOffset, SeekOrigin.Begin);
fileStream.Write(data, 0, data.Length);
}
}
static void AppendBytes(string path, byte[] data)
{
using (var fileStream = new FileStream(path, FileMode.Append))
{
fileStream.Write(data, 0, data.Length);
}
}
static byte[] GetFileSHA512(string path)
{
using (SHA512 sha = new SHA512Managed())
{
return sha.ComputeHash(File.ReadAllBytes(path));
}
}
static string ToHexString(byte[] data)
{
return string.Join("", data.Select(b => b.ToString("X2")));
}

Return buffer while processing Stream

So I have a file upload form which (after uploading) encrypts the file and uploads it to an S3 bucket. However, I'm doing an extra step which I want to avoid. First, I'll show you some code what I am doing now:
using (MemoryStream memoryStream = new MemoryStream())
{
Security.EncryptFile(FileUpload.UploadedFile.OpenReadStream(), someByteArray, memoryStream);
memoryStream.Position = 0; // reset it's position
await S3Helper.Upload(objectName, memoryStream);
}
My Security.EncryptFile method:
public static void EncryptFile(Stream inputStream, byte[] key, Stream outputStream)
{
CryptoStream cryptoStream;
using (SymmetricAlgorithm cipher = Aes.Create())
using (inputStream)
{
cipher.Key = key;
// aes.IV will be automatically populated with a secure random value
byte[] iv = cipher.IV;
// Write a marker header so we can identify how to read this file in the future
outputStream.WriteByte(69);
outputStream.WriteByte(74);
outputStream.WriteByte(66);
outputStream.WriteByte(65);
outputStream.WriteByte(69);
outputStream.WriteByte(83);
outputStream.Write(iv, 0, iv.Length);
using (cryptoStream =
new CryptoStream(inputStream, cipher.CreateEncryptor(), CryptoStreamMode.Read))
{
cryptoStream.CopyTo(outputStream);
}
}
}
The S3Helper.Upload method:
public async static Task Upload(string objectName, Stream inputStream)
{
try
{
// Upload a file to bucket.
using (inputStream)
{
await minio.PutObjectAsync(S3BucketName, objectName, inputStream, inputStream.Length);
}
Console.Out.WriteLine("[Bucket] Successfully uploaded " + objectName);
}
catch (MinioException e)
{
Console.WriteLine("[Bucket] Upload exception: {0}", e.Message);
}
}
So, what happens above is I'm creating a MemoryStream, running the EncryptFile() method (which outputs it back to the stream), I reset the stream position and finally reuse it again to upload it to the S3 bucket (Upload()).
The question
What I'd like to do is the following (if possible): directly upload the uploaded file to the S3 bucket, without storing the full file in memory first (kinda like the code below, even though it's not working):
await S3Helper.Upload(objectName, Security.EncryptFile(FileUpload.UploadedFile.OpenReadStream(), someByteArray));
So I assume it has to return a buffer to the Upload method, which will upload it, and waits for the EncryptFile() method to return a buffer again until the file has been fully read. Any pointers to the right direction will be greatly appreciated.
What you could do is make your own EncryptionStream that overloads the Stream class. When you read from this stream, it will take a block from the inputstream, encrypt it and then output the encrypted data.
As an example, something like this:
public class EncrypStream : Stream {
private Stream _cryptoStream;
private SymmetricAlgorithm _cipher;
private Stream InputStream { get; }
private byte[] Key { get; }
public EncrypStream(Stream inputStream, byte[] key) {
this.InputStream = inputStream;
this.Key = key;
}
public override int Read(byte[] buffer, int offset, int count) {
if (this._cipher == null) {
_cipher = Aes.Create();
_cipher.Key = Key;
// aes.IV will be automatically populated with a secure random value
byte[] iv = _cipher.IV;
// Write a marker header so we can identify how to read this file in the future
// #TODO Make sure the BUFFER is big enough...
var idx = offset;
buffer[idx++] = 69;
buffer[idx++] = 74;
buffer[idx++] = 66;
buffer[idx++] = 65;
buffer[idx++] = 69;
buffer[idx++] = 83;
Array.Copy(iv, 0, buffer, idx, iv.Length);
offset = idx + iv.Length;
// Startup stream
this._cryptoStream = new CryptoStream(InputStream, _cipher.CreateEncryptor(), CryptoStreamMode.Read);
}
// Write block
return this._cryptoStream.Read(buffer, offset, count);
}
protected override void Dispose(bool disposing) {
base.Dispose(disposing);
// Make SURE you properly dispose the underlying streams!
this.InputStream?.Dispose();
this._cipher?.Dispose();
this._cryptoStream?.Dispose();
}
// Omitted other methods from stream for readability...
}
Which allows you to call the stream as:
using (var stream = new EncrypStream(FileUpload.UploadedFile.OpenReadStream(), someByteArray)) {
await S3Helper.Upload(objectName, stream);
}
As I notice your upload method requires the total bytelength of the encrypted data, you can look into this post here to get an idea how you would be able to calculate this.
(I'm guessing that the CryptoStream does not return the expected length of the encrypted data, but please correct me if I'm wrong on this)

One file encryption for multiple public keys and private key decryption C#

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();
}
}
}
}

Encrypting/Decrypting a file using C# and RSA

I am trying to encrypt and then decrypt an XML file using RSA and C# and while I'm really close, there's a problem. Once it's decrypted, almost all of the file is there but there's a hiccup toward the end. It's either a gap toward the end of the file or more data is appended to the very end of the file.
Here is my encrypt method:
public static bool Encrypt(ProcessingHolder ph)
{
FileInfo inFile = ph.encryptedFI;
FileInfo outFile = ph.unEncryptedFI;
X509Certificate2 daCert = new X509Certificate2(keyFP, daCertPassword);
RSACryptoServiceProvider RSA = (RSACryptoServiceProvider)daCert.PrivateKey;
bool done = false;
FileStream fs = null;
FileStream fso = null;
try
{
//opens the file to encrypt into a filestream object
fs = inFile.OpenRead();
//240 is what the iOS side is using
//algorithm that calculates max bytes ((KeySize - 384) / 8) + 37
//(returns 245)
int chunkSize = 245;
fso = outFile.OpenWrite();
byte[] buffer = new byte[chunkSize];
int totalRead = 0;
while (totalRead < fs.Length)
{
int readBytes = fs.Read(buffer,0, chunkSize);
totalRead += readBytes;
//check to see if the final chunk of data is less than 245 so as not to write empty buffer
if (readBytes < chunkSize) buffer = new byte[readBytes];
//byte[] encr = new byte[readBytes];
//actual encryption
//encr = RSA.Encrypt(buffer, false);
byte[] encr = RSA.Encrypt(buffer, false);
fso.Write(encr, 0, encr.Length);
}
fso.Flush();
fso.Close();
fs.Close();
done = true;
}
catch (Exception ex)
{
Debug.WriteLine("Decrypt failed with message " + ex.Message);
done = false;
}
finally
{
if (fs != null) fs.Close();
if (fso != null) fso.Close();
}
return done;
}
}
and here is my decrypt method:
public static bool Decrypt(ProcessingHolder ph)
{
FileInfo inFile = ph.encryptedFI;
FileInfo outFile = ph.unEncryptedFI;
X509Certificate2 daCert = new X509Certificate2(keyFP, daCertPassword);
RSACryptoServiceProvider RSA = (RSACryptoServiceProvider)daCert.PrivateKey;
bool done = false;
FileStream fs = null;
FileStream fso = null;
try
{
fs = inFile.OpenRead();
int chunkSize = 256;
fso = outFile.OpenWrite();
byte[] buffer = new byte[chunkSize];
int totalRead = 0;
while (totalRead < fs.Length)
{
int readBytes = fs.Read(buffer, 0, chunkSize);
totalRead += readBytes;
//check to see if the final chunk of data is less than 245 so as not to write empty buffer
//if (readBytes < chunkSize) buffer = new byte[readBytes];
byte[] decr = RSA.Decrypt(buffer, false);
fso.Write(decr, 0, decr.Length);
}
fso.Flush();
fso.Close();
fs.Close();
done = true;
}
catch (Exception ex)
{
Debug.WriteLine("Decrypt failed with message " + ex.Message);
done = false;
}
finally
{
if (fs != null) fs.Close();
if (fso != null) fso.Close();
}
return done;
}
banging my head against the wall here, thanks in advance
What happens during encrypting if the file is not a multiple of the length of the chunk size? Ie. a file 500 bytes long would read two sets of 245, but they have 10 bytes left over? This might be loosing the last few bytes at the end or adding extra values?
Maybe you need to add a header to the file with the size in bytes of the decrypted file so that the decrypter knows where to stop and a way to pad out the final block during encryption

Categories

Resources