Encrypt string to fixed length

15,046

Solution 1

If you're looking for 1-way encryption (no need to decrypt), you can use SHA1

        string secretKey = "MySecretKey";
        string salt = "123";
        System.Security.Cryptography.SHA1 sha = System.Security.Cryptography.SHA1.Create();
        byte[] preHash = System.Text.Encoding.UTF32.GetBytes(secretKey + salt);
        byte[] hash = sha.ComputeHash(preHash);
        string password = System.Convert.ToBase64String(hash);

If you want to encrypt and decrypt, you could probably use RSA.

Solution 2

(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.

Share:
15,046
RRR
Author by

RRR

Updated on June 21, 2022

Comments

  • RRR
    RRR almost 2 years

    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?