如何确定字符串是否是Base64解码? [英] How to determine if a string is Base64 decoded or not?

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

问题描述

如何确定字符串是否已被Base64解码?

How to determine if a string is Base64 decoded or not?

推荐答案

这样做:



Do it like this:

public bool IsBase64Encoded(String str)
{
    try
    {
        // If no exception is caught, then it is possibly a base64 encoded string
        byte[] data = Convert.FromBase64String(str);
        // The part that checks if the string was properly padded to the
        // correct length was borrowed from d@anish's solution
        return (str.Replace(" ","").Length % 4 == 0);
    }
    catch
    {
        // If exception is caught, then it is not a base64 encoded string
       return false;
    }
}







如果字符串str,该函数将返回true是Base64编码,如果不是,则为false。仍然存在疑问,因为包含随机字母和数字的字符串可能仍然看起来是Base64编码的,即使它只是一个随机字符串。在这种情况下唯一的好答案是假的,因为这会告诉你字符串绝对不是Base64编码的字符串。



干杯和快乐的编码!



-MRB




The function will return true if the string str was Base64 encoded and false if it was not. There is still is a doubt because a string that contains random letters and numbers might still look Base64 encoded even if it was just a random string. The only good answer in this case is false because that will tell you that the string is definitely not a Base64 encoded string.

Cheers and happy coding!

-MRB


我认为你的意思是编码,对吗?



使用 Convert.FromBase64String 方法。如果它抛出FormatException,则原始字符串不是base64。这样的事情:



I think you mean encoded, right?

Use Convert.FromBase64String method. If it throws FormatException, then the original string was not base64. Something like this:

public static bool IsBase64(string base64String){
if(base64String.Replace(" ","").Length % 4 != 0){
return false;
}

try{
Convert.FromBase64String(base64String);
return true;
}
catch(FormatException exception){
// Handle the exception
}
return false;
}





您可以在此方法中添加null check等,以减少异常。



You can add null check etc to this method to make it less exception prone.


你的意思是编码?



如果是这样,你可以在C#中这样做:



Do you mean encoded?

If so, you can do it like this in C#:

try
{
   byte[] converted = Convert.FromBase64String(base64value);
   return base64value.EndsWith("=");
}
catch
{
   return false;
}


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

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