[英]Throwing an exception when convert string to base64
我有兩種方法,我需要在開始時將字符串轉換為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格式(這些在pt.1和2中)我需要從這些方法返回字符串。 有人知道如何解決這種行為嗎?
您正在使用base-64; base-64翻譯:
byte[]
到結構化 string
string
到原始byte[]
相反, 常規文本編碼以另一種方式工作:
string
到結構化 byte[]
byte[]
到原始string
您正在嘗試使用base-64從任意 string
獲取byte[]
,這不是它所做的事情 。 為此,您需要常規文本編碼 ,例如UTF-8。 嘗試使用Encoding.UTF8.GetBytes()
等等,而不是為二分之一 ,和基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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.