将字符串转换为base64时引发异常

时间:2019-06-12 07:07:52

标签: c# .net encoding

我有两种方法,其中我需要在开始时将字符串转换为base64并在结束时逆转此操作。问题是当我的输入字符串长度不能被4整除时,转换方法将引发异常。

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();
    }
}

问题是我需要在Decrypt和Encrypt方法的输入处使用base64格式(这些方法在第1和2页),并且我需要从这些方法返回字符串。有人知道如何解决此问题吗?

1 个答案:

答案 0 :(得分:3)

您使用的base-64错误; base-64的翻译为:

  • 向前,将任意byte[]转换为结构化 string
  • 向后,结构化 string到原始byte[]

相反,常规文本编码则以另一种方式起作用:

  • 向前,将任意string转换为结构化 byte[]
  • 向后,结构化 byte[]到原始string

您正尝试使用base-64从任意 byte[]中获取string,而并非如此。为此,您需要使用常规文本编码,例如UTF-8。尝试将Encoding.UTF8.GetBytes()等用于一半,将base-64用于另一

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);
}
相关问题