void decode_send(char serial_input[181]){ char temp1[181] = {0}; char sender[181] = {0}; int rc = 0; printf("[DECODING: %s\n",serial_input); switch(serial_input[1]) { case '3': //disable warning sercurity serial_input[1] = '2'; sprintf(temp1, "005$%s$%s$%s", "rpi001", "ceslab", serial_input); break; case '4': //get status autolight 1 2 serial_input[1] = '3'; sprintf(temp1, "005$%s$%s$%s", "rpi001", "ceslab", serial_input); break; case '6': //turn led 1 off serial_input[1] = '5'; sprintf(temp1, "005$%s$%s$%s", "rpi001", "ceslab", serial_input); break; case '7': //turn led 2 on serial_input[1] = '6'; sprintf(temp1, "005$%s$%s$%s", "rpi001", "ceslab", serial_input); break; case '8': //turn led 2 off serial_input[1] = '6'; sprintf(temp1, "005$%s$%s$%s", "rpi001", "ceslab", serial_input); break; case '9': //turn led 3 on serial_input[1] = '7'; sprintf(temp1, "005$%s$%s$%s", "rpi001", "ceslab", serial_input); break; case 'a': //turn led 3 off serial_input[1] = '7'; sprintf(temp1, "005$%s$%s$%s", "rpi001", "ceslab", serial_input); break; case 'b': //turn led 4 on serial_input[1] = '8'; sprintf(temp1, "005$%s$%s$%s", "rpi001", "ceslab", serial_input); break; case 'c': //turn led 4 off serial_input[1] = '8'; sprintf(temp1, "005$%s$%s$%s", "rpi001", "ceslab", serial_input); break; case 'e': //turn Autoled 1 off serial_input[1] = 'd'; sprintf(temp1, "005$%s$%s$%s", "rpi001", "ceslab", serial_input); break; case 'k': // detected opened door sprintf(temp1,"006$rpi001$ceslab$Door"); break; default: sprintf(temp1, "005$%s$%s$%s", "rpi001", "ceslab", serial_input); break; } printf("[Detected] SEND data %s \n", temp1); rc = Base64Encode(temp1, sender, BUFFFERLEN); send(global_socket,sender,181,NULL); }
already_AddRefed<Promise> MediaKeySession::GenerateRequest(const nsAString& aInitDataType, const ArrayBufferViewOrArrayBuffer& aInitData, ErrorResult& aRv) { nsRefPtr<DetailedPromise> promise(MakePromise(aRv)); if (aRv.Failed()) { return nullptr; } if (!mUninitialized) { EME_LOG("MediaKeySession[%p,'%s'] GenerateRequest() failed, uninitialized", this, NS_ConvertUTF16toUTF8(mSessionId).get()); promise->MaybeReject(NS_ERROR_DOM_INVALID_ACCESS_ERR, NS_LITERAL_CSTRING("Session is already initialized in MediaKeySession.generateRequest()")); return promise.forget(); } mUninitialized = false; nsTArray<uint8_t> data; if (aInitDataType.IsEmpty() || !CopyArrayBufferViewOrArrayBufferData(aInitData, data)) { promise->MaybeReject(NS_ERROR_DOM_INVALID_ACCESS_ERR, NS_LITERAL_CSTRING("Bad arguments to MediaKeySession.generateRequest()")); EME_LOG("MediaKeySession[%p,'%s'] GenerateRequest() failed, " "invalid initData or initDataType", this, NS_ConvertUTF16toUTF8(mSessionId).get()); return promise.forget(); } // Convert initData to base64 for easier logging. // Note: UpdateSession() Move()s the data out of the array, so we have // to copy it here. nsAutoCString base64InitData; if (EME_LOG_ENABLED()) { nsDependentCSubstring rawInitData(reinterpret_cast<const char*>(data.Elements()), data.Length()); if (NS_FAILED(Base64Encode(rawInitData, base64InitData))) { NS_WARNING("Failed to base64 encode initData for logging"); } } PromiseId pid = mKeys->StorePromise(promise); mKeys->GetCDMProxy()->CreateSession(Token(), mSessionType, pid, aInitDataType, data); EME_LOG("MediaKeySession[%p,'%s'] GenerateRequest() sent, " "promiseId=%d initData(base64)='%s'", this, NS_ConvertUTF16toUTF8(mSessionId).get(), pid, base64InitData.get()); return promise.forget(); }
int TPMinitialProvisioning(void) { if (EKserverAddr == NULL) { printf("TPM Manufacturer Endorsement Credential Server Address cannot be NULL\n"); return -99; } RetrieveEndorsementCredentials(Base64Encode(HashEKPublicKey())); return 0; }
nsresult SRICheckDataVerifier::VerifyHash(const SRIMetadata& aMetadata, uint32_t aHashIndex, const nsACString& aSourceFileURI, nsIConsoleReportCollector* aReporter) { NS_ENSURE_ARG_POINTER(aReporter); nsAutoCString base64Hash; aMetadata.GetHash(aHashIndex, &base64Hash); SRILOG(("SRICheckDataVerifier::VerifyHash, hash[%u]=%s", aHashIndex, base64Hash.get())); nsAutoCString binaryHash; if (NS_WARN_IF(NS_FAILED(Base64Decode(base64Hash, binaryHash)))) { nsTArray<nsString> params; aReporter->AddConsoleReport(nsIScriptError::errorFlag, NS_LITERAL_CSTRING("Sub-resource Integrity"), nsContentUtils::eSECURITY_PROPERTIES, aSourceFileURI, 0, 0, NS_LITERAL_CSTRING("InvalidIntegrityBase64"), const_cast<const nsTArray<nsString>&>(params)); return NS_ERROR_SRI_CORRUPT; } uint32_t hashLength; int8_t hashType; aMetadata.GetHashType(&hashType, &hashLength); if (binaryHash.Length() != hashLength) { nsTArray<nsString> params; aReporter->AddConsoleReport(nsIScriptError::errorFlag, NS_LITERAL_CSTRING("Sub-resource Integrity"), nsContentUtils::eSECURITY_PROPERTIES, aSourceFileURI, 0, 0, NS_LITERAL_CSTRING("InvalidIntegrityLength"), const_cast<const nsTArray<nsString>&>(params)); return NS_ERROR_SRI_CORRUPT; } if (MOZ_LOG_TEST(SRILogHelper::GetSriLog(), mozilla::LogLevel::Debug)) { nsAutoCString encodedHash; nsresult rv = Base64Encode(mComputedHash, encodedHash); if (NS_SUCCEEDED(rv)) { SRILOG(("SRICheckDataVerifier::VerifyHash, mComputedHash=%s", encodedHash.get())); } } if (!binaryHash.Equals(mComputedHash)) { SRILOG(("SRICheckDataVerifier::VerifyHash, hash[%u] did not match", aHashIndex)); return NS_ERROR_SRI_CORRUPT; } SRILOG(("SRICheckDataVerifier::VerifyHash, hash[%u] verified successfully", aHashIndex)); return NS_OK; }
// https://developer.twitter.com // /en/docs/basics/authentication/guides/creating-a-signature.html std::string Network::CalcSignature( const std::string &http_method, const std::string &base_url, const KeyValue &oauth_param, const KeyValue &query_param, const std::string &consumer_secret, const std::string &token_secret) { // "Collecting parameters" // percent encode しつつ合成してキーでソートする KeyValue param; auto encode_insert = [this, ¶m](const KeyValue &map) { for (const auto &entry : map) { param.emplace(Escape(entry.first), Escape(entry.second)); } }; encode_insert(oauth_param); encode_insert(query_param); // 文字列にする // key1=value1&key2=value2&... std::string param_str; bool is_first = true; for (const auto &entry : param) { if (is_first) { is_first = false; } else { param_str += '&'; } param_str += entry.first; param_str += '='; param_str += entry.second; } // "Creating the signature base string" // 署名対象 std::string base = http_method; base += '&'; base += Escape(base_url); base += '&'; base += Escape(param_str); // "Getting a signing key" // 署名鍵は consumer_secret と token_secret をエスケープして & でつなぐだけ std::string key = Escape(consumer_secret); key += '&'; key += Escape(token_secret); // "Calculating the signature" ShaDigest signature; HmacSha1( key.data(), key.size(), reinterpret_cast<const unsigned char *>(base.data()), base.size(), signature); return Base64Encode(signature, sizeof(signature)); }
nsCString ToBase64(const nsTArray<uint8_t>& aBytes) { nsAutoCString base64; nsDependentCSubstring raw(reinterpret_cast<const char*>(aBytes.Elements()), aBytes.Length()); nsresult rv = Base64Encode(raw, base64); if (NS_WARN_IF(NS_FAILED(rv))) { return NS_LITERAL_CSTRING("[Base64EncodeFailed]"); } return base64; }
BOOL CSoftInfoQueryTask::CombineBodyContent(const SoftQueryInfoList &queryInfoList, string &bodyContent) { try { // SID string sids; { ostringstream os; os.imbue(locale::classic()); SoftQueryInfoCIter end = queryInfoList.end(); for(SoftQueryInfoCIter it = queryInfoList.begin(); it != end; ++it) { os<<it->_id<<','; } sids = os.str(); trim_right(sids, ","); } // 验证码 string code = "&c="; { unsigned int crc32 = ::CRC32(0, sids.c_str(), static_cast<unsigned int>(sids.length())); static const char KEY[] = "kingsoftgrade2_%^}[793dkle"; crc32 = ::CRC32(crc32, KEY, static_cast<unsigned int>(sizeof(KEY) - 1)); ostringstream os; os.imbue(locale::classic()); os<<hex<<crc32; code += os.str(); } // 版本 & SID & 验证码 string plainText = string("v=1_0&sid=") + sids + code; // base64 DWORD sizeBase64 = Base64EncodeGetLength(static_cast<DWORD>(plainText.length())); auto_buffer<char> buffer(sizeBase64 + 1); if(buffer.empty()) return FALSE; sizeBase64 = Base64Encode(&buffer[0], plainText.c_str(), static_cast<DWORD>(plainText.length())); buffer[sizeBase64] = '\0'; bodyContent = string("c=") + &buffer[0] + "\r\n"; return TRUE; } catch(...) {} return FALSE; }
static int _video_send_ClientThread() { char *header, *init , *dest, *data; char buffer[181] = {0}; char temp[181]={0}; char temp1[181]={0}; char combine[181]={0}; char receiver[181] = {0}; char sender[181] = {0}; int rc = 0; // Send ice ifo to android memcpy(temp,mInfo_SendVideo,sizeof(temp)); sprintf(combine,"002$%s$%s$%s",destBuf,originBuf,temp); rc = Base64Encode(combine, sender, BUFFFERLEN); send(global_socket,sender,181,NULL); printf ("=============== Send Video ===============\n"); printf("[send video] send = %s\n", combine); printf("[send video] send[Encode] = %s\n", sender); //Receive ice info from android if(recv(global_socket, buffer, 181, NULL)) { rc = Base64Decode(buffer, receiver, BUFFFERLEN); printf("[send video] receive = %s\n", buffer); printf("[send video] receive[Decode] = %s\n", receiver); header = strtok (receiver,"$"); init = strtok (NULL,"$"); dest = strtok (NULL,"$"); data = strtok (NULL,"$"); //printf("%s - %s\n",header ,data); int j=0; if (data!=NULL) while(j<strlen(data)) { temp1[j] = *(data+j); j++; } if(!strcmp(header,"002")) { AndroidInfo_SendVideo = (gchar*)malloc(sizeof(gchar)*181); memcpy(AndroidInfo_SendVideo, temp1, sizeof(temp1)); flag_trans = 1; return 0; } } }
static void copyKeys(QSettings &old, SettingsObject *object) { foreach (const QString &key, old.childKeys()) { QVariant value = old.value(key); if ((QMetaType::Type)value.type() == QMetaType::QDateTime) object->write(key, value.toDateTime()); else if ((QMetaType::Type)value.type() == QMetaType::QByteArray) object->write(key, Base64Encode(value.toByteArray())); else object->write(key, value.toString()); } }
void HTTPRequestHeader::SetAuthentication(int type, std::string userName, std::string password) { if (type != HTTP_AUTH_TYPE_BASIC) return; std::string auth("Basic "); std::string authString; authString.append(userName).append(":").append(password); authString = Base64Encode(authString); auth.append(authString); SetValue("Authorization", auth); }
static void desencode(char *content, char *content_in) { char de_content[1024] = {0}; DES_cblock key_cblock; DES_string_to_key(key, &key_cblock); DES_key_schedule schedule; DES_set_key_checked(&key_cblock, &schedule); DES_ncbc_encrypt(content, de_content, strlen(content), &schedule, &key_cblock, DES_ENCRYPT ); DES_string_to_key(key, &key_cblock); DES_set_key_checked(&key_cblock, &schedule); printf("key_cblock= %s\n", key_cblock); Base64Encode(de_content, strlen(de_content), content_in, sizeof(content_in)); }
already_AddRefed<Promise> MediaKeySession::Update(const ArrayBufferViewOrArrayBuffer& aResponse, ErrorResult& aRv) { nsRefPtr<DetailedPromise> promise(MakePromise(aRv, NS_LITERAL_CSTRING("MediaKeySession.update"))); if (aRv.Failed()) { return nullptr; } nsTArray<uint8_t> data; if (IsClosed() || !mKeys->GetCDMProxy()) { promise->MaybeReject(NS_ERROR_DOM_INVALID_STATE_ERR, NS_LITERAL_CSTRING("Session is closed or was not properly initialized")); EME_LOG("MediaKeySession[%p,'%s'] Update() failed, session is closed or was not properly initialised.", this, NS_ConvertUTF16toUTF8(mSessionId).get()); return promise.forget(); } if (!CopyArrayBufferViewOrArrayBufferData(aResponse, data)) { promise->MaybeReject(NS_ERROR_DOM_INVALID_ACCESS_ERR, NS_LITERAL_CSTRING("Invalid response buffer")); EME_LOG("MediaKeySession[%p,'%s'] Update() failed, invalid response buffer", this, NS_ConvertUTF16toUTF8(mSessionId).get()); return promise.forget(); } // Convert response to base64 for easier logging. // Note: UpdateSession() Move()s the data out of the array, so we have // to copy it here. nsAutoCString base64Response; if (EME_LOG_ENABLED()) { nsDependentCSubstring rawResponse(reinterpret_cast<const char*>(data.Elements()), data.Length()); if (NS_FAILED(Base64Encode(rawResponse, base64Response))) { NS_WARNING("Failed to base64 encode response for logging"); } } PromiseId pid = mKeys->StorePromise(promise); mKeys->GetCDMProxy()->UpdateSession(mSessionId, pid, data); EME_LOG("MediaKeySession[%p,'%s'] Update() sent to CDM, " "promiseId=%d Response(base64)='%s'", this, NS_ConvertUTF16toUTF8(mSessionId).get(), pid, base64Response.get()); return promise.forget(); }
UINT DlgModPass::ModPwdThread(LPVOID pParam) { DlgModPass* pDlg = static_cast<DlgModPass*>(pParam); CXTraderApp* pApp = g_App; CAppCfgs& s = g_App->m_cfg; char szOriPass[MAX_PATH],szNewPass[MAX_PATH]; if (pDlg->m_szNewPass.IsEmpty()||pDlg->m_szOldPass.IsEmpty()||pDlg->m_szNewCfm.IsEmpty()) { ShowErroTips(IDS_STREMPTY,IDS_STRTIPS); return 0; } if (pDlg->m_szNewPass.Compare(pDlg->m_szNewCfm)!=0) { ShowErroTips(IDS_CFMPASSERR,IDS_STRTIPS); return 0; } uni2ansi(CP_ACP,(LPTSTR)(LPCTSTR)pDlg->m_szOldPass,szOriPass); uni2ansi(CP_ACP,(LPTSTR)(LPCTSTR)pDlg->m_szNewPass,szNewPass); if (pDlg->m_itype==0) { pApp->m_cT->ReqUserPwdUpdate(szNewPass,szOriPass); DWORD dwRet = WaitForSingleObject(g_hEvent,WAIT_MS); if (dwRet==WAIT_OBJECT_0) { strcpy(s.m_sPwd,szNewPass); ResetEvent(g_hEvent); ///////±£´æÐ޸ĵÄÃÜÂë//////// size_t iSize = s.m_pInfVec.size(); TThostFtdcEncPasswordType szEncPass; Base64Encode(szEncPass, s.m_sPwd, 0); if (iSize>0){ strcpy(s.m_pInfVec[iSize-1].szPass,szEncPass); } } } if (pDlg->m_itype==1) { pApp->m_cT->ReqTdAccPwdUpdate(szNewPass,szOriPass); DWORD dwRet = WaitForSingleObject(g_hEvent,WAIT_MS); if (dwRet==WAIT_OBJECT_0) { ResetEvent(g_hEvent); } } pDlg->m_pModPass = NULL; return 0; }
const char *MSNObject::Base64Encoded(void) { if (fBase64.Length() == 0) { BString temp = Value(); temp << '\0'; char *b64 = Base64Encode(temp.String(), temp.Length()); fBase64 = b64; free(b64); }; return fBase64.String(); };
static int GetEncodedVersion(char *buf) { char version[20] = {0}; char tmp[9] = {0}; sprintf(tmp, "%02x%02x%02x%02x", magic[0], magic[1], magic[2], magic[3]); memcpy(version, ClientVersion, strlen(ClientVersion)); memcpy(version+16, magic, 4); EORMix(version, tmp, 16); EORMix(version, H3CKey, 20); return Base64Encode(version, buf, 20); }
int main() { char* in = "This is a simple base64 encoding test!\n這是個簡單的 Base64 編碼測試!"; int inlen = strlen(in); int outlen = Base64Encode((BYTE*)in, inlen, NULL, 0); char* out = new char[outlen + 1]; memset(out, 'X', outlen); outlen = Base64Encode((BYTE*)in, inlen, (BYTE*)out, outlen); out[outlen] = 0; printf("encoded: %s\n", out); in = out; inlen = strlen(in); outlen = Base64Decode((BYTE*)in, inlen, NULL, 0); out = new char[outlen + 1]; memset(out, 'X', outlen); outlen = Base64Decode((BYTE*)in, inlen, (BYTE*)out, outlen); out[outlen] = 0; printf("decoded: %s\n", out); delete in; delete out; getchar(); return 0; }
int main() { //Encode To Base64 char* base64EncodeOutput, *text="Hello World"; Base64Encode(text, strlen(text), &base64EncodeOutput); printf("Output (base64): %s\n", base64EncodeOutput); //Decode From Base64 char* base64DecodeOutput; size_t test; Base64Decode("SGVsbG8gV29ybGQ=", &base64DecodeOutput, &test); printf("Output: %s %d\n", base64DecodeOutput, test); return(0); }
bool NtlmProxy::NtlmStep1(char* pOutBuffer, int* pOutBufferLen) { memset(pOutBuffer, 0, *pOutBufferLen); if(!m_pFunTable) { return false; } SECURITY_STATUS SecurityStatus = SEC_E_OK; BYTE Buffer[1024]; memset(Buffer,0,1024); SecBuffer sBuffer; sBuffer.cbBuffer = 1024; sBuffer.BufferType = SECBUFFER_TOKEN; sBuffer.pvBuffer = Buffer; SecBufferDesc OutBufferDesc; OutBufferDesc.ulVersion = SECBUFFER_VERSION; OutBufferDesc.cBuffers = 1; OutBufferDesc.pBuffers = &sBuffer; SecurityStatus = m_pFunTable->InitializeSecurityContextA( &m_hCredentials, 0, "NTLM", ISC_REQ_USE_DCE_STYLE | ISC_REQ_DELEGATE | ISC_REQ_MUTUAL_AUTH |ISC_REQ_REPLAY_DETECT | ISC_REQ_SEQUENCE_DETECT |ISC_REQ_CONFIDENTIALITY | ISC_REQ_CONNECTION, 0, 0, 0, 0, &m_SecurityContext, &OutBufferDesc, &m_ulContextAttributes, &m_ts ); if (IS_ERROR(SecurityStatus)) return false; Base64Encode((unsigned char*)sBuffer.pvBuffer, sBuffer.cbBuffer, pOutBuffer, pOutBufferLen, BASE64_FLAG_NOCRLF); return true; }
static void CreateJSONCommunityFlowIdv4(json_t *js, const Flow *f, const uint16_t seed) { struct { uint16_t seed; uint32_t src; uint32_t dst; uint8_t proto; uint8_t pad0; uint16_t sp; uint16_t dp; } __attribute__((__packed__)) ipv4; uint32_t src = f->src.addr_data32[0]; uint32_t dst = f->dst.addr_data32[0]; uint16_t sp = f->sp; if (f->proto == IPPROTO_ICMP) sp = f->icmp_s.type; sp = htons(sp); uint16_t dp = f->dp; if (f->proto == IPPROTO_ICMP) dp = f->icmp_d.type; dp = htons(dp); ipv4.seed = htons(seed); if (ntohl(src) < ntohl(dst) || (src == dst && sp < dp)) { ipv4.src = src; ipv4.dst = dst; ipv4.sp = sp; ipv4.dp = dp; } else { ipv4.src = dst; ipv4.dst = src; ipv4.sp = dp; ipv4.dp = sp; } ipv4.proto = f->proto; ipv4.pad0 = 0; uint8_t hash[20]; if (ComputeSHA1((const uint8_t *)&ipv4, sizeof(ipv4), hash, sizeof(hash)) == 1) { unsigned char base64buf[64] = "1:"; unsigned long out_len = sizeof(base64buf) - 2; if (Base64Encode(hash, sizeof(hash), base64buf+2, &out_len) == SC_BASE64_OK) { json_object_set_new(js, "community_id", json_string((const char *)base64buf)); } } }
static void CreateJSONCommunityFlowIdv6(json_t *js, const Flow *f, const uint16_t seed) { struct { uint16_t seed; uint32_t src[4]; uint32_t dst[4]; uint8_t proto; uint8_t pad0; uint16_t sp; uint16_t dp; } __attribute__((__packed__)) ipv6; uint16_t sp = f->sp; if (f->proto == IPPROTO_ICMPV6) sp = f->icmp_s.type; sp = htons(sp); uint16_t dp = f->dp; if (f->proto == IPPROTO_ICMPV6) dp = f->icmp_d.type; dp = htons(dp); ipv6.seed = htons(seed); if (FlowHashRawAddressIPv6LtU32(f->src.addr_data32, f->dst.addr_data32) || ((memcmp(&f->src, &f->dst, sizeof(f->src)) == 0) && sp < dp)) { memcpy(&ipv6.src, &f->src.addr_data32, 16); memcpy(&ipv6.dst, &f->dst.addr_data32, 16); ipv6.sp = sp; ipv6.dp = dp; } else { memcpy(&ipv6.src, &f->dst.addr_data32, 16); memcpy(&ipv6.dst, &f->src.addr_data32, 16); ipv6.sp = dp; ipv6.dp = sp; } ipv6.proto = f->proto; ipv6.pad0 = 0; uint8_t hash[20]; if (ComputeSHA1((const uint8_t *)&ipv6, sizeof(ipv6), hash, sizeof(hash)) == 1) { unsigned char base64buf[64] = "1:"; unsigned long out_len = sizeof(base64buf) - 2; if (Base64Encode(hash, sizeof(hash), base64buf+2, &out_len) == SC_BASE64_OK) { json_object_set_new(js, "community_id", json_string((const char *)base64buf)); } } }
static void AlertJsonPacket(const Packet *p, json_t *js) { unsigned long len = GET_PKT_LEN(p) * 2; uint8_t encoded_packet[len]; Base64Encode((unsigned char*) GET_PKT_DATA(p), GET_PKT_LEN(p), encoded_packet, &len); json_object_set_new(js, "packet", json_string((char *)encoded_packet)); /* Create packet info. */ json_t *packetinfo_js = json_object(); if (unlikely(packetinfo_js == NULL)) { return; } json_object_set_new(packetinfo_js, "linktype", json_integer(p->datalink)); json_object_set_new(js, "packet_info", packetinfo_js); }
/* * Encrypts a plaintext and sets it to out * @param message: the plaintext string * @param length: the length of the plaintext string in bytes * @param key: the RSA object that is the key * @param out: where the output encrypted message is returned * @return: the length of the encrypted message */ unsigned int rsa_encrypt_message(unsigned char *message, unsigned int length, RSA *key, unsigned char **out) { unsigned char *encrypted_message = (unsigned char *)malloc(RSA_size(key)); unsigned int size; if ((size = RSA_public_encrypt(length, message, encrypted_message, key, padding)) < 0) { printf("RSA_public_encrypt() failed\n"); exit(EXIT_FAILURE); } if (Base64Encode(encrypted_message, size, (char **)out) < 0) { printf("Base64Encode failed\n"); exit(EXIT_FAILURE); } return size; }
std::string Token::toString() const { try { size_t len = 0; std::vector<char> buffer(1024); WritableUtils out(&buffer[0], buffer.size()); len += out.WriteInt32(identifier.size()); len += out.WriteRaw(&identifier[0], identifier.size()); len += out.WriteInt32(password.size()); len += out.WriteRaw(&password[0], password.size()); len += out.WriteText(kind); len += out.WriteText(service); return Base64Encode(&buffer[0], len); } catch (...) { NESTED_THROW(HdfsIOException, "cannot convert token to string"); } }
int main(int argc, char** argv){ int i, len64, lenout; char* pass = "******"; char* encoded, * decoded; char tmp64[BUFFER_SIZE], tmpout[BUFFER_SIZE]; for(i=1; i<argc; i++){ encoded = Base64Encode(argv[i], strlen(argv[i])); decoded = Base64Decode(encoded, strlen(encoded)); printf("%s -> %s -> %s\n", argv[i], encoded, decoded); free(encoded); free(decoded); //len64 = toS64(argv[i], strlen(argv[i]), tmp64, BUFFER_SIZE, pass); //lenout = fromS64(tmp64, len64, tmpout, BUFFER_SIZE, pass); //printf("%s -> %s -> %s\n", argv[i], tmp64, tmpout); } return 0; }
int on_response_header_value(http_parser* _, const char* at, size_t length) { _--; char value[RESPONSE_HEADER_MAXSIZE], *t; size_t real_length = RESPONSE_HEADER_MAXSIZE > length ? length : RESPONSE_HEADER_MAXSIZE; struct stream* stream = (struct stream*)_; if(stream->response_cache[0] == '\0') return 0; memcpy(&value, at, real_length); value[real_length] = '\0'; if (base64_output == 1) { t = Base64Encode(value, real_length); json_object_object_add(stream->json, stream->response_cache, json_object_new_string(t)); free(t); } else { json_object_object_add(stream->json, stream->response_cache, json_object_new_string(value)); } return 0; }
int on_url(http_parser* _, const char* at, size_t length) { char *t; struct stream* stream = (struct stream*)_; size_t real_length = URL_MAXSIZE > length ? length : URL_MAXSIZE; memcpy(&(stream->url), at, real_length); stream->url[real_length] = '\0'; stream->is_http = 1; json_object_object_add(stream->json, "request.method", json_object_new_string(http_method_str(stream->request_parser.method))); if (base64_output == 1 && test == 0) { t = Base64Encode(stream->url, real_length); json_object_object_add(stream->json, "request.url", json_object_new_string(t)); free(t); } else { json_object_object_add(stream->json, "request.url", json_object_new_string(stream->url)); } return 0; }
void Gate::BuildToken(char * token, s32 size, const TokenData& data) { char checkBuf[1024]; SafeMemcpy(checkBuf, sizeof(checkBuf), &data, sizeof(TokenData)); SafeSprintf(checkBuf + sizeof(TokenData), sizeof(checkBuf) - sizeof(TokenData), "%s", _tokenKey.GetString()); MD5 md5; md5.update(checkBuf, sizeof(TokenData) + _tokenKey.Length()); std::string sign = md5.toString(); char buf[1024]; SafeMemcpy(buf, sizeof(buf), &data, sizeof(TokenData)); SafeSprintf(buf + sizeof(TokenData), sizeof(buf) - sizeof(TokenData), "%s", sign.c_str()); u32 outSize = size; s32 ret = Base64Encode((u8*)buf, (u32)(sizeof(TokenData) + sign.size()), token, &outSize); OASSERT(ret == BASE64_OK, "wtf"); token[outSize] = 0; }
bool JabberProtocol::Authorize() { int length = (strlen(user.String())*2)+strlen(domain.String())+strlen(pass.String())+3; char credentials[length]; sprintf(credentials, "%s@%s%c%s%c%s", user.String(), domain.String(), '\0', user.String(), '\0', pass.String()); BString xml = "<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>"; char creds64[length*4]; Base64Encode(credentials, length, creds64, length*4); xml = xml.Append(creds64); xml << "</auth>"; socketAdapter->SendData(xml); return false; }
static JSVAL fs_readfile64(JSARGS args) { HandleScope scope; String::Utf8Value path(args[0]->ToString()); int fd = open(*path, O_RDONLY); if (fd == -1) { printf("%s\n%s\n", *path, strerror(errno)); return scope.Close(Null()); } long size = lseek(fd, 0, 2); lseek(fd, 0, 0); unsigned char buf[size]; if (read(fd, buf, size) != size) { return scope.Close(Null()); } close(fd); string encoded = Base64Encode(buf, size); Handle<String>s = String::New(encoded.c_str(), encoded.size()); return scope.Close(s); }
int encoding(char* in, int inlen, char** out, int* outlen) { int ret; char* aes; int aes_len; char* b64; int b64_len; aes_len = (inlen / 16 + 1) * 16; aes = get_pre_aes_buffer(aes_len); if (aes == NULL) { syslog(LOG_ERR, "get aes buffer for aesEncrypt failed\n"); return -1; } ret = aesEncrypt(in, inlen, aes, &aes_len); if (ret < 0) { syslog(LOG_ERR, "aesEncrypt failed ret %d\n", ret); return -2; } b64_len = (aes_len + 2) / 3 * 4; /* max base64 encode len */ b64 = (char*)malloc(b64_len + 4); /* 4 bytes for length field */ if (b64 == NULL) { syslog(LOG_ERR, "malloc buffer for Base64Encode failed\n"); return -3; } ret = Base64Encode(aes, aes_len, b64 + 4, &b64_len); if (ret < 0) { syslog(LOG_ERR, "Base64Encode failed ret %d\n", ret); return -4; } *out = b64; *(int*)b64 = htonl(b64_len); *outlen = b64_len + 4; return 0; }