我想解码Base64编码的字符串,然后将它存储在我的数据库中。如果输入不是Base64编码的,我需要抛出一个错误。

我如何检查一个字符串是否被Base64编码?


当前回答

检查字符串的长度是否为4的倍数。然后使用这个正则表达式来确保字符串中的所有字符都是base64字符。

\A[a-zA-Z\d\/+]+={,2}\z

如果您使用的库添加换行符作为遵守每行最多76个字符规则的一种方式,请将它们替换为空字符串。

其他回答

检查字符串的长度是否为4的倍数。然后使用这个正则表达式来确保字符串中的所有字符都是base64字符。

\A[a-zA-Z\d\/+]+={,2}\z

如果您使用的库添加换行符作为遵守每行最多76个字符规则的一种方式,请将它们替换为空字符串。

Base64有许多变体,所以考虑只确定您的字符串是否类似于您期望处理的变体。因此,您可能需要根据索引和填充字符(即+,/,=)调整下面的正则表达式。

class String
  def resembles_base64?
    self.length % 4 == 0 && self =~ /^[A-Za-z0-9+\/=]+\Z/
  end
end

用法:

raise 'the string does not resemble Base64' unless my_string.resembles_base64?

不可能检查一个字符串是否是base64编码的。只有当该字符串是base64编码的字符串格式时才有可能验证,这意味着它可能是由base64编码生成的字符串(为了验证这一点,可以根据regexp验证字符串,也可以使用库,这个问题的许多其他答案提供了很好的检查方法,所以我不会详细讨论)。

例如,string flow是一个有效的base64编码的字符串。但不可能知道它只是一个简单的字符串,一个英语单词流,还是它是以64为基数编码的字符串~Z0

如果你正在使用Java,你实际上可以使用common -codec库

import org.apache.commons.codec.binary.Base64;

String stringToBeChecked = "...";
boolean isBase64 = Base64.isArrayByteBase64(stringToBeChecked.getBytes());

[更新1]弃用通知 而不是使用

Base64.isBase64(价值);

   /**
     * Tests a given byte array to see if it contains only valid characters within the Base64 alphabet. Currently the
     * method treats whitespace as valid.
     *
     * @param arrayOctet
     *            byte array to test
     * @return {@code true} if all bytes are valid characters in the Base64 alphabet or if the byte array is empty;
     *         {@code false}, otherwise
     * @deprecated 1.5 Use {@link #isBase64(byte[])}, will be removed in 2.0.
     */
    @Deprecated
    public static boolean isArrayByteBase64(final byte[] arrayOctet) {
        return isBase64(arrayOctet);
    }

在Java中,以下代码适用于我:

public static boolean isBase64Encoded(String s) {
        String pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(s);
        return m.find();
    }