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;
}
// Encode any sufficiently trivial object to Base64.
template <typename T> std::string encodeBase64Bytewise(const T &x)
{
#if not defined __GNUC__ or __GNUC__ > 4
    static_assert(std::is_trivially_copyable<T>::value, "requires a trivially copyable type");
#endif

    return encodeBase64(reinterpret_cast<const unsigned char *>(&x), sizeof(T));
}
Esempio n. 3
0
util::json::Object
ApiResponseGenerator<DataFacadeT>::BuildHintData(const InternalRouteResult &raw_route) const
{
    util::json::Object json_hint_object;
    json_hint_object.values["checksum"] = facade->GetCheckSum();
    util::json::Array json_location_hint_array;
    std::string hint;
    for (const auto i : util::irange<std::size_t>(0, raw_route.segment_end_coordinates.size()))
    {
        hint = encodeBase64(raw_route.segment_end_coordinates[i].source_phantom);
        json_location_hint_array.values.push_back(std::move(hint));
    }
    hint = encodeBase64(raw_route.segment_end_coordinates.back().target_phantom);
    json_location_hint_array.values.emplace_back(std::move(hint));
    json_hint_object.values["locations"] = json_location_hint_array;

    return json_hint_object;
}
Esempio n. 4
0
int FLDigiDoc::dataDigest(const QByteArray &data, QByteArray &digestResult)
{
  int sigLen = SIGNATURE_LEN;
  byte buf[sigLen * sizeof(char)];
  byte buf1[sigLen * sizeof(char) * 2];
  int err = calculateDigest((const byte *)data.data(), data.size() * sizeof(char),
                            DIGEST_SHA1, buf, &sigLen);
  digestResult = encodeBase64(buf, sigLen);
  return err;
}
Esempio n. 5
0
int FLDigiDoc::verifySignatureFile(const QString &fileName, QByteArray &signResult,
                                   const QString &certfile)
{
  int sigLen = SIGNATURE_LEN;
  byte buf[sigLen * sizeof(char)];
  byte buf1[sigLen * sizeof(char) * 2];
  int err = verifyFileSignature(fileName.latin1(), DIGEST_SHA1, buf, sigLen,
                                certfile.latin1());
  signResult = encodeBase64(buf, sigLen);
  return err;
}
Esempio n. 6
0
int FLDigiDoc::dataSignature(const QByteArray &data, QByteArray &signResult,
                             const QString &keyfile, const QString &passwd)
{
  int sigLen = SIGNATURE_LEN;
  byte buf[sigLen * sizeof(char)];
  byte buf1[sigLen * sizeof(char) * 2];
  int err = signData((const byte *)data.data(), data.size() * sizeof(char), buf,
                     &sigLen, DIGEST_SHA1, keyfile.latin1(), passwd.latin1());
  signResult = encodeBase64(buf, sigLen);
  return err;
}
Esempio n. 7
0
int FLDigiDoc::fileSignature(const QString &fileName, QByteArray &signResult,
                             const QString &keyfile, const QString &passwd)
{
  int sigLen = SIGNATURE_LEN;
  byte buf[sigLen * sizeof(char)];
  byte buf1[sigLen * sizeof(char) * 2];
  int err = calculateFileSignature(fileName.latin1(), DIGEST_SHA1, buf, &sigLen,
                                   keyfile.latin1(), passwd.latin1());
  signResult = encodeBase64(buf, sigLen);
  return err;
}
Esempio n. 8
0
int FLDigiDoc::fileDigest(const QString &fileName, QByteArray &digestResult)
{
  int sigLen = SIGNATURE_LEN;
  long fileLen;
  byte buf[sigLen * sizeof(char)];
  byte buf1[sigLen * sizeof(char) * 2];
  int err = calculateFileDigest(fileName.latin1(), DIGEST_SHA1, buf,
                                &sigLen, &fileLen);
  digestResult = encodeBase64(buf, sigLen);
  return err;
}
Esempio n. 9
0
void XMLWriter::setContents(Common::SeekableReadStream &stream) {
	if (_openTags.empty())
		return;

	Tag &tag = _openTags.back();

	tag.base64.clear();
	tag.contents.clear();

	encodeBase64(tag.base64, stream);

	tag.empty = false;
}
Esempio n. 10
0
void XMLWriter::setContents(const byte *data, uint32 size) {
	if (_openTags.empty())
		return;

	Tag &tag = _openTags.back();

	tag.base64.clear();
	tag.contents.clear();

	Common::MemoryReadStream stream(data, size);
	encodeBase64(tag.base64, stream);

	tag.empty = false;
}
Esempio n. 11
0
Tmysql_LiveRow YaeMaster_Database::authenticate(std::string login, std::string password)
{
	Tmysql_Connection& sql = Tmysql_Connection::getInstance("dawn");
	//md5(base64_encode('***REMOVED***'.sha1( strrev($password).'***REMOVED***' ).'***REMOVED***').'***REMOVED***')
	//@todo: password encode
	reverse(password.begin(),password.end());
	password = password + "***REMOVED***";
	Tmysql_Arguments args = {password};
	Tmysql_Row row = sql.fetchRow("SELECT SHA1(?) AS p", args);
	password = row["p"];
	password = encodeBase64("***REMOVED***" + password + "***REMOVED***") + "***REMOVED***";
	Tmysql_Arguments args2 = {login,password};
	return sql.fetchLiveRow("users", "WHERE username=? AND password=MD5(?)", args2);
}
Esempio n. 12
0
int FLDigiDoc::verifySignatureData(const QByteArray &data, QByteArray &signResult,
                                   const QString &certfile)
{
  X509 *pCert = 0;
  int err = ReadCertificate(&pCert, certfile.latin1());
  if (!err && pCert) {
    int sigLen = SIGNATURE_LEN;
    byte buf[sigLen * sizeof(char)];
    byte buf1[sigLen * sizeof(char) * 2];
    err = verifySignature((const char *)data, data.size() * sizeof(char),
                          DIGEST_SHA1, buf, sigLen, pCert);
    signResult = encodeBase64(buf, SIGNATURE_LEN);
  }
  if (pCert) {
    X509_free(pCert);
    pCert = 0;
  }
  return err;
}
Esempio n. 13
0
VARIANT CMUSHclientDoc::Base64Encode(LPCTSTR Text, BOOL MultiLine) 
{
	VARIANT vaResult;
	VariantInit(&vaResult);
  CString strResult;

  try 
    {
    strResult = encodeBase64 (Text, MultiLine);
    }   // 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::Base64Encode
/*!
 * \brief   l_genDataString()
 *
 * \param[in]    filein input file of serialized data
 * \param[in]    ifunc index into set of functions in output file
 * \return  encoded ascii data string, or NULL on error reading from file
 */
static char *
l_genDataString(const char  *filein,
                l_int32      ifunc)
{
char      buf[80];
char     *cdata1, *cdata2, *cdata3;
l_uint8  *data1, *data2;
l_int32   csize1, csize2;
size_t    size1, size2;
SARRAY   *sa;

    PROCNAME("l_genDataString");

    if (!filein)
        return (char *)ERROR_PTR("filein not defined", procName, NULL);

        /* Read it in, gzip it, encode, and reformat.  We gzip because some
         * serialized data has a significant amount of ascii content. */
    if ((data1 = l_binaryRead(filein, &size1)) == NULL)
        return (char *)ERROR_PTR("bindata not returned", procName, NULL);
    data2 = zlibCompress(data1, size1, &size2);
    cdata1 = encodeBase64(data2, size2, &csize1);
    cdata2 = reformatPacked64(cdata1, csize1, 4, 72, 1, &csize2);
    LEPT_FREE(data1);
    LEPT_FREE(data2);
    LEPT_FREE(cdata1);

        /* Prepend the string declaration signature and put it together */
    sa = sarrayCreate(3);
    snprintf(buf, sizeof(buf), "static const char *l_strdata_%d =\n", ifunc);
    sarrayAddString(sa, buf, L_COPY);
    sarrayAddString(sa, cdata2, L_INSERT);
    sarrayAddString(sa, (char *)";\n", L_COPY);
    cdata3 = sarrayToString(sa, 0);
    sarrayDestroy(&sa);
    return cdata3;
}
Esempio n. 15
0
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);
}
Esempio n. 16
0
/* LINE SENDER  */
void Smtp::putSendLine()
{
    int current = linesend;
    switch(current)
    {
    case 1:
        response = sendLineAndGrab("ehlo " + smtphost);
        if (response.size() > 0)
        {
            errorMSG.append(response);
            linesend = 2;
            emit sendLine();
        }
        response ="";
        break;
    case 2:
        response = sendLineAndGrab("AUTH LOGIN");
        if (response.size() >=0)
        {
            errorMSG.append(response);
            linesend = 3;
            emit sendLine();
        }

        response ="";

        break;
    case 3:
        response = sendLineAndGrab(encodeBase64(smtpusername));   /* username send */
        if (response.size() > 0)
        {
            errorMSG.append(response);
            linesend = 4;
            emit sendLine();
        }

        response ="";
        break;
    case 4:
        response = sendLineAndGrab(encodeBase64(smtppass));     /* pass send */
        qDebug() << "4---- " << response;
        if (response.size() > 0)
        {
            errorMSG.append(response);
            if (response.contains("235", Qt::CaseInsensitive))
            {
                linesend = 5;
                emit sendLine();
            }

        }

        response ="";
        break;
    case 5:
        response = sendLineAndGrab("MAIL FROM:<"+from+">");
        if (response.size() > 0)
        {
            linesend = 6;
            emit sendLine();
        }

        break;
    case 6:
        response = sendLineAndGrab("RCPT TO: <"+rcpt+">");
        if (response.size() > 0)
        {
            errorMSG.append(response);
            response ="";
            response = sendLineAndGrab("DATA");
            if (!response.contains("not", Qt::CaseInsensitive))
            {
                errorMSG.append(response);
                response ="";
                linesend = 7;
                emit sendLine();
            }
        }
        response ="";
        break;
    case 7:
        response = sendLineAndGrab(message+"\r\n.");

        if (response.size() && response.contains("ok", Qt::CaseInsensitive) )
        {
            errorMSG.append(response);
            linesend = 8;
            emit sendLine();
        }
        response ="";
        break;
    case 8:
        sendLineAndGrab("QUIT");
        break;
    default:
        /*emit ErrorCloseAll();*/
        return;
        break;
    }
}
// Overload for char catches (not only but also) C-string literals.
inline std::string encodeBase64(const char *first, std::size_t size)
{
    return encodeBase64(reinterpret_cast<const unsigned char *>(first), size);
}
// Convenience specialization, encoding from string instead of byte-dumping it.
inline std::string encodeBase64(const std::string &x) { return encodeBase64(x.data(), x.size()); }
Esempio n. 19
0
/**
 * reduce the size of AIDE DB
 *
 *                     reduced
 *  AIDE-DB  IMA-IML   AIDE-DB
 *  --------------------------
 *     O        O         O
 *     O        -         -
 *     -        O         -
 *     -        -         -
 *  --------------------------
 *
 *
 * return AIDE entry count
 *
 */
int writeReducedAidbDatabase(AIDE_CONTEXT *ctx, char *filename) {
    gzFile fp;
    AIDE_METADATA *md;
    int i;
    int cnt = 0;
    char *buf;
    int buf_len;

    DEBUG("writeReducedAidbDatabase %s\n", filename);

    /* check */
    if (ctx == NULL) {
        LOG(LOG_ERR, "null input");
        return -1;
    }
    if (filename == NULL) {
        LOG(LOG_ERR, "null input");
        return -1;
    }

    /* file open for write */
    fp = gzopen(filename, "wb");
    if (fp == NULL) {
        LOG(LOG_ERR, "%s fail to open\n", filename);
        return -1;
    }

    /* Header */
    gzprintf(fp, "@@begin_db\n");
    gzprintf(fp, "# This file was generated by OpenPTS\n");
    gzprintf(fp, "@@db_spec name sha1 \n");

    /* scan */
    md = ctx->start;

    for (i = 0; i < ctx->metadata_num; i++) {
        if (md == NULL) {
            return -1;
        }

        if (md->status == OPENPTS_AIDE_MD_STATUS_HIT) {
            buf = encodeBase64(
                (unsigned char *)md->sha1,
                SHA1_DIGEST_SIZE,
                &buf_len);
            if (buf == NULL) {
                LOG(LOG_ERR, "encodeBase64 fail");
                return -1;
            }
            gzprintf(fp, "%s ", md->name);
            gzprintf(fp, "%s \n", buf);
            xfree(buf);
            cnt++;
        }

        md = md->next;
    }

    /* Footer */
    gzprintf(fp, "@@end_db\n");

    /* file close */
    gzseek(fp, 1L, SEEK_CUR);  // add one \n
    gzclose(fp);

    DEBUG("convertImlToAideDbFile - done\n");


    return cnt;
}
Esempio n. 20
0
/**
 * Convert IML TSS/file(ptscd.conf) to AIDE DB
 *
 * ctx       get the IML before call this func
 * filename  output AIDE DB filename
 *
 * TODO(munetoh) IMA_31 only 
 */
int convertImlToAideDbFile(OPENPTS_CONTEXT *ctx, char *filename) {
    gzFile fp;
    int i = 0;
    OPENPTS_SNAPSHOT *ss;
    OPENPTS_PCR_EVENT_WRAPPER *eventWrapper;
    TSS_PCR_EVENT *event;
    char *buf;
    int buf_len;
    char *aide_filename = NULL;
    int len;

    DEBUG_CAL("convertImlToAideDbFile %s\n", filename);

    /* check */
    if (ctx == NULL) {
        LOG(LOG_ERR, "null input");
        return -1;
    }
    if (filename == NULL) {
        LOG(LOG_ERR, "null input");
        return -1;
    }

    /* file open for write */
    fp = gzopen(filename, "wb");
    if (fp == NULL) {
        LOG(LOG_ERR, "%s fail to open\n", filename);
        return -1;
    }

    /* Header */
    gzprintf(fp, "@@begin_db\n");
    gzprintf(fp, "# This file was generated by OpenPTS\n");
    gzprintf(fp, "@@db_spec name sha1 \n");

    /* IMLs */
    ss = getSnapshotFromTable(ctx->ss_table, 10, 1);  // TODO def or conf
    if (ss == NULL) {
        LOG(LOG_ERR, "events is missing\n");
        goto close;
    }
    eventWrapper = ss->start;
    if (eventWrapper == NULL) {
        LOG(LOG_ERR, "events is missing\n");
        goto close;
    }

    event = eventWrapper->event;

    // DEBUG("PCR[%d]\n", ss->pcrIndex);
    // DEBUG("event_num %d\n", ss->event_num);

    // for (i = 0; i < ctx->eventNum; i++) {
    for (i = 0; i < ctx->ss_table->event_num; i++) {  // TODO ss->event_num?
        // DEBUG("SM DEBUG event %p\n",event);

        if (event == NULL) {
            LOG(LOG_ERR, "event is NULL\n");
            goto close;
        }

        if (event->rgbEvent == NULL) {
            LOG(LOG_ERR, "event->rgbEvent is NULL\n");
            goto close;
        }

        // TODO 2010-10-05 SM
        // AIDE convert the following chars in filename
        // SPACE 0x20  ->  "%20"
        // @     0x40  ->  "%40"
        // [ "%5B"
        // ] "%5D"
        // % "%25"
        // : "%3A"
        // { "%7B"
        // } "%7D"
        // ~ "%7E"

        // gzprintf(fp, "%s ",&eventWrapper->event->rgbEvent[20]);

        /* filename (allocated) */
        len = escapeFilename(&aide_filename, (char *) &eventWrapper->event->rgbEvent[20]);
        if (len < 0) {
            LOG(LOG_ERR, "convertImlToAideDbFile - no mem?\n");
            gzprintf(fp, "bad_filename ");
        } else {
            gzprintf(fp, "%s ", aide_filename);
            xfree(aide_filename);
            aide_filename = NULL;
        }

        /* digest */
        buf = encodeBase64(
            (unsigned char *)event->rgbEvent,
            SHA1_DIGEST_SIZE,
            &buf_len);
        if (buf == NULL) {
            LOG(LOG_ERR, "encodeBase64 fail");
            goto close;
        }
        gzprintf(fp, "%s \n", buf);
        xfree(buf);

        eventWrapper = eventWrapper->next_pcr;
        if (eventWrapper == NULL) break;
        event = eventWrapper->event;
    }

    /* Footer */
    gzprintf(fp, "@@end_db\n");

    /* file close */
    gzseek(fp, 1L, SEEK_CUR);  // add one \n
  close:
    gzclose(fp);
    if (aide_filename != NULL) xfree(aide_filename);

    DEBUG("convertImlToAideDbFile - done\n");

    return i+1;  // event num
}
Esempio n. 21
0
/**
 * check Eventlog with AIDE DB
 *
 * IMA
 * event->rgbEvent[0] - [20] <= SHA1 digest of the File
 *
 * Return
 *   -1: ERROR
 *    0: HIT
 *    1: IGNORE
 *    2: MISS
 *
 * skip this check 33sec -> 2sec
 * 
 */
int checkEventByAide(AIDE_CONTEXT *ctx, OPENPTS_PCR_EVENT_WRAPPER *eventWrapper) {
    TSS_PCR_EVENT *event;
    char *name;
    int rc = 0;
    char *buf;
    int buf_len;
#ifdef CONFIG_SQLITE
#else
    AIDE_METADATA *md;
#if AIDE_CHBY_LIST
    int i;
#else
    ENTRY e;
    ENTRY *ep;
#endif  //  AIDE_CHBY_LIST
#endif  //  CONFIG_SQLITE

    // DEBUG("checkEventByAide - start\n");

    if (ctx == NULL) {
        LOG(LOG_ERR, "checkEventByAide - AIDE_CONTEXT is NULL\n");
        return -1;
    }

    if (eventWrapper == NULL) {
        LOG(LOG_ERR, "OcheckEventByAide - PENPTS_PCR_EVENT_WRAPPER is NULL\n");
        return -1;
    }

    event = eventWrapper->event;

    // 20100627 ignore pseudo event
    if (event->eventType == OPENPTS_PSEUDO_EVENT_TYPE) {
        LOG(LOG_ERR, "validateImaMeasurement - event->eventType == OPENPTS_PSEUDO_EVENT_TYPE\n");
        return 1;
    }

    if (event->rgbEvent == NULL) {
        DEBUG("no event\n");
        return -1;
    }

    if (event->ulPcrValueLength != SHA1_DIGEST_SIZE) {
        DEBUG("bad digest size\n");
        return -1;
    }

    /* OK, let's find the HIT */
#ifdef CONFIG_SQLITE
    /* base64 */
    buf = encodeBase64(
            event->rgbEvent,
            20
            &buf_len);
    if (buf == NULL) {
        LOG(LOG_ERR, "encodeBase64 fail");
        return -1;
    }
    rc = verifyBySQLite(ctx, (char*)buf);
    xfree(buf);

    if (rc == OPENPTS_RESULT_VALID) {
        /* hit */
        // md = (AIDE_METADATA *) ep->data;
        // DEBUG_FSM("checkFileByAide - HIT name=[%s]\n", md->name);
        // md->status = OPENPTS_AIDE_MD_STATUS_HIT;
        // md->event_wrapper = eventWrapper;  // n:1
        // eventWrapper->aide_metadata = md;  // 1:n
        // this output many lines:-P
        // DEBUG("HIT  [%s] \n",b64);
        return 0;
    }
#else  // CONFIG_SQLITE
#if AIDE_CHBY_LIST
    md = ctx->start;

    for (i = 0; i < ctx->metadata_num; i++) {
        if (md == NULL) {
            DEBUG("AIDE MeataData is NULL\n");
            return -1;
        }

        if (md->sha1 != NULL) {
            if (memcmp(event->rgbEvent, md->sha1, SHA1_DIGEST_SIZE) == 0) {
                /* hit */
                DEBUG_FSM("checkFileByAide - HIT name=[%s]\n", md->name);
                md->status = OPENPTS_AIDE_MD_STATUS_HIT;
                md->event_wrapper = eventWrapper;  // n:1
                eventWrapper->aide_metadata = md;  // 1:n
                // copyAideMetadata(metadata, md);
                return 0;
            }
        }
        md = md->next;
    }
    DEBUG_FSM("checkFileByAide - MISS\n");
#else  // hashtable

    buf = encodeBase64(
            event->rgbEvent,
            20,
            &buf_len);
    if (buf == NULL) {
        LOG(LOG_ERR, "encodeBase64 fail");
        return -1;
    }
    e.key = (char *) buf;  // size?
    e.data = NULL;  // just initialized for static analysys

    // before (list)
    //   real  0m36.896s
    //   user  0m33.913s
    //
    // after (hash) BINARY
    //   real  0m33.002s
    //   user  0m30.093s
    //
    // after (hash) BASE64 :-(
    //   real  0m39.148s
    //   user  0m36.529s
    //
    // skip
    //   real  0m2.506s
    //   user  0m0.109s

    rc = hsearch_r(e, FIND, &ep, ctx->aide_md_table);
    if (rc != 0) {
        /* hit */
        // DEBUG("MD HIT\n");
        md = (AIDE_METADATA *) ep->data;
        DEBUG_FSM("checkFileByAide - HIT name=[%s]\n", md->name);
        md->status = OPENPTS_AIDE_MD_STATUS_HIT;
        md->event_wrapper = eventWrapper;  // n:1
        eventWrapper->aide_metadata = md;  // 1:n
        // DEBUG("HIT  [%s] %s\n",b64, md->name);
        return 0;
    } else {
        // DEBUG("MISS [%s] MISS\n",b64);
    }

#endif
#endif  // CONFIG_SQLITE

    /* check ignore list */

    // TODO(munetoh)
    name = (char *)event->rgbEvent;
    name += SHA1_DIGEST_SIZE;
    /* add '\n' */
    name = snmalloc(name, (event->ulEventLength - SHA1_DIGEST_SIZE));

#if 1
    rc = checkIgnoreList(ctx, name);
    if (rc == 0) {
        // HIT
        xfree(name);
        return 1;  // IGNORE
    }

    xfree(name);
    return 2;
#else
    xfree(name);
    return 1;  // force
#endif
}
Esempio n. 22
0
QByteArray FLDigiDoc::encodeBase64(const QByteArray &data) const
{
  return encodeBase64((const byte *)data.data(), data.size());
}
Esempio n. 23
0
void SMTP_Connection::on_read()
{
    if( !sock->canReadLine() )
        return;

    QString responseLine;

    do {
            responseLine = sock->readLine();
            response += responseLine;
        } while( sock->canReadLine() && responseLine[3] != ' ' );
    emit serverResponse(responseLine);
    responseLine.truncate( 3 );

    if ( state == Init && responseLine[0] == '2' )
        {

            *t << "HELO there\r\n";
            t->flush();
            state = Start;
        }
    else if (state == Start && responseLine[0] == '2')
        {
            *t << "AUTH LOGIN\r\n";
            t->flush();
            state = Login;
        }
    else if (state == Login && responseLine[0] == '3')
        {
            *t << encodeBase64(p_login) << "\r\n";
            t->flush();
            state = Pass;
        }
    else if (state == Pass && responseLine[0] == '3')
        {
            *t << encodeBase64(p_password) << "\r\n";
            t->flush();
            state = Mail;
        }
    else if ( state == Mail && responseLine[0] == '2' )
        {

            *t << "MAIL FROM: <" << p_mail_From << ">\r\n";
            t->flush();
            state = Rcpt;
        }
    else if ( state == Rcpt && responseLine[0] == '2' )
        {

            *t << "RCPT TO: <" << p_mail_to << ">\r\n";
            t->flush();
            state = Data;
        }
    else if ( state == Data && responseLine[0] == '2' )
        {
            *t << "DATA\r\n";
            t->flush();
            state = Body;
        }
    else if ( state == Body && responseLine[0] == '3' )
        {
            QString body;
            body = p_body;
            QString subject;
            subject = p_subject;
            message = QString::fromLatin1( "From: " ) + p_mail_From
                      +QString::fromLatin1( "\nTo: " ) + p_mail_to +QString::fromLatin1( "\nSubject: "
                                                                                                       ) + subject +QString::fromLatin1( "\n\n" ) + body +"\n";
            message.replace( QString::fromLatin1( "\n" ), QString::fromLatin1(
                    "\r\n" ) );
            message.replace( QString::fromLatin1( "\r\n.\r\n" ),
                             QString::fromLatin1( "\r\n..\r\n" ) );

            *t << message << "\n" << ".\r\n";
            t->flush();
            state = Quit;
        }
    else if ( state == Quit && responseLine[0] == '2' )
        {
            *t << "QUIT\r\n";
            state = Close;
            emit status( tr( "Message sent" ) );
        }
    else if ( state == Close )
        {

        }
    else
        {
            emit status(tr("Неизвестный ответ от сервера"));
            state = Close;
        }
    response = "";
}
void ARTSPConnection::addAuthentication(AString *request) {
    if (mAuthType == NONE) {
        return;
    }

    // Find the boundary between headers and the body.
    ssize_t i = request->find("\r\n\r\n");
    CHECK_GE(i, 0);

    if (mAuthType == BASIC) {
        AString tmp;
        tmp.append(mUser);
        tmp.append(":");
        tmp.append(mPass);

        AString out;
        encodeBase64(tmp.c_str(), tmp.size(), &out);

        AString fragment;
        fragment.append("Authorization: Basic ");
        fragment.append(out);
        fragment.append("\r\n");

        request->insert(fragment, i + 2);

        return;
    }

#if defined(HAVE_ANDROID_OS)
    CHECK_EQ((int)mAuthType, (int)DIGEST);

    AString method, url;
    GetMethodAndURL(*request, &method, &url);

    AString A1;
    A1.append(mUser);
    A1.append(":");
    A1.append("Streaming Server");
    A1.append(":");
    A1.append(mPass);

    AString A2;
    A2.append(method);
    A2.append(":");
    A2.append(url);

    AString HA1, HA2;
    H(A1, &HA1);
    H(A2, &HA2);

    AString tmp;
    tmp.append(HA1);
    tmp.append(":");
    tmp.append(mNonce);
    tmp.append(":");
    tmp.append(HA2);

    AString digest;
    H(tmp, &digest);

    AString fragment;
    fragment.append("Authorization: Digest ");
    fragment.append("nonce=\"");
    fragment.append(mNonce);
    fragment.append("\", ");
    fragment.append("username=\"");
    fragment.append(mUser);
    fragment.append("\", ");
    fragment.append("uri=\"");
    fragment.append(url);
    fragment.append("\", ");
    fragment.append("response=\"");
    fragment.append(digest);
    fragment.append("\"");
    fragment.append("\r\n");

    request->insert(fragment, i + 2);
#endif
}
Esempio n. 25
0
QByteArray MIMECodec::CramMd5Digest
(
  const QCString &username,
  const QCString &password,
  const QCString &challenge
)
{
  md5_byte_t *key   = new md5_byte_t[password.length()];
  md5_byte_t *text  = new md5_byte_t[challenge.length()];

  memcpy(key,   password.data(),  password.length());
  memcpy(text,  challenge.data(), challenge.length());

  int key_len   = password.length();
  int text_len  = challenge.length();

  // The rest of this is basically verbatim from rfc2104, with slight
  // adjustments for the md5 implementation I'm using and for for POSIX.

  md5_state_t context;

  md5_byte_t k_ipad[65];    // Inner padding - key XORd with ipad.
  md5_byte_t k_opad[65];    // Outer padding - key XORd with opad.
  md5_byte_t tk[16];

  int i;

  // If key is longer than 64 bytes, reset it to key=MD5(key).

  if (key_len > 64) {
    md5_state_t tctx;

    md5_init(&tctx);
    md5_append(&tctx, key, key_len);
    md5_finish(&tctx, tk);

    key = tk;
    key_len = 16;
  }

  /*
   * the HMAC_MD5 transform looks like:
   *
   * MD5(K XOR opad, MD5(K XOR ipad, text))
   *
   * where K is an n byte key
   * ipad is the byte 0x36 repeated 64 times
   * opad is the byte 0x5c repeated 64 times
   * and text is the data being protected
   */

  // Start out by storing key in pads.

  memset(k_ipad, 0, sizeof(k_ipad));
  memset(k_opad, 0, sizeof(k_opad));

  memcpy(k_ipad, key, key_len);
  memcpy(k_opad, key, key_len);

  // XOR key with ipad and opad values.

  for (i = 0; i < 64; i++) {
    k_ipad[i] ^= 0x36;
    k_opad[i] ^= 0x5c;
  }

  md5_byte_t digest[16];

  // Perform inner MD5.

  md5_init(&context);                   // Init context for 1st pass.
  md5_append(&context, k_ipad, 64);     // Start with inner pad.
  md5_append(&context, text, text_len);   // Then text of datagram.
  md5_finish(&context, digest);         // Finish up 1st pass.

  // Perform outer MD5.

  md5_init(&context);                   // Init context for 2nd pass.
  md5_append(&context, k_opad, 64);     // Start with outer pad.
  md5_append(&context, digest, 16);     // Then results of 1st hash.
  md5_finish(&context, digest);         // Finish up 2nd pass.

  delete [] text;
  delete [] key;

  char hexDigest[33];

  ::sprintf
  (
    hexDigest,
    "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
    digest[0],
    digest[1],
    digest[2],
    digest[3],
    digest[4],
    digest[5],
    digest[6],
    digest[7],
    digest[8],
    digest[9],
    digest[10],
    digest[11],
    digest[12],
    digest[13],
    digest[14],
    digest[15]
  );

  QCString toEncode = username + " " + QCString(hexDigest);

  QByteArray encoded = encodeBase64(toEncode, false);

  return encoded;
}