summaryrefslogtreecommitdiffabout
path: root/lib/util.cc
Unidiff
Diffstat (limited to 'lib/util.cc') (more/less context) (ignore whitespace changes)
-rw-r--r--lib/util.cc67
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
@@ -4,3 +4,4 @@
4#include <string> 4#include <string>
5#include <mimetic/mimetic.h> 5#include <openssl/bio.h>
6#include <openssl/evp.h>
6#include <curl/curl.h> 7#include <curl/curl.h>
@@ -15,2 +16,54 @@ namespace opkele {
15 /* 16 /*
17 * base64
18 */
19 string encode_base64(const void *data,size_t length) {
20 BIO *b64 = 0, *bmem = 0;
21 try {
22 b64 = BIO_new(BIO_f_base64());
23 if(!b64)
24 throw exception_openssl(OPKELE_CP_ "failed to BIO_new() base64 encoder");
25 BIO_set_flags(b64,BIO_FLAGS_BASE64_NO_NL);
26 bmem = BIO_new(BIO_s_mem());
27 BIO_set_flags(b64,BIO_CLOSE);
28 if(!bmem)
29 throw exception_openssl(OPKELE_CP_ "failed to BIO_new() memory buffer");
30 BIO_push(b64,bmem);
31 if(BIO_write(b64,data,length)!=length)
32 throw exception_openssl(OPKELE_CP_ "failed to BIO_write()");
33 BIO_flush(b64);
34 char *rvd;
35 long rvl = BIO_get_mem_data(bmem,&rvd);
36 string rv(rvd,rvl);
37 BIO_free_all(b64);
38 return rv;
39 }catch(...) {
40 if(b64) BIO_free_all(b64);
41 throw;
42 }
43 }
44
45 void decode_base64(const string& data,vector<unsigned char>& rv) {
46 BIO *b64 = 0, *bmem = 0;
47 rv.clear();
48 try {
49 bmem = BIO_new_mem_buf((void*)data.data(),data.size());
50 if(!bmem)
51 throw exception_openssl(OPKELE_CP_ "failed to BIO_new_mem_buf()");
52 b64 = BIO_new(BIO_f_base64());
53 if(!b64)
54 throw exception_openssl(OPKELE_CP_ "failed to BIO_new() base64 decoder");
55 BIO_set_flags(b64,BIO_FLAGS_BASE64_NO_NL);
56 BIO_push(b64,bmem);
57 unsigned char tmp[512];
58 size_t rb = 0;
59 while((rb=BIO_read(b64,tmp,sizeof(tmp)))>0)
60 rv.insert(rv.end(),tmp,&tmp[rb]);
61 BIO_free_all(b64);
62 }catch(...) {
63 if(b64) BIO_free_all(b64);
64 throw;
65 }
66 }
67
68 /*
16 * big numerics 69 * big numerics
@@ -20,6 +73,3 @@ namespace opkele {
20 vector<unsigned char> bin; 73 vector<unsigned char> bin;
21 mimetic::Base64::Decoder b; 74 decode_base64(b64,bin);
22 mimetic::decode(
23 b64.begin(),b64.end(), b,
24 back_insert_iterator<vector<unsigned char> >(bin) );
25 BIGNUM *rv = BN_bin2bn(&(bin.front()),bin.size(),0); 75 BIGNUM *rv = BN_bin2bn(&(bin.front()),bin.size(),0);
@@ -40,8 +90,3 @@ namespace opkele {
40 int l = BN_bn2bin(bn,&(bin.front())); 90 int l = BN_bn2bin(bn,&(bin.front()));
41 string rv; 91 return encode_base64(&(bin.front()),l);
42 mimetic::Base64::Encoder b(0);
43 mimetic::encode(
44 bin.begin(),bin.begin()+l, b,
45 back_insert_iterator<string>(rv) );
46 return rv;
47 } 92 }