Using SharpAESCrypt to encrypt strings

ぐ巨炮叔叔 提交于 2019-12-06 03:15:27

A quick code review reveals a few things including what, from discussion, seems to be the main problem you are facing. The problematic line is

EncryptedTB.Text = Encoding.UTF8.GetString(newByteArray);

This line is taking the binary data in newByteArray and telling your code that it is a valid UTF8 byte array. Chances are that it is almost certainly not actually going to be valid UTF8. Parts of it may be (such as the header) but the actually encrypted data is not going to be and so you shouldn't use this method to get a string.

If you need a printable string to put in a textbox of some sort then the correct way to do this for binary data is through base64 encoding.

EncryptedTB.Text = Convert.ToBase64String(newByteArray);

Base64 encoding effectively takes groups of three bytes (24 bits) and converts them to groups of four characters.

A further note while I'm here is that in these two lines:

byte[] newByteArray = new byte[encryptedData.Length];
newByteArray = encryptedData.ToArray();

You declare a byte array and allocate a new array to it. You then immediately discard this in favour of the array from encryptedData.ToArray(). This does not put data into the array allocated by new byte[encryptedData.Length] but creates a new array and puts it into the newByteArray variable. Better would be to just do:

byte[] newByteArray = encryptedData.ToArray();

Full working code below:

byte[] byteArray = Encoding.UTF8.GetBytes(sourceText);
Byte[] newByteArray;
using (MemoryStream plainText = new MemoryStream(byteArray))
{
    using (MemoryStream encryptedData = new MemoryStream())
    {
        SharpAESCrypt.Encrypt(password, plainText, encryptedData);
        newByteArray = encryptedData.ToArray();
    }
}
EncryptedTB.Text = Convert.ToBase64String(newByteArray);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!