0

I was wondering those differences, since I have a program that asks me for a byte[].

public static string DecryptTextFromFile(String FileName, byte[] Key, byte[] 
IV){}

enter image description here

and I have already tried:

char[] key= { '9', 'D', '2', 'A', 'E'}; doesn't give an error but I need byte[]

and this:

byte[] key= { '9', 'D', '2', 'A', 'E'}; // but this one says that I am using char characters, how do I put them in byte[] format?.

Soheila Tarighi
  • 487
  • 4
  • 15
Sergio
  • 55
  • 7
  • a byte is a series of 8 bits. a char is a character that can be represented by one or more bytes, depending on your encoding. [the documentation might help you understand](https://learn.microsoft.com/en-gb/dotnet/api/system.text.encoding.utf8?view=netframework-4.8) – Franz Gleichmann Apr 02 '20 at 16:55
  • 1
    byte[] key = {0x9d, 0x2a, 0xea, ...etc } – Hans Passant Apr 02 '20 at 17:12
  • @FranzGleichmann I find that misleading - [`char` in .NET is always 16bits in size](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/types#integral-types). – V0ldek Apr 02 '20 at 17:34

2 Answers2

1

You can initialize a byte array like :

byte[] key1 = new byte[] { 57, 68, 50, 65, 69 };

Or convert from Char Array :

char[] keyChars = { '9', 'D', '2', 'A', 'E' };
var key2 = Encoding.ASCII.GetBytes(keyChars);
XAMT
  • 1,515
  • 2
  • 11
  • 31
0

The char and byte are two different types, char size is 16 bit and byte size is 8 bit; To represent a char you need to convert to bytes.

To do that you can use BitConverter

 char charValue = 'c';
 bytep[] bytes = BitConverter.GetBytes(charValue);

To convert your string from the picture you can use this method

static class HexStringConverter
{
    public static byte[] ToByteArray(String HexString)
    {
        int NumberChars = HexString.Length;
        byte[] bytes = new byte[NumberChars / 2];
        for (int i = 0; i < NumberChars; i += 2)
        {
            bytes[i / 2] = Convert.ToByte(HexString.Substring(i, 2), 16);
        }
        return bytes;
    }
}

Hope this answer will help you

V0ldek
  • 9,623
  • 1
  • 26
  • 57
Support Ukraine
  • 978
  • 6
  • 20