I created an OnFly encryption algorithm that encrypts bytes without having to copy them to a new copy of these same bytes. This is both for encrypting and decrypting these byte lists. As in the scheme below, the same string that enters will be the same one that will be described, I did this thinking about the cost of memory I would have when using large files.
Forexample,considerthefileBytesfilethathasa4MBPNGimage(4,194,304bytes)storedinit.Myalgorithmonlyincreasesby1byteoftheoriginalsize,andencryptstheremainingbytesofthefile,maintainingitssizeandappearance.
Todecrypt,1byteisdiscountedinthisfile.
Myquestionisasfollows,ifIuseanarbitrarilylargefileinencryption,inadditiontousingahugeprocessorusagetheapplicationmemorywillbeaddedalongwiththefilesize,andifIusea10GBfileona4GBRAMcomputer,aOutOfMemoryException
exceptionwillbethrown.
Seeintheexamplebelowhowthiswouldoccur:
//askeysemCRYRAZtambémsãooutrasArraysdebytes.byte[]key=newbyte[]{12,51,63};//criaumanovainstânciadeCRYRAZ.CryrazclientCriptografia=newCryraz(key);//amensagemqueseráusadaparaencriptarstringMensagem="Olá, mundo!";
// bytes da mensagem
byte[] Mensagem_bytes = System.Text.Encoding.Default.GetBytes(Mensagem);
// Mensagem_bytes será o nosso alvo. Atualmente ela se encontra decriptada e original, vamos encriptar ela agora.
Cryraz.EncryptData(ref Mensagem_bytes);
// Pronto, Mensagem_bytes está encriptado.
This is how Cryraz works, unlike the other encryption methods that you copy the bytes, thus getting the original version and encrypted in the same code, different from Cryraz, it encrypts the original directly.
This is the body of the encryption method (I cut unnecessary parts of algorithm security checks and options):
public void EncryptData(ref byte[] entryByteData) {
// ...
for (int i = 0; i <= entryByteData.Length - 1; i++) {
// ação recursiva em todos os bytes de entrada
// é aqui a ação de criptografia
// no final, o byte é atribuído à array:
entryByteData[i] = ((byte)a);
// obs: "a" é o novo byte encriptado
}
// aumenta o tamanho original da array para inserir o hash de segurança
Array.Resize(ref entryByteData, entryByteData.Length + 1);
// cria o hash de segurança e insere-o na array, sem esse hash, não há
// descriptografia, é parte do algoritmo
byte hash_x = performKeyHash(key);
entryByteData[entryByteData.Length - 1] = hash_x;
// coleta as variáveis inutilizadas
GC.Collect();
}
Full Code: link
Even with GC.Collect();
at the end of the method there is a huge amount of memory being used in the application, because of reading the bytes of the files that will be used.
For the algorithm to work, it is necessary to know the byte index in relation to the array being encrypted and to have the exact size of the input and output.