0

I am doing a symmetric encryption of a field in a database "name", just to test it. I have never done it so I'm kinda new to this. I am getting the inputted name by the user, encrypting it using a symmetric encryption and adding it encrypted in the database. However, the value of the name is being saved as System.IO.MemoryStream

The code for the SymmetricEncryption is this:

public static MemoryStream SymmetricEncryptData(MemoryStream stream)
    {
        stream.Position = 0;

        var myAlg = Rijndael.Create();

        var myKeys = GenerateSecretKey();

        MemoryStream msOut = new MemoryStream();

        CryptoStream cs = new CryptoStream(msOut, myAlg.CreateEncryptor(myKeys.SecretKey, 
        myKeys.IV), CryptoStreamMode.Write);
        stream.CopyTo(cs);
        cs.FlushFinalBlock();

        return msOut;
    }

Then I have the code that is doing the encryption for the name and adding it, as shown below (u is the user instance, Name is the name inputted by the user)

 byte[] namee = Encoding.UTF32.GetBytes(u.Name);
 MemoryStream stream = new MemoryStream(namee);

 u.Name = Encryption.SymmetricEncryptData(stream).ToString();

 u.Blocked = false;

 ur.AddUser(u);

Am I doing a wrong encryption? What am I doing wrong and why am I getting the value "System.IO.MemoryStream" in the database instead of an encrypted name?

Rick Astley
  • 125
  • 1
  • 11

1 Answers1

2

A MemoryStream instance is an object that wraps a backing byte array or arrays. The state of this instance is the position and the amount of bytes written to the backing arrays. It does however not include the backing array or arrays itself.

To retrieve all the data from the backing arrays in one go, you would use the method ToArray. If you simply use ToString then you get a representation of the state, which doesn't include the stored data, as explained above. So ToString is not a string equivalent to ToArray.

Ciphertext may contain any byte value and it doesn't represent any textual string. It may contain invalid characters, whichever is used to represent it. Instead, if you want a string, you need to encode the returned bytes using - for instance - base 64.

Note that base 64 expands the size of the ciphertext compared to the size of plaintext. If that's not feasible then you may need to look at Format Preserving Encryption (FPS). That's however not commonly implemented in base cryptography of any language and it will require a steep learning curve. For names (usually a variable sized string) the expansion should usually not matter much.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
  • Hi thanks for the reply. I tried replacing the ToString, like you said, to ToArray.ToString() (since i still need the output in string), however it's putting System.Byte[] in the name property.. – Rick Astley Dec 30 '19 at 01:47
  • Ok I understood it better now and it worked! Thanks! – Rick Astley Dec 30 '19 at 02:28