How to convert and send a string in the Http Authorization Header?

I am developing a REST API. The Client puts the username and password in the authorization header HttpClient

after encrypting it with the Server's public key. The username and password always consist of letters and numbers, which means that it can be represented in ASCII.

I am using this code for encryption.

string encrypted = Encrypt (someText, crypto);

    public static string Encrypt (string plainText, RSACryptoServiceProvider crypto)
    {
        var plainData = GetBytes (plainText);
        var encryptedData = crypto.Encrypt (plainData, true);
        return GetString (encryptedData);
    }

    public static byte[] GetBytes (string str)
    {
        var bytes = new byte[str.Length * sizeof (char)];
        Buffer.BlockCopy (str.ToCharArray (), 0, bytes, 0, bytes.Length);
        return bytes;
    }

    public static string GetString (byte[] bytes)
    {
        var chars = new char[bytes.Length / sizeof (char)];
        Buffer.BlockCopy (bytes, 0, chars, 0, bytes.Length);
        return new string (chars);
    }

      

The problem is I get this string after encryption

꠨ 屰 欧 㼡 ⭮ 鍴 ⬎ 㔾 䐛 え 멩 戻 덒 郝 㬭 ே 䉚 ꑰ 䵇 ᷹᷶ 虣 ⱒ̿ ঊࠎ 飳 枹 鬭 쉦폩 ᤫ 槺 愐  丄 裘 ډ 졽 肟 ䷋ٱ᮷ 튼쁡 鮤 붮 飦 ꃨ◡ 뉋 ⭠ 夏旻 浨 ፛ ᠏ რ

I am unable to send these unicode characters to the authorization header. Is there a way to get the ciphertext in ASCII so that it can be sent easily via HttpClient?

+3


source to share


1 answer


You can base64 encode it. Base64 encoding creates a string that is suitable for sending over a transport that supports ASCII strings.

public static string Encrypt (string plainText, RSACryptoServiceProvider crypto)
{
    var plainData = GetBytes (plainText);
    var encryptedData = crypto.Encrypt (plainData, true);
    return Convert.ToBase64String (encryptedData);
}

      



Btw, I would replace your own GetBytes method to convert a string to a byte array with Encoding.GetBytes

; which is the built-in and preferred way of doing this. For example:

var plainData = System.Text.Encoding.UTF8.GetBytes(plainText);

      

+2


source







All Articles