Herewith is an example of encoding to and from base64 using OpenSSL's C library. Code presented here is both binary safe, and portable (i.e. it should work on any Posix compliant system e.g. FreeBSD and Linux).
The MIT License (MIT)
Copyright (c) 2013 Barry Steyn
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
About that
calcDecodeLength
function again. It has a critical bug when you're looking for that equal sign terminators. It's a very classic example of buffer over-read. Just think about string which is shorter than 2. You should not access memory which doesn't belong to you.Btw, I'm surprised how many people over the whole internet are trying to decode a B64 strings with using that crappy interface provided by OpenSSL. I guess that if you're using OpenSSL, then your job must be somehow related to the security. That's why I'm surprised even more, because that Base64 filter doesn't handle wrong inputs very well. Yes, it doesn't crash (hopefully), but it will report incorrect B64 strings as a valid sequences, but result is just shorter. It simply ends reading on first incorrect character and that's all. Normally that might be acceptable, but in the field of security, that's always suspicious. On top of that, all that "BIO" routines are slow like hell.
So, don't be lazy and write your own B64 encoder and decoder or grab some other code. It's not so difficult, trust me :)