Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encrypt string to fixed length

I want to encrypt string to base64, the string input can be in differential length(the limit is 16 charcters), and I want to get the encrypted string in fixed length.

Does anyone know about the way to do that in .NET framework? or has an algorithm to do that?

like image 245
RRR Avatar asked Mar 03 '11 07:03

RRR


1 Answers

(EDIT: I've been assuming you want to both encrypt a string, and then encode the result as base64, always ending up with the same output length. It would help if you could clarify the question to confirm this or explain what you do want if this isn't it.)

Well, there's a pretty simply algorithm which would work given any encryption scheme which always encrypts an input of a fixed length to an output of a fixed length (and there are plenty of those):

  • Encode the string as binary using UTF-16 (which will always give the same byte array length for the same string input)
  • Pad the binary data to 32 bytes (i.e. the maximum size) using random data
  • Add an extra byte at the end (or start) indicating the original length
  • Encrypt the binary data (which will always be 33 bytes)
  • Convert the result to base64 using Convert.ToBase64String

To decrypt, simply reverse the process:

  • Convert the base64 text to the encrypted binary data using Convert.FromBase64String
  • Decrypt the binary data (back to "plaintext" binary)
  • Find the length from the first or last byte
  • Decode the relevant section of the plaintext binary as UTF-16 text

(Use MSDN to find details of each step, and feel free to ask for help in a specific part. Your choice of encryption algorithm will depend on what you're trying to do, and I'm no expert on that, I'm afraid.)

EDIT: If you only need a hash, then other questions come into play. Would you always want the same string to end up being hashed to the same string? That's typically desirable for hashing but not encryption.

like image 71
Jon Skeet Avatar answered Sep 18 '22 12:09

Jon Skeet