void array_new(ArrayValue* myself, char* xml) { Tag* valueTag; DictValue* curValue; myself->values = NULL; myself->size = 0; while (*xml != '\0') { valueTag = getNextTag(&xml); if (valueTag == NULL) { break; } myself->size++; myself->values = realloc(myself->values, sizeof(DictValue*) * myself->size); curValue = (DictValue*) malloc(sizeof(DictValue)); curValue->key = (char*) malloc(sizeof("arraykey")); strcpy(curValue->key, "arraykey"); curValue->next = NULL; if (strcmp(valueTag->name, "dict") == 0) { curValue->type = DictionaryType; curValue = (DictValue*) realloc(curValue, sizeof(Dictionary)); dictionary_new((Dictionary*) curValue, valueTag->xml); } else if (strcmp(valueTag->name, "string") == 0) { curValue->type = StringType; curValue = (DictValue*) realloc(curValue, sizeof(StringValue)); ((StringValue*)curValue)->value = (char*) malloc(sizeof(char) * (strlen(valueTag->xml) + 1)); strcpy(((StringValue*)curValue)->value, valueTag->xml); } else if(strcmp(valueTag->name, "data") == 0) { size_t len; curValue->type = StringType; curValue = (DictValue*) realloc(curValue, sizeof(DataValue)); ((DataValue*)curValue)->value = decodeBase64(valueTag->xml, &len); ((DataValue*)curValue)->len = len; } else if(strcmp(valueTag->name, "integer") == 0) { curValue->type = IntegerType; curValue = (DictValue*) realloc(curValue, sizeof(IntegerValue)); sscanf(valueTag->xml, "%d", &(((IntegerValue*) curValue)->value)); } else if (strcmp(valueTag->name, "array") == 0) { curValue->type = ArrayType; curValue = (DictValue*) realloc(curValue, sizeof(ArrayValue)); array_new((ArrayValue*) curValue, valueTag->xml); } else if (strcmp(valueTag->name, "true/") == 0) { curValue->type = BoolType; curValue = (DictValue*) realloc(curValue, sizeof(BoolValue)); ((BoolValue*) curValue)->value = TRUE; } else if (strcmp(valueTag->name, "false/") == 0) { curValue->type = BoolType; curValue = (DictValue*) realloc(curValue, sizeof(BoolValue)); ((BoolValue*) curValue)->value = FALSE; } myself->values[myself->size - 1] = curValue; releaseTag(valueTag); } }
LUA_STRING CCCrypto::encodingBase64Lua(bool isDecoding, const char* input, int inputLength) { CCScriptEngineProtocol* engine = CCScriptEngineManager::sharedManager()->getScriptEngine(); engine->cleanLuaStack(); lua_State* L = engine->getLuaState(); int outputLength = inputLength * 2; char* output = static_cast<char*>(malloc(outputLength)); int dataUsed = -1; if (isDecoding) { dataUsed = decodeBase64(input, output, outputLength); } else { dataUsed = encodeBase64(input, inputLength, output, outputLength); } if (dataUsed > 0 && dataUsed < outputLength) { lua_pushlstring(L, output, dataUsed); } else { lua_pushnil(L); } free(output); return 1; }
LUA_STRING CCCrypto::encodingBase64Lua(bool isDecoding, const char* input, int inputLength) { CCLuaStack* stack = CCLuaEngine::defaultEngine()->getLuaStack(); stack->clean(); int outputLength = inputLength * 2; char* output = static_cast<char*>(malloc(outputLength)); int dataUsed = -1; if (isDecoding) { dataUsed = decodeBase64(input, output, outputLength); } else { dataUsed = encodeBase64((unsigned char*)input, inputLength, output, outputLength); } if (dataUsed > 0 && dataUsed < outputLength) { stack->pushString(output, dataUsed); } else { stack->pushNil(); } free(output); return 1; }
// Convenience specialization, filling string instead of byte-dumping into it. inline std::string decodeBase64(const std::string &encoded) { std::string rv; decodeBase64(encoded, std::back_inserter(rv)); return rv; }
/*! * pixaGenerateFontFromString() * * Input: fontsize (4, 6, 8, ... , 20, in pts at 300 ppi) * &bl1 (<return> baseline of row 1) * &bl2 (<return> baseline of row 2) * &bl3 (<return> baseline of row 3) * Return: pixa of font bitmaps for 95 characters, or null on error * * Notes: * (1) See pixaGenerateFontFromFile() for details. */ PIXA * pixaGenerateFontFromString(l_int32 fontsize, l_int32 *pbl0, l_int32 *pbl1, l_int32 *pbl2) { l_uint8 *data; l_int32 redsize, nbytes; PIX *pix; PIXA *pixa; PROCNAME("pixaGenerateFontFromString"); if (!pbl0 || !pbl1 || !pbl2) return (PIXA *)ERROR_PTR("&bl not all defined", procName, NULL); *pbl0 = *pbl1 = *pbl2 = 0; redsize = (fontsize / 2) - 2; if (redsize < 0 || redsize > NUM_FONTS) return (PIXA *)ERROR_PTR("invalid font size", procName, NULL); if (fontsize == 4) { data = decodeBase64(fontdata_4, strlen(fontdata_4), &nbytes); } else if (fontsize == 6) { data = decodeBase64(fontdata_6, strlen(fontdata_6), &nbytes); } else if (fontsize == 8) { data = decodeBase64(fontdata_8, strlen(fontdata_8), &nbytes); } else if (fontsize == 10) { data = decodeBase64(fontdata_10, strlen(fontdata_10), &nbytes); } else if (fontsize == 12) { data = decodeBase64(fontdata_12, strlen(fontdata_12), &nbytes); } else if (fontsize == 14) { data = decodeBase64(fontdata_14, strlen(fontdata_14), &nbytes); } else if (fontsize == 16) { data = decodeBase64(fontdata_16, strlen(fontdata_16), &nbytes); } else if (fontsize == 18) { data = decodeBase64(fontdata_18, strlen(fontdata_18), &nbytes); } else { /* fontsize == 20 */ data = decodeBase64(fontdata_20, strlen(fontdata_20), &nbytes); } if (!data) return (PIXA *)ERROR_PTR("data not made", procName, NULL); pix = pixReadMem(data, nbytes); FREE(data); if (!pix) return (PIXA *)ERROR_PTR("pix not made", procName, NULL); pixa = pixaGenerateFont(pix, fontsize, pbl0, pbl1, pbl2); pixDestroy(&pix); return pixa; }
/*! * l_autodecode_137() * * Input: index into array of functions * Return: data struct (e.g., pixa) in memory */ void * l_autodecode_137(l_int32 index) { l_uint8 *data1, *data2; l_int32 size1; size_t size2; void *result = NULL; l_int32 nfunc = 2; PROCNAME("l_autodecode_137"); if (index < 0 || index >= nfunc) { L_ERROR("invalid index = %d; must be less than %d\n", procName, index, nfunc); return NULL; } lept_mkdir("lept/auto"); /* Unencode selected string, write to file, and read it */ switch (index) { case 0: data1 = decodeBase64(l_strdata_0, strlen(l_strdata_0), &size1); data2 = zlibUncompress(data1, size1, &size2); l_binaryWrite("/tmp/lept/auto/data.bin","w", data2, size2); result = (void *)pixaRead("/tmp/lept/auto/data.bin"); lept_free(data1); lept_free(data2); break; case 1: data1 = decodeBase64(l_strdata_1, strlen(l_strdata_1), &size1); data2 = zlibUncompress(data1, size1, &size2); l_binaryWrite("/tmp/lept/auto/data.bin","w", data2, size2); result = (void *)pixaRead("/tmp/lept/auto/data.bin"); lept_free(data1); lept_free(data2); break; default: L_ERROR("invalid index", procName); } return result; }
// Decodes from Base 64 to any sufficiently trivial object. template <typename T> T decodeBase64Bytewise(const std::string &encoded) { #if not defined __GNUC__ or __GNUC__ > 4 static_assert(std::is_trivially_copyable<T>::value, "requires a trivially copyable type"); #endif T x; decodeBase64(encoded, reinterpret_cast<unsigned char *>(&x)); return x; }
/*! * \brief l_bootnum_gen2() * * \return pixa of labelled digits * * <pre> * Call this way: * PIXA *pixa = l_bootnum_gen2(); (C) * Pixa *pixa = l_bootnum_gen2(); (C++) * </pre> */ PIXA * l_bootnum_gen2(void) { l_uint8 *data1, *data2; l_int32 size1; size_t size2; PIXA *pixa; /* Unencode selected string, write to file, and read it */ data1 = decodeBase64(l_bootnum2, strlen(l_bootnum2), &size1); data2 = zlibUncompress(data1, size1, &size2); pixa = pixaReadMem(data2, size2); lept_free(data1); lept_free(data2); return pixa; }
/*! * l_bootnum_gen() * * Return: the bootnum pixa * * Call this way: * PIXA *pixa = (PIXA *)l_bootnum_gen(); (C) * Pixa *pixa = (Pixa *)l_bootnum_gen(); (C++) */ void * l_bootnum_gen() { l_uint8 *data1, *data2; l_int32 size1; size_t size2; void *result; /* Unencode selected string, write to file, and read it */ data1 = decodeBase64(l_bootnum, strlen(l_bootnum), &size1); data2 = zlibUncompress(data1, size1, &size2); l_binaryWrite("/tmp/data.bin", "w", data2, size2); result = (void *)pixaRead("/tmp/data.bin"); FREE(data1); FREE(data2); return result; }
/*! * \brief l_bootnum_gen3() * * \return pixa of labelled digits * * <pre> * Call this way: * PIXA *pixa = l_bootnum_gen3(); (C) * Pixa *pixa = l_bootnum_gen3(); (C++) * </pre> */ PIXA * l_bootnum_gen3(void) { l_uint8 *data1, *data2; l_int32 size1; size_t size2; PIXA *pixa; lept_mkdir("lept/auto"); /* Unencode selected string, uncompress it, and read it */ data1 = decodeBase64(l_strdata_0, strlen(l_strdata_0), &size1); data2 = zlibUncompress(data1, size1, &size2); pixa = pixaReadMem(data2, size2); lept_free(data1); lept_free(data2); return pixa; }
/* 功能:验证签名 入口: char*certFile 证书(含匙) char* plainText 明文 char* cipherText 签名 出口: bool true 签名验证成功 bool false 验证失败 */ bool PKCS7_VerifySign(char*certFile,char* plainText,char* cipherText ) { /* Get X509 */ FILE* fp = fopen (certFile, "r"); if (fp == NULL) return false; X509* x509 = PEM_read_X509(fp, NULL, NULL, NULL); fclose (fp); if (x509 == NULL) { ERR_print_errors_fp (stderr); return false; } //BASE64解码 unsigned char *retBuf[1024*8]; int retBufLen = sizeof(retBuf); memset(retBuf,0,sizeof(retBuf)); decodeBase64(cipherText,(void *)retBuf,&retBufLen); //从签名中取PKCS7对象 BIO* vin = BIO_new_mem_buf(retBuf,retBufLen); PKCS7 *p7 = d2i_PKCS7_bio(vin,NULL); //取STACK_OF(X509)对象 STACK_OF(X509) *stack=sk_X509_new_null();//X509_STORE_new() sk_X509_push(stack,x509); //明码数据转为BIO BIO *bio = BIO_new(BIO_s_mem()); BIO_puts(bio,plainText); //验证签名 int err = PKCS7_verify(p7, stack, NULL,bio, NULL, PKCS7_NOVERIFY); if (err != 1) { ERR_print_errors_fp (stderr); return false; } return true; }
/*! * l_bootnum_gen2() * * Return: the bootnum2 pixa * * Call this way: * PIXA *pixa = (PIXA *)l_bootnum_gen2(); (C) * Pixa *pixa = (Pixa *)l_bootnum_gen2(); (C++) */ void * l_bootnum_gen2(void) { l_uint8 *data1, *data2; l_int32 size1; size_t size2; void *result; lept_mkdir("lept/auto"); /* Unencode selected string, write to file, and read it */ data1 = decodeBase64(l_bootnum2, strlen(l_bootnum2), &size1); data2 = zlibUncompress(data1, size1, &size2); l_binaryWrite("/tmp/lept/auto/data.bin", "w", data2, size2); result = (void *)pixaRead("/tmp/lept/auto/data.bin"); lept_free(data1); lept_free(data2); return result; }
static unsigned char* getXMLData(char** location, size_t *dataLength, char** encodedStart, size_t* encodedLength) { char* curLoc; char* tagEnd; char* encodedData; unsigned char* toReturn; size_t strLen; curLoc = *location; curLoc = strstr(curLoc, "<data>"); if(!curLoc) return NULL; curLoc += sizeof("<data>") - 1; if (encodedStart) *encodedStart = curLoc; tagEnd = strstr(curLoc, "</data>"); strLen = (size_t)(tagEnd - curLoc); if (encodedLength) *encodedLength = strLen; encodedData = (char*) malloc(strLen + 1); memcpy(encodedData, curLoc, strLen); encodedData[strLen] = '\0'; curLoc = tagEnd + sizeof("</data>") - 1; *location = curLoc; toReturn = decodeBase64(encodedData, dataLength); free(encodedData); return toReturn; }
VARIANT CMUSHclientDoc::Base64Decode(LPCTSTR Text) { VARIANT vaResult; VariantInit(&vaResult); CString strResult; try { strResult = decodeBase64 (Text); } // end of try catch(CException* e) { e->Delete (); vaResult.vt = VT_NULL; return vaResult; } // end of catch SetUpVariantString (vaResult, strResult); return vaResult; } // end of CMUSHclientDoc::Base64Decode
void SeeIfBase64 (CString & strText) { const char * p = strText; char c; bool bBase64 = true; int iCount; // locale-independent tests (see decodeBase64) for (iCount = 0 ; c = *p; p++) if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v' ) continue; else if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '+' || c == '/' || c == '=') iCount++; else { bBase64 = false; break; } // might be base 64 if only base64 characters, and mod 4 non-space length // (if base64 can't be plain XML because plain XML will have < in it) if (bBase64 && (iCount % 4 == 0)) strText = decodeBase64 (strText); } // end of SeeIfBase64
QByteArray FLDigiDoc::decodeBase64(const QByteArray &data) const { return decodeBase64((const byte *)data.data(), data.size()); }
/** * Take the converted Ndef JSON output return, and create a NdefMessage */ jobject convertJsonToNdefMessage(const char *input, size_t length) { json_error_t error; json_t *root = json_loads(input, 0, &error); if (!root) { LOGE("convertJsontoNdefMessage: unable to parse input: (%s)", input); return NULL; } // Android object: NdefMessage with NdefRecord array. // Go to record array items: json_t *jsonType = json_object_get(root, "type"); json_t *jsonContent = json_object_get(root, "content"); json_t *jsonRecords = json_object_get(jsonContent, "records"); // Determine number of records and create NdefRecord array: jsize numRecords = json_array_size(jsonRecords); jobjectArray ndefRecords = dummyEnv->NewObjectArray(numRecords, NULL, NULL); // Iterate through opaque records, and append to jbyteArray: for (int i = 0; i < numRecords; i++) { LOGI("Processing message record (%d)", i); jobject jNdefRec = instantiate_NdefRecord(); json_t *jsonRecordItem = json_array_get(jsonRecords, i); // Fields: char tnf; json_t *tnfItem = json_object_get(jsonRecordItem, "tnf"); if (json_is_integer(tnfItem)) { tnf = json_integer_value(tnfItem); } else { // Although we can try to parse a non-integer as a tnf bit field, // we'll just reject the message. break; } const char* type = json_string_value(json_object_get(jsonRecordItem, "type")); const char* id = json_string_value(json_object_get(jsonRecordItem, "id")); const char* payload = json_string_value(json_object_get(jsonRecordItem, "payload")); // We'll keep empty binary/strings if decode somehow failed. size_t decodedIdLen; size_t decodedPayloadLen; size_t decodedTypeLen; type = decodeBase64((unsigned char*)type, strlen(type), &decodedTypeLen); id = decodeBase64((unsigned char*)id, strlen(id), &decodedIdLen); payload = decodeBase64((unsigned char*)payload, strlen(payload), &decodedPayloadLen); LOGI("tnf=(%d)", tnf); LOGI("type=(%s), typeLen(%d)", type, decodedTypeLen); LOGI("id=(%s), idLen(%d)", id, decodedIdLen); LOGI("payload=(%s), payloadLen(%d)", payload, decodedPayloadLen); jbyteArray idBuf = dummyEnv->NewByteArray(decodedIdLen); jbyteArray payloadBuf = dummyEnv->NewByteArray(decodedPayloadLen); jbyteArray typeBuf = dummyEnv->NewByteArray(decodedTypeLen); dummyEnv->SetByteArrayRegion(idBuf, 0, decodedIdLen, (jbyte*)id); dummyEnv->SetByteArrayRegion(payloadBuf, 0, decodedPayloadLen, (jbyte*)payload); dummyEnv->SetByteArrayRegion(typeBuf, 0, decodedTypeLen, (jbyte*)type); // Check that tnf is in range jbyte tnfByte = (jbyte) tnf; if(tnfByte < 0 || tnfByte > 7) { LOGE("TNF out of range (%d)!", tnfByte); json_decref(root); return NULL; } // Create record: android_nfc_NdefRecord_init(jNdefRec, tnfByte, typeBuf, idBuf, payloadBuf); isNdefMessageParsable(wrapper_android_nfc_NdefRecord_toByteArray(dummyEnv, jNdefRec)); dummyEnv->SetObjectArrayElement(ndefRecords, i, jNdefRec); } json_decref(root); jobject ndefMsg = instantiate_NdefMessage(); android_nfc_NdefMessage_init_ndef(ndefMsg, ndefRecords); isNdefMessageParsable(android_nfc_NdefMessage_toByteArray(ndefMsg)); return ndefMsg; }
int main(int argc, char **argv) { char buf[512]; char *pathname, *datastr, *formstr; l_uint8 *data1, *data2; l_int32 i, bl1, bl2, bl3, sbytes, formbytes, fontsize, rbytes; size_t nbytes; PIX *pix1, *pix2, *pixd; PIXA *pixa; L_REGPARAMS *rp; if (regTestSetup(argc, argv, &rp)) return 1; /* ------------ Generate pixa char bitmap files from file ----------- */ lept_rmdir("filefonts"); lept_mkdir("filefonts"); for (i = 0; i < 9; i++) { pixaSaveFont("fonts", "/tmp/filefonts", sizes[i]); pathname = genPathname("/tmp/filefonts", outputfonts[i]); pixa = pixaRead(pathname); if (rp->display) { fprintf(stderr, "Found %d chars in font size %d\n", pixaGetCount(pixa), sizes[i]); } pixd = pixaDisplayTiled(pixa, 1500, 0, 15); regTestWritePixAndCheck(rp, pixd, IFF_PNG); /* 0 - 8 */ if (i == 2) pixDisplayWithTitle(pixd, 100, 0, NULL, rp->display); pixDestroy(&pixd); pixaDestroy(&pixa); lept_free(pathname); } lept_rmdir("filefonts"); /* ---------- Generate pixa char bitmap files from string --------- */ lept_rmdir("strfonts"); lept_mkdir("strfonts"); for (i = 0; i < 9; i++) { pixaSaveFont(NULL, "/tmp/strfonts", sizes[i]); pathname = genPathname("/tmp/strfonts", outputfonts[i]); pixa = pixaRead(pathname); if (rp->display) { fprintf(stderr, "Found %d chars in font size %d\n", pixaGetCount(pixa), sizes[i]); } pixd = pixaDisplayTiled(pixa, 1500, 0, 15); regTestWritePixAndCheck(rp, pixd, IFF_PNG); /* 9 - 17 */ if (i == 2) pixDisplayWithTitle(pixd, 100, 150, NULL, rp->display); pixDestroy(&pixd); pixaDestroy(&pixa); lept_free(pathname); } /* ----- Use pixaGetFont() and write the result out -----*/ lept_rmdir("pafonts"); lept_mkdir("pafonts"); for (i = 0; i < 9; i++) { pixa = pixaGetFont("/tmp/strfonts", sizes[i], &bl1, &bl2, &bl3); fprintf(stderr, "Baselines are at: %d, %d, %d\n", bl1, bl2, bl3); snprintf(buf, sizeof(buf), "/tmp/pafonts/chars-%d.pa", sizes[i]); pixaWrite(buf, pixa); if (i == 2) { pixd = pixaDisplayTiled(pixa, 1500, 0, 15); pixDisplayWithTitle(pixd, 100, 300, NULL, rp->display); pixDestroy(&pixd); } pixaDestroy(&pixa); } lept_rmdir("pafonts"); /* ------- Generate 4/3 encoded ascii strings from tiff files ------ */ lept_rmdir("fontencode"); lept_mkdir("fontencode"); for (i = 0; i < 9; i++) { fontsize = 2 * i + 4; pathname = genPathname("fonts", inputfonts[i]); data1 = l_binaryRead(pathname, &nbytes); datastr = encodeBase64(data1, nbytes, &sbytes); if (rp->display) fprintf(stderr, "nbytes = %lu, sbytes = %d\n", (unsigned long)nbytes, sbytes); formstr = reformatPacked64(datastr, sbytes, 4, 72, 1, &formbytes); snprintf(buf, sizeof(buf), "/tmp/fontencode/formstr_%d.txt", fontsize); l_binaryWrite(buf, "w", formstr, formbytes); regTestCheckFile(rp, buf); /* 18-26 */ if (i == 8) pix1 = pixReadMem(data1, nbytes); /* original */ FREE(data1); data2 = decodeBase64(datastr, sbytes, &rbytes); snprintf(buf, sizeof(buf), "/tmp/fontencode/image_%d.tif", fontsize); l_binaryWrite(buf, "w", data2, rbytes); if (i == 8) { pix2 = pixReadMem(data2, rbytes); /* encode/decode */ regTestComparePix(rp, pix1, pix2); /* 27 */ pixDestroy(&pix1); pixDestroy(&pix2); } FREE(data2); FREE(pathname); FREE(datastr); FREE(formstr); } /* ------------ Get timing for font generation ----------- */ startTimer(); for (i = 0; i < 100; i++) { pixa = pixaGenerateFontFromString(sizes[5], &bl1, &bl2, &bl3); pixaDestroy(&pixa); } fprintf(stderr, "Time for font gen = %7.4f sec\n", stopTimer() / 100.0); return regTestCleanup(rp); }
/* * carsonl, jan 8,98 * Decodes a string encoded in RFC2047 format. If the string is not encoded * returns the original string. Can be used on the header value returned by * getHeader() and getAllHeaders() methods in MIMEMessage class. * * parameter : * * szInputString : string to be trimmed * * return : The decoded header string. */ char *decodeHeader( char *szInputString ) { int len, retLen = 0; int i, j, outBytes, outBits; int nStart = 0; int nEnd = 0; char *szEncodedText = NULL; char *szDecodedText = NULL; char *plainPart = NULL, *retBuf=NULL; char *leftOverBuf=NULL, *leftOverDecodedBuf=NULL; int plainTextLen = 0, leftOverLen=0; char achCharset[16]; BOOLEAN bEncodeBase64 = FALSE; BOOLEAN bEncodeQP = FALSE; BOOLEAN bEncodeString = FALSE; if ( szInputString == NULL ) return NULL; len = strlen( szInputString ); /* find start of encoding text */ for ( i = 0; i < len && szInputString[i] != 0 ; i++ ) { if ( szInputString[i] == '=' && szInputString[i+1] == '?' ) { bEncodeString = TRUE; break; } } if (bEncodeString == FALSE) return (strdup (szInputString)); if (i > 0) { plainTextLen = (i); plainPart = malloc (i+1); strncpy (plainPart, szInputString, plainTextLen); plainPart [i] = 0; } /* get charset */ for ( i += 2, j = 0; i < len && szInputString[i] != '?' && j < 15; i++, j++ ) { achCharset[j] = szInputString[i]; } achCharset[j] = 0; i++; /* skip ? */ /* get encoding type */ if ( szInputString[i] == 'Q' || szInputString[i] == 'q' ) bEncodeQP = TRUE; else if ( szInputString[i] == 'B' || szInputString[i] == 'b' ) bEncodeBase64 = TRUE; if (szInputString[i] == '?' ) i++; /* skip ? */ nStart = ++i; /* look for end of encoded text */ for ( j = 0; i < len && szInputString[i] != 0; i++, j++ ) { if ( szInputString[i] == '?' && (i+1) < len && szInputString[i+1] == '=' ) { nEnd = i; break; } } if ( nEnd > 0 ) { /* extract encoded text */ szEncodedText = (char *) malloc( j + 1 ); szDecodedText = (char *) malloc( j + 1 ); if ( szEncodedText != NULL && szDecodedText != NULL ) { strncpy( szEncodedText, &szInputString[nStart], j ); if ( bEncodeQP ) decodeQP( szEncodedText, szDecodedText, j ); else if ( bEncodeBase64 ) decodeBase64( szEncodedText, szDecodedText, j, j, &outBytes, &outBits ); free( szEncodedText ); } } if (nEnd+2 < len-1) { leftOverLen = len - (nEnd+2); leftOverBuf = malloc (leftOverLen + 1); strncpy (leftOverBuf, &szInputString[nEnd+2], leftOverLen); leftOverBuf [leftOverLen] = 0; leftOverDecodedBuf = decodeHeader (leftOverBuf); } retLen = plainTextLen + strlen (szDecodedText) + strlen (leftOverDecodedBuf); retBuf = malloc (retLen +1); if (plainPart != NULL && szDecodedText != NULL && leftOverDecodedBuf != NULL) { sprintf (retBuf, "%s%s%s", plainPart, szDecodedText, leftOverDecodedBuf); free (plainPart); free (szDecodedText); free (leftOverBuf); free (leftOverDecodedBuf); } else if (plainPart != NULL && szDecodedText != NULL) { sprintf (retBuf, "%s%s", plainPart, szDecodedText); free (plainPart); free (szDecodedText); } else if (szDecodedText != NULL && leftOverDecodedBuf != NULL) { sprintf (retBuf, "%s%s", szDecodedText, leftOverDecodedBuf); free (szDecodedText); free (leftOverBuf); free (leftOverDecodedBuf); } else if (szDecodedText != NULL) { free (retBuf); return szDecodedText; } else { free (retBuf); return null; } return retBuf; }
void createDictionary(Dictionary* myself, char* xml) { Tag* keyTag; Tag* valueTag; DictValue* curValue; DictValue* lastValue; curValue = NULL; lastValue = NULL; while(*xml != '\0') { keyTag = getNextTag(&xml); if(keyTag == NULL) { break; } if(strcmp(keyTag->name, "key") != 0) { releaseTag(keyTag); continue; } curValue = (DictValue*) malloc(sizeof(DictValue)); curValue->key = (char*) malloc(sizeof(char) * (strlen(keyTag->xml) + 1)); strcpy(curValue->key, keyTag->xml); curValue->next = NULL; releaseTag(keyTag); valueTag = getNextTag(&xml); if(valueTag == NULL) { break; } if(strcmp(valueTag->name, "dict") == 0) { curValue->type = DictionaryType; curValue = (DictValue*) realloc(curValue, sizeof(Dictionary)); createDictionary((Dictionary*) curValue, valueTag->xml); } else if(strcmp(valueTag->name, "string") == 0) { curValue->type = StringType; curValue = (DictValue*) realloc(curValue, sizeof(StringValue)); ((StringValue*)curValue)->value = (char*) malloc(sizeof(char) * (strlen(valueTag->xml) + 1)); strcpy(((StringValue*)curValue)->value, valueTag->xml); } else if(strcmp(valueTag->name, "data") == 0) { size_t len; curValue->type = StringType; curValue = (DictValue*) realloc(curValue, sizeof(DataValue)); ((DataValue*)curValue)->value = decodeBase64(valueTag->xml, &len); ((DataValue*)curValue)->len = len; } else if(strcmp(valueTag->name, "integer") == 0) { curValue->type = IntegerType; curValue = (DictValue*) realloc(curValue, sizeof(IntegerValue)); sscanf(valueTag->xml, "%d", &(((IntegerValue*)curValue)->value)); } else if(strcmp(valueTag->name, "array") == 0) { curValue->type = ArrayType; curValue = (DictValue*) realloc(curValue, sizeof(ArrayValue)); createArray((ArrayValue*) curValue, valueTag->xml); } else if(strcmp(valueTag->name, "true/") == 0) { curValue->type = BoolType; curValue = (DictValue*) realloc(curValue, sizeof(BoolValue)); ((BoolValue*)curValue)->value = TRUE; } else if(strcmp(valueTag->name, "false/") == 0) { curValue->type = BoolType; curValue = (DictValue*) realloc(curValue, sizeof(BoolValue)); ((BoolValue*)curValue)->value = FALSE; } curValue->prev = lastValue; if(lastValue == NULL) { myself->values = curValue; } else { lastValue->next = curValue; } lastValue = curValue; releaseTag(valueTag); } }
/** * load AIDE database from file * * filename base64(digest) * Return * num of meatdata * -1 ERROR * * caller * ir.c */ int loadAideDatabaseFile(AIDE_CONTEXT *ctx, char *filename) { gzFile fp; char buf[AIDE_SPEC_BUF_SIZE]; int items[AIDE_MAX_ITEM_NUM]; int item_num = 0; char *ptr; char *end; char *sep; AIDE_METADATA *md; int body = 0; int i; int is_null; int len; ENTRY e; // htable ENTRY *ep; int rc; char *sha1_b64_ptr; DEBUG_CAL("loadAideDatabaseFile - start, filename=[%s]\n", filename); /* check */ if (ctx == NULL) { LOG(LOG_ERR, "null input"); return -1; } if (filename == NULL) { LOG(LOG_ERR, "null input"); return -1; } fp = gzopen(filename, "r"); if (fp == NULL) { LOG(LOG_ERR, "%s missing\n", filename); return -1; } while (gzgets(fp, buf, sizeof(buf)) != NULL) { if (!strncmp(buf, "#", 1)) { } else if (!strncmp(buf, "@@begin_db", 10)) { body = 1; } else if (!strncmp(buf, "@@end_db", 8)) { body = 0; } else if (!strncmp(buf, "@@db_spec", 9)) { /* check item def */ ptr = &buf[10]; end = buf + strlen(buf); item_num = 0; /* loop */ while (ptr < end) { /* skip space */ while ((ptr < end) && (*ptr == 0x20)) { // skip ptr++; } /* find sep */ sep = strstr(ptr, " "); if (sep == NULL) { LOG(LOG_ERR, "bad data, %s\n", buf); return -1; } else { // terminate at " " *sep = 0; } /* get item code */ items[item_num] = getAideItemIndex(ptr); if (items[item_num] < 0) { LOG(LOG_ERR, "Bad spec\n"); return -1; } item_num++; if (sep + 3 > end) break; // TODO(munetoh) ptr = sep + 1; } body = 2; if (item_num > AIDE_MAX_ITEM_NUM) { LOG(LOG_ERR, "loadAideDatabaseFile - %d items > %d \n", item_num, AIDE_MAX_ITEM_NUM); return -1; } DEBUG("loadAideDatabaseFile - has %d items\n", item_num); } else if (body == 2) { /* DB items */ /* new MD */ md = newAideMetadata(); /* check item */ ptr = buf; end = buf + strlen(buf); sep = buf; // *end = 0; // TODO(munetoh) remove \n sha1_b64_ptr = NULL; /* loop */ for (i = 0; i < item_num; i++) { /* space -> \0 */ if (i != item_num - 1) { sep = strstr(ptr, " "); if (sep == NULL) { LOG(LOG_ERR, "bad data, %s\n", buf); freeAideMetadata(md); return -1; } else { *sep = 0; // set \0 } } /* check the null string*/ if (!strncmp(ptr, "0", strlen(ptr))) { is_null = 1; } else if (!strncmp(ptr, "0\n", strlen(ptr))) { is_null = 1; } else { is_null = 0; } switch (items[i]) { case AIDE_ITEM_NAME: // char if (!is_null) { md->name = smalloc_assert(ptr); } break; case AIDE_ITEM_LNAME: // char if (!is_null) { md->lname = smalloc_assert(ptr); } break; case AIDE_ITEM_ATTR: // int md->attr = atoi(ptr); break; case AIDE_ITEM_SHA1: // base64 if (!is_null) { sha1_b64_ptr = ptr; md->sha1 = decodeBase64( (char *)ptr, SHA1_BASE64_DIGEST_SIZE, &len); if (md->sha1 == NULL) { LOG(LOG_ERR, "decodeBase64 fail"); goto close; } if (len != SHA1_DIGEST_SIZE) { LOG(LOG_ERR, "bad SHA1 size %d %s\n", len, ptr); printHex("digest", md->sha1, len, "\n"); } } break; case AIDE_ITEM_SHA256: // base64 if (!is_null) { md->sha256 = decodeBase64( (char *)ptr, SHA256_BASE64_DIGEST_SIZE, &len); if (md->sha256 == NULL) { LOG(LOG_ERR, "decodeBase64 fail"); goto close; } if (len != SHA256_DIGEST_SIZE) { LOG(LOG_ERR, "bad SHA256 size %d\n", len); OUTPUT("base64 [%s] => [", ptr); printHex("", (BYTE *)ptr, 2, " "); OUTPUT("][\n"); printHex("", md->sha256, len, " "); OUTPUT("]\n"); } } break; case AIDE_ITEM_SHA512: // base64 if (!is_null) { md->sha512 = decodeBase64( (char *)ptr, SHA512_BASE64_DIGEST_SIZE, &len); if (md->sha512 == NULL) { LOG(LOG_ERR, "decodeBase64 fail"); goto close; } if (len != SHA512_DIGEST_SIZE) { LOG(LOG_ERR, "bad SHA512 size %d\n", len); OUTPUT("base64 [%s] => [", ptr); printHex("", (BYTE *)ptr, 2, ""); OUTPUT("][\n"); printHex("", md->sha512, len, ""); OUTPUT("]\n"); } } break; case AIDE_ITEM_XATTRS: // DEBUG("AIDE_ITEM_XATTRS\n"); break; default: // DEBUG("Unknown item[%d] %d\n", i, items[i]); break; } // switch ptr = sep + 1; } // for /* update ctx */ md->status = OPENPTS_AIDE_MD_STATUS_NEW; addAideMetadata(ctx, md); /* save to the hash table */ if (sha1_b64_ptr != NULL) { // TODO SHA1 only, add hash agility later /* alloc hash key */ sha1_b64_ptr[SHA1_BASE64_DIGEST_SIZE] = 0; // jXgiZyt0yUbP4QhAq9WFsLF/FL4= 28 md->hash_key = xmalloc(strlen(sha1_b64_ptr) +1); // TODO check NULL memcpy(md->hash_key, sha1_b64_ptr, strlen(sha1_b64_ptr) + 1); e.key = (char *)md->hash_key; e.data = (void *)md; rc = hsearch_r(e, ENTER, &ep, ctx->aide_md_table); if (rc == 0) { if (errno == ENOMEM) { LOG(LOG_ERR, " hsearch_r failed, table is full, errno=%x\n", errno); } else { LOG(LOG_ERR, " hsearch_r failed, errno=%x\n", errno); } } // CAUTION too many messages, use for debugging the unit test // DEBUG("Hash Table <- %4d [%s] %s\n", ctx->aide_md_table_size, md->hash_key, md->name); ctx->aide_md_table_size++; } #if 0 if (ctx->start == NULL) { ctx->start = md; ctx->end = md; } else { ctx->end->next = md; md->prev = ctx->end; ctx->end = md; } ctx->metadata_num++; #endif } else { // ignore } // if } // while close: gzclose(fp); DEBUG("loadAideDatabaseFile - has %d entries\n", ctx->metadata_num); DEBUG_CAL("loadAideDatabaseFile - done\n"); return ctx->metadata_num; }
/** * SAX parser - End of Element */ void irEndElement(void * context, const xmlChar * name) { IR_CONTEXT *ctx = (IR_CONTEXT *)context; int rc = 0; UINT32 padding = 0; int pad_len; if (!strcmp((char *)name, "stuff:Objects")) { /* Event finish, let's print out */ ctx->event_index++; /* set the event structure */ if (ctx->event == NULL) { LOG(LOG_ERR, "internal error\n"); ctx->sax_error++; } else { if (ctx->binary == 0) { /* text */ fprintf(ctx->fp, "%5d %2d 0x%08x ", ctx->event_index, ctx->event->ulPcrIndex, ctx->event->eventType); fprintHex(ctx->fp, ctx->event->rgbPcrValue, 20); fprintf(ctx->fp, " ["); fprintEventData(ctx->fp, ctx->event->eventType, ctx->event->ulEventLength, ctx->event->rgbEvent); fprintf(ctx->fp, "]\n"); } else { /* binary */ if (ctx->endian == 0) { // TODO check rc rc = fwrite((BYTE *)&ctx->event->ulPcrIndex, 1, 4, ctx->fp); // PCR index rc = fwrite((BYTE *)&ctx->event->eventType, 1, 4, ctx->fp); // Event type rc = fwrite(ctx->event->rgbPcrValue, 1, 20, ctx->fp); // PCR rc = fwrite((BYTE *)&ctx->event->ulEventLength, 1, 4, ctx->fp); // EventData length rc = fwrite(ctx->event->rgbEvent, 1, ctx->event->ulEventLength, ctx->fp); // EventData } else { /* convert endian */ // TODO used htonl() UINT32 u; u = econv(ctx->event->ulPcrIndex); rc = fwrite((BYTE *)&u, 1, 4, ctx->fp); // PCR index u = econv(ctx->event->eventType); rc = fwrite((BYTE *)&u, 1, 4, ctx->fp); // Event type rc = fwrite(ctx->event->rgbPcrValue, 1, 20, ctx->fp); // PCR u = econv(ctx->event->ulEventLength); rc = fwrite((BYTE *)&u, 1, 4, ctx->fp); // EventData length rc = fwrite(ctx->event->rgbEvent, 1, ctx->event->ulEventLength, ctx->fp); // EventData } /* padding */ if (ctx->aligned > 0) { // TODO base64 IR already contains padding? // DEBUG("padding\n"); pad_len = ctx->event->ulEventLength % ctx->aligned; if (pad_len > 0) { /* add padding */ rc = fwrite((BYTE *)&padding, 1, pad_len, ctx->fp); // Padding LOG(LOG_TODO, "%d mod %d => %d\n", ctx->event->ulEventLength, ctx->aligned, pad_len); } } } /* extend to eTPM */ extend( ctx->event->ulPcrIndex, ctx->event->rgbPcrValue); ctx->event = NULL; } } else if (!strcmp((char *)name, "SnapshotCollection")) { /* snapshot finish */ } else if (!strcmp((char *)name, "pcrindex")) { ctx->buf[ctx->char_size] = 0; ctx->event->ulPcrIndex = atoi(ctx->buf); } else if (!strcmp((char *)name, "stuff:Hash")) { ctx->buf[ctx->char_size] = 0; ctx->event->rgbPcrValue = decodeBase64( (char *)ctx->buf, ctx->char_size, (int *)&ctx->event->ulPcrValueLength); if (ctx->event->rgbEvent == NULL) { // LOG(LOG_ERR, ) ctx->event->ulPcrValueLength = 0; } } else if (!strcmp((char *)name, "eventtype")) { ctx->buf[ctx->char_size] = 0; ctx->event->eventType = atoi(ctx->buf); } else if (!strcmp((char *)name, "eventdata")) { ctx->buf[ctx->char_size] = 0; // null terminate ctx->event->rgbEvent = decodeBase64( (char *)ctx->buf, ctx->char_size, (int *)&ctx->event->ulEventLength); if (ctx->event->rgbEvent == NULL) { // LOG(LOG_ERR, ) ctx->event->ulEventLength = 0; } } else if (!strcmp((char *)name, "PcrHash")) { /* PCR value */ ctx->buf[ctx->char_size] = 0; // null terminate // decodeBase64(ctx->pcr, (unsigned char *)ctx->buf, ctx->char_size); /* Check with PCR in TPM */ // rc = checkTpmPcr2(&pctx->tpm, ctx->pcr_index, ctx->pcr); if (rc != 0) { LOG(LOG_ERR, "ERROR PCR[%d] != IML\n", ctx->pcr_index); ctx->sax_error = 1; } else { /* IML and PCR are consistent :-) */ // DEBUG_FSM("PCR[%d] == IML\n", ctx->pcr_index); // TODO(munetoh) add property? tpm.pcr.N.snapshot.N.integrity=valid #if 0 /* update pcrs, used by validatePcrCompositeV11 */ if (pctx->conf->iml_mode == 0) { if (pcrs == NULL) { /* malloc OPENPTS_PCRS */ // LOG(LOG_ERR, "PCR is not intialized - No QuoteData element\n"); pcrs = xmalloc(sizeof(OPENPTS_PCRS)); if (pcrs == NULL) { return; } memset(pcrs, 0, sizeof(OPENPTS_PCRS)); pctx->pcrs = pcrs; } pcrs->pcr_select[ctx->pcr_index] = 1; memcpy(pcrs->pcr[ctx->pcr_index], ctx->pcr, 20); // TODO pcr size } else { // DEBUG("iml.mode!=tss, skip pcr copy to PCRS\n"); } #endif } } else if (!strcmp((char *)name, "ValueSize")) { DEBUG("ignore ValueSize\n"); } else if (!strcmp((char *)name, "PcrValue")) { DEBUG("ignore PcrValue\n"); } else if (!strcmp((char *)name, "SignatureValue")) { DEBUG("ignore SignatureValue\n"); } else if (!strcmp((char *)name, "KeyValue")) { DEBUG("ignore KeyValue\n"); } else if (!strcmp((char *)name, "QuoteData")) { DEBUG("ignore QuoteData\n"); } else { /* Else? */ DEBUG("END ELEMENT [%s] ", name); } ctx->sax_state = IR_SAX_STATE_IDOL; }