1

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?

stefam mierz
  • 53
  • 1
  • 6
  • 1
    Minor note: your method names and parameter names are odd... one doesn't `Encrypt` an `encrypted` string - nor does one `Decrypt` a `decrypted` string; you might want to normalize those parameter names – Marc Gravell Jun 12 '19 at 07:11
  • maybe this [link](https://stackoverflow.com/questions/11743160/how-do-i-encode-and-decode-a-base64-string) will be usefull – arlan schouwstra Jun 12 '19 at 07:18

1 Answers1

3

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);
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900