Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

delphi - simple text file encryption based on a key

I am trying to implement a simple text file encryption technique and I am using the following code to do so. The code is not written by me, I just googled and got it. The encryption technique seems to be pretty simple, concise and easy to implement. I see that it has only one function that can do the encryption and the decryption on the fly. Just pass the key it will do the trick. However, I just wanted to know, is it possible for me to check if the key is passed by the user is correct or not. Currently it will just encrypt / decrypt the text file based on the passed key. But there is no mechanism to check if we are decrypting with correct key or not. Whatever the key we pass, it will get decrypted, but it will not be readable. Any idea how to tackle this problem..?

procedure TEnDeCrypt.EnDecryptFile(pathin, pathout: string; Chave: Word);
var
  InMS, OutMS: TMemoryStream;
  cnt: Integer;
  C: byte;
begin
  InMS  := TMemoryStream.Create;
  OutMS := TMemoryStream.Create;
  try
    InMS.LoadFromFile(pathin);
    InMS.Position := 0;
    for cnt := 0 to InMS.Size - 1 DO
      begin
        InMS.Read(C, 1);
        C := (C xor not (ord(chave shr cnt)));
        OutMS.Write(C, 1);
      end;
    OutMS.SaveToFile(pathout);
  finally
    InMS.Free;
    OutMS.Free;
  end;
end;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you are aware of the kind of content your file will have (whether it is a binary file / text file etc), then you can sample the text and see if there are any non-ASCII or characters that are not expected in the file after decryption.

Another thing you can do is to add a watermark text at the end of the file. After decryption, you can check if your watermark is containing data that is outside the expected data-type (if you are expecting only characters and you see a non-char data in it, then there is possibly an issue). This though is not fool-proof, just a sort of a buffer for you.

That said, I will ask you this question - what is the intent behind this? The key the user is passing is to encrypt; so if the user is passing an invalid key, then they get invalid output. Why do you need to steer the user towards the right key? And if there is some business use-case for something like that, then you also need to understand that this is going to make your encryption very easy to break. I will suggest that you pick up a standard encryption algorithm and use that to encrypt your file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...