I want to decode a base64 encoded string, then store it in my database. If the input is not base64 encoded, I need to throw an error. How can I check if the string was base64 enocoded?
相关问题
- Views base64 encoded blob in HTML with PHP
- POST Base64 encoded data in PHP
- PHP base64_decode C# equivalent
- can't add a base64-encoded image to vCard
- Getting base64 string on scraping image src
相关文章
- How to create base64Binary data?
- Base64 Encoding: Illegal base64 character 3c
- Base64URL decoding via JavaScript?
- Python 3 and base64 encoding of a binary file
- Is it a good practice to save a base64 string on t
- Decode Base64 string to byte array
- Can you resize or change resolution of base64 imag
- Why does k8s secrets need to be base64 encoded whe
There are many variants of Base64, so consider just determining if your string resembles the varient you expect to handle. As such, you may need to adjust the regex below with respect to the index and padding characters (i.e.
+
,/
,=
).Usage:
Well you can:
If you're expecting that it will be base64, then you can probably just use whatever library is available on your platform to try to decode it to a byte array, throwing an exception if it's not valid base 64. That depends on your platform, of course.
It is impossible to check if a string is base64 encoded or not. It is only possible to validate if that string is of a base64 encoded string format, which would mean that it could be a string produced by base64 encoding (to check that, string could be validated against a regexp or a library could be used, many other answers to this question provide good ways to check this, so I won't go into details).
For example, string
flow
is a valid base64 encoded string. But it is impossible to know if it is just a simple string, an English wordflow
, or is it base 64 encoded string~Z0
/^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$/
this regular expression helped me identify the base64 in my application in rails, I only had one problem, it is that it recognizes the string "errorDescripcion", I generate an error, to solve it just validate the long of string.
Try this:
You can use the following regular expression to check if a string is base64 encoded or not:
In base64 encoding, the character set is
[A-Z, a-z, 0-9, and + /]
. If the rest length is less than 4, the string is padded with'='
characters.^([A-Za-z0-9+/]{4})*
means the string starts with 0 or more base64 groups.([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$
means the string ends in one of three forms:[A-Za-z0-9+/]{4}
,[A-Za-z0-9+/]{3}=
or[A-Za-z0-9+/]{2}==
.