C#C
C#3y ago
Ysehporp

❔ Encoding Confusion and string variables

Hello! I am trying to encrypt a string, send it between two clients, and then decrypt the string. Which sounds simple enough but where I've hit a snag is in string encodings, or so I believe.
I am using the following code to encrypt and decrypt my string (userPassWord)

 public byte[] Encrypt(string userPassWord, string passphrase)
    {
        using Aes aes = Aes.Create();
        aes.Key = DeriveKeyFromPassword(passphrase);
        aes.IV = IV;
        using MemoryStream output = new();
        using CryptoStream cryptoStream = new(output, aes.CreateEncryptor(), CryptoStreamMode.Write);
        cryptoStream.Write(Encoding.Unicode.GetBytes(userPassWord));
        cryptoStream.FlushFinalBlock();
        return output.ToArray();
    }


    public string Decrypt(byte[] encrypted, string passphrase)
    {
        using Aes aes = Aes.Create();
        aes.Key = DeriveKeyFromPassword(passphrase);
        aes.IV = IV;
        using MemoryStream input = new(encrypted);
        using CryptoStream cryptoStream = new(input, aes.CreateDecryptor(), CryptoStreamMode.Read);
        using MemoryStream output = new();
        cryptoStream.CopyTo(output);
        return Encoding.Unicode.GetString(output.ToArray());
    }

This works if I run it in isolation and just pass the result from one into the other. However! Where I am hitting a snag is that I cannot send the encrypted string as a byte[] but I need to send it as a string instead. However whenever I convert that byte array to a string and then back, it ends up either being an incorrect blocksize or decoding incorrectly. Do any of you know how to do this? Thanks a ton!
Was this page helpful?