MemoryBlock->encrypt->File->decrypt not working

Hello. I have a MemoryBlock encrypting and decrypting successfully. However, the in-between stage of writing to and loading from a file is somehow changing the MemoryBlock so it’s not decrypting properly. I’m using the same BlowFish for both e&d so it’s not that. Code:

MemoryBlock mb = MemoryBlock();
ScopedPointer <MemoryOutputStream> mos = new MemoryOutputStream (mb, false);

vt.writeToStream (*mos);
mos->flush();
    
const String newKey = key + "_" + OnlineUnlockStatus::MachineIDUtilities::getLocalMachineIDs() [0] + "_" + name + "_" + email + "_" + expiry;
BlowFish blowFish = BlowFish (&newKey, static_cast <int> (newKey.getNumBytesAsUTF8()));
blowFish.encrypt (mb);
    
File file = File::getSpecialLocation (File::userDesktopDirectory).getChildFile ("testFile");
file.create();
    
FileOutputStream fos (file);
fos.write (&mb, mb.getSize());
fos.flush();
    
File file2 = File::getSpecialLocation (File::userDesktopDirectory).getChildFile ("testFile");
ScopedPointer <FileInputStream> fis = new FileInputStream (file2);
MemoryBlock mb2 = MemoryBlock();
file2.loadFileAsData (mb2);

//MemoryBlock mb2 = MemoryBlock (mb); PROOF
blowFish.decrypt (mb2);

I’ve also tested The sizes of of all the files / MemoryBlocks and they correlate. The proof is that the same MemoryBlock decrypts successfully if not written to a file, so it’s something about the way the MemoryBlock is written / read.

Thank you!

fos.write (mb.getData(), mb.getSize());

Rail

Ah, fantastic. Works, thank you. I’m looking forward to being experienced enough to pick out things that quickly!

-deleted-

Try calling file.deleteFile() instead of file.create()

And whenever you write this kind of thing, it’s always smart to break your code up into functions rather than just dumping all these complex objects into the same lexical scope. That way you know streams are getting closed and deleted without any danger of them all being left open at the same time.

Thank you Jules. I will indeed be splitting this up, it was just for testing more than anything.

As an aside, I can create a new BlowFish using the same key address, and it works fine. However, when I create a new key, the String being identical, it doesn’t work. Is this because the key is based on the actual address as well as the contents of the key?

Nope. It’s because you take a pointer to the String object itself rather than the data inside it!

I see, so the key data could be anything you want really… interesting.