stefam mierz
stefam mierz

Reputation: 53

Throwing an exception when convert string to base64

I have two methods, where I need to convert string to base64 at begin and reverse this operation at the end. Problem is when my input string lenght is not divisible by 4 an conversion method throws exception.

public class Hashing
{
    public string Encrypt(string encrypted)
    {
        byte[] byteData = Convert.FromBase64String(encrypted);
        byte[] byteResult = Encrypt(byteData); // pt.1
        return Convert.ToBase64String(byteResult);
    }

    public string Decrypt(string decrypted)
    {
        byte[] byteData = Convert.FromBase64String(decrypted);
        byte[] byteResult = Decrypt(byteData); //pt.2
        return Convert.ToBase64String(byteResult);
    }

    /*
    ...
    */
}

class Program
{
    static void Main(string[] args)
    {
        Hashing cryptographyContext = new Hashing();

        var cryptoTest = "123456789"; //someStringThatNotGonnaBeConverted;

        string enc = cryptographyContext.Encrypt(password);
        string dec = cryptographyContext.Decrypt(enc);

        Console.WriteLine(dec);
        Console.ReadLine();
    }
}

Problem is I need base64 format at input of Decrypt and Encrypt methods (these at pt. 1 and 2) And I need returning strings from these methods. Do someone have an idea how to workaround this behaviour?

Upvotes: 1

Views: 602

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062494

You are using base-64 incorrectly; base-64 translates:

  • forwards, arbitrary byte[] to structured string
  • backwards, structured string to the original byte[]

Conversely, a regular text encoding works the other way:

  • forwards, arbitrary string to structured byte[]
  • backwards, structured byte[] to the original string

You are trying to use base-64 to get a byte[] from an arbitrary string, which isn't a thing that it does. For that, you want a regular text encoding, such as UTF-8. Try using Encoding.UTF8.GetBytes() etc instead for one half, and base-64 for the other:

public string Encrypt(string plainText)
{
    byte[] byteData = Encoding.UTF8.GetBytes(plainText);
    byte[] byteResult = Encrypt(byteData);
    return Convert.ToBase64String(byteResult);
}

public string Decrypt(string cipherText)
{
    byte[] byteData = Convert.FromBase64String(cipherText);
    byte[] byteResult = Decrypt(byteData);
    return Encoding.UTF8.GetString(byteResult);
}

Upvotes: 3

Related Questions