using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace MsgReader.Mime.Decode
{
///
/// Utility class for dealing with Base64 encoded strings
///
internal static class Base64
{
#region Decode
///
/// Decodes a base64 encoded string into the bytes it describes
///
/// The string to decode
/// A byte array that the base64 string described
public static byte[] Decode(string base64Encoded)
{
try
{
using (var memoryStream = new MemoryStream())
{
base64Encoded = base64Encoded.Replace("\r\n", "");
base64Encoded = base64Encoded.Replace("\t", "");
base64Encoded = base64Encoded.Replace(" ", "");
var inputBytes = Encoding.ASCII.GetBytes(base64Encoded);
using (var transform = new FromBase64Transform(FromBase64TransformMode.DoNotIgnoreWhiteSpaces))
{
var outputBytes = new byte[transform.OutputBlockSize];
// Transform the data in chunks the size of InputBlockSize.
const int inputBlockSize = 4;
var currentOffset = 0;
while (inputBytes.Length - currentOffset > inputBlockSize)
{
transform.TransformBlock(inputBytes, currentOffset, inputBlockSize, outputBytes, 0);
currentOffset += inputBlockSize;
memoryStream.Write(outputBytes, 0, transform.OutputBlockSize);
}
// Transform the final block of data.
outputBytes = transform.TransformFinalBlock(inputBytes, currentOffset,
inputBytes.Length - currentOffset);
memoryStream.Write(outputBytes, 0, outputBytes.Length);
}
return memoryStream.ToArray();
}
}
catch (Exception)
{
return new byte[0];
}
}
///
/// Decodes a Base64 encoded string using a specified
///
/// Source string to decode
/// The encoding to use for the decoded byte array that describes
/// A decoded string
/// If or is
/// If is not a valid base64 encoded string
public static string Decode(string base64Encoded, Encoding encoding)
{
if (base64Encoded == null)
throw new ArgumentNullException(nameof(base64Encoded));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
try
{
return encoding.GetString(Decode(base64Encoded));
}
catch (FormatException)
{
return string.Empty;
}
}
#endregion
}
}