如何检查有效的Base64编码的字符串 [英] How to check for a valid Base64 encoded string

查看:230
本文介绍了如何检查有效的Base64编码的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,除了试图转换字符串并查看是否有错误之外,是否有其他方法可以查看字符串是否为Base 64编码?我有这样的代码:

Is there a way in C# to see if a string is Base 64 encoded other than just trying to convert it and see if there is an error? I have code code like this:

// Convert base64-encoded hash value into a byte array.
byte[] HashBytes = Convert.FromBase64String(Value);

我想避免如果该值不是有效的64位基数字符串,则会发生"Base-64位字符串中的无效字符"异常.我只想检查并返回false而不是处理异常,因为我希望有时该值不会是基数为64的字符串.在使用Convert.FromBase64String函数之前,有什么方法可以检查吗?

I want to avoid the "Invalid character in a Base-64 string" exception that happens if the value is not valid base 64 string. I want to just check and return false instead of handling an exception because I expect that sometimes this value is not going to be a base 64 string. Is there some way to check before using the Convert.FromBase64String function?

谢谢!

更新:
感谢您的所有回答.到目前为止,这是一个大家都可以使用的扩展方法,似乎可以确保您的字符串毫无例外地通过Convert.FromBase64String.转换为基数64时,.NET似乎会忽略所有尾随空格,因此"1234"有效,"1234"有效

Update:
Thanks for all of your answers. Here is an extension method you can all use so far it seems to make sure your string will pass Convert.FromBase64String without an exception. .NET seems to ignore all trailing and ending spaces when converting to base 64 so "1234" is valid and so is " 1234 "

public static bool IsBase64String(this string s)
{
    s = s.Trim();
    return (s.Length % 4 == 0) && Regex.IsMatch(s, @"^[a-zA-Z0-9\+/]*={0,3}$", RegexOptions.None);

}

对于那些对测试性能,捕获性能和异常性能感到疑惑的人来说,在大多数情况下,对于这种基于64位的东西,检查直到捕获一定长度才比捕获异常更快.长度越短越快

For those wondering about performance of testing vs catching and exception, in most cases for this base 64 thing it is faster to check than to catch the exception until you reach a certain length. The smaller the length faster it is

在我非常不科学的测试中: 对于字符长度100,000-110000的10000次迭代,第一次测试的速度快2.7倍.

In my very unscientific testing: For 10000 iterations for character length 100,000 - 110000 it was 2.7 times faster to test first.

对于1000个字符长度为1到16个字符的迭代,总共进行了16,000次测试,速度提高了10.9倍.

For 1000 iterations for characters length 1 - 16 characters for total of 16,000 tests it was 10.9 times faster.

我敢肯定,使用基于异常的方法进行测试会变得更好.我只是不知道那是什么时候.

I am sure there is a point where it becomes better to test with the exception based method. I just don't know at what point that is.

推荐答案

识别Base64字符串非常容易,因为它仅由字符'A'..'Z', 'a'..'z', '0'..'9', '+', '/'组成,并且通常在结尾处最多填充三个' =',以使长度为4的倍数.但是最好不要忽略这些异常(如果发生).

It's pretty easy to recognize a Base64 string, as it will only be composed of characters 'A'..'Z', 'a'..'z', '0'..'9', '+', '/' and it is often padded at the end with up to three '=', to make the length a multiple of 4. But instead of comparing these, you'd be better off ignoring the exception, if it occurs.

这篇关于如何检查有效的Base64编码的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆