-rw-r--r-- | lib/util.cc | 67 |
1 files changed, 56 insertions, 11 deletions
diff --git a/lib/util.cc b/lib/util.cc index d78b5e0..d9abca7 100644 --- a/lib/util.cc +++ b/lib/util.cc @@ -1,9 +1,10 @@ #include <errno.h> #include <cassert> #include <vector> #include <string> -#include <mimetic/mimetic.h> +#include <openssl/bio.h> +#include <openssl/evp.h> #include <curl/curl.h> #include "opkele/util.h" #include "opkele/exception.h" @@ -12,17 +13,66 @@ namespace opkele { namespace util { /* + * base64 + */ + string encode_base64(const void *data,size_t length) { + BIO *b64 = 0, *bmem = 0; + try { + b64 = BIO_new(BIO_f_base64()); + if(!b64) + throw exception_openssl(OPKELE_CP_ "failed to BIO_new() base64 encoder"); + BIO_set_flags(b64,BIO_FLAGS_BASE64_NO_NL); + bmem = BIO_new(BIO_s_mem()); + BIO_set_flags(b64,BIO_CLOSE); + if(!bmem) + throw exception_openssl(OPKELE_CP_ "failed to BIO_new() memory buffer"); + BIO_push(b64,bmem); + if(BIO_write(b64,data,length)!=length) + throw exception_openssl(OPKELE_CP_ "failed to BIO_write()"); + BIO_flush(b64); + char *rvd; + long rvl = BIO_get_mem_data(bmem,&rvd); + string rv(rvd,rvl); + BIO_free_all(b64); + return rv; + }catch(...) { + if(b64) BIO_free_all(b64); + throw; + } + } + + void decode_base64(const string& data,vector<unsigned char>& rv) { + BIO *b64 = 0, *bmem = 0; + rv.clear(); + try { + bmem = BIO_new_mem_buf((void*)data.data(),data.size()); + if(!bmem) + throw exception_openssl(OPKELE_CP_ "failed to BIO_new_mem_buf()"); + b64 = BIO_new(BIO_f_base64()); + if(!b64) + throw exception_openssl(OPKELE_CP_ "failed to BIO_new() base64 decoder"); + BIO_set_flags(b64,BIO_FLAGS_BASE64_NO_NL); + BIO_push(b64,bmem); + unsigned char tmp[512]; + size_t rb = 0; + while((rb=BIO_read(b64,tmp,sizeof(tmp)))>0) + rv.insert(rv.end(),tmp,&tmp[rb]); + BIO_free_all(b64); + }catch(...) { + if(b64) BIO_free_all(b64); + throw; + } + } + + /* * big numerics */ BIGNUM *base64_to_bignum(const string& b64) { vector<unsigned char> bin; - mimetic::Base64::Decoder b; - mimetic::decode( - b64.begin(),b64.end(), b, - back_insert_iterator<vector<unsigned char> >(bin) ); + decode_base64(b64,bin); BIGNUM *rv = BN_bin2bn(&(bin.front()),bin.size(),0); if(!rv) throw failed_conversion(OPKELE_CP_ "failed to BN_bin2bn()"); return rv; @@ -37,14 +87,9 @@ namespace opkele { string bignum_to_base64(const BIGNUM *bn) { vector<unsigned char> bin(BN_num_bytes(bn)); int l = BN_bn2bin(bn,&(bin.front())); - string rv; - mimetic::Base64::Encoder b(0); - mimetic::encode( - bin.begin(),bin.begin()+l, b, - back_insert_iterator<string>(rv) ); - return rv; + return encode_base64(&(bin.front()),l); } /* * w3c times |