当前位置: 首页>>代码示例>>C++>>正文


C++ MD5Init函数代码示例

本文整理汇总了C++中MD5Init函数的典型用法代码示例。如果您正苦于以下问题:C++ MD5Init函数的具体用法?C++ MD5Init怎么用?C++ MD5Init使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了MD5Init函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: main

/*********************************************************************
 *
 *         Main Bacula Tray Monitor -- User Interface Program
 *
 */
int main(int argc, char *argv[])
{
   int ch;
   DIRRES s_dird;
   CLIENT s_filed;
   STORE s_stored;

   char host[250];
   char daemon[20];
   char monitorname[100];
   char pw[200];
   int port = 0;

   char answer[1024];
   int retcode = STATE_UNKNOWN;

   unsigned int i, j;
   struct MD5Context md5c;
   unsigned char signature[16];


   struct sigaction sigignore;
   sigignore.sa_flags = 0;
   sigignore.sa_handler = SIG_IGN;
   sigfillset(&sigignore.sa_mask);
   sigaction(SIGPIPE, &sigignore, NULL);

   strcpy (pw, "");

   init_stack_dump();
   my_name_is(argc, argv, "check_bacula");
   textdomain("bacula");
   init_msg(NULL, NULL);

   while ((ch = getopt(argc, argv, "H:D:M:P:K:d:h?")) != -1) {

      switch (ch) {

                  case 'H':
                        strcpy (host, optarg);
                        break;

                  case 'D':
                        strcpy (daemon, optarg);
                        break;

                  case 'M':
                        strcpy (monitorname, optarg);
                        break;

                  case 'P':
                        port = atoi(optarg);
                        break;

                  case 'K':
                        strcpy (pw, optarg);
                        break;

                  case 'd':
                        debug_level = atoi(optarg);
                        if (debug_level <= 0) {
                           debug_level = 1;
                        }
                        break;

          case 'h':
          case '?':
          default:
                         usage();
                         exit(1);
      }
   }
   argc -= optind;
   //argv += optind;

   if (argc) {
      usage();
      exit(STATE_UNKNOWN);
   }

   lmgr_init_thread();

   char sig[100];
   MD5Init(&md5c);
   MD5Update(&md5c, (unsigned char *) pw, strlen(pw));
   MD5Final(signature, &md5c);
   for (i = j = 0; i < sizeof(signature); i++) {
      sprintf(&sig[j], "%02x", signature[i]);
      j += 2;
   }


   /* director ?  */
   if (strcmp (daemon, "dir") == 0) {

//.........这里部分代码省略.........
开发者ID:rkorzeniewski,项目名称:bacula,代码行数:101,代码来源:check_bacula.c

示例2: tac_authen_send

/* this function sends a packet do TACACS+ server, asking
 * for validation of given username and password
 *
 * return value:
 *      0 : success
 *   <  0 : error status code, see LIBTAC_STATUS_...
 *             LIBTAC_STATUS_WRITE_ERR
 *             LIBTAC_STATUS_WRITE_TIMEOUT
 *             LIBTAC_STATUS_ASSEMBLY_ERR
 */
int tac_authen_send(int fd, const char *user, char *pass, char *tty,
    char *r_addr) {

    HDR *th;    /* TACACS+ packet header */
    struct authen_start tb;     /* message body */
    int user_len, port_len, chal_len, mdp_len, token_len, bodylength, w;
    int r_addr_len;
    int pkt_len = 0;
    int ret = 0;
    char *chal = "1234123412341234";
    char digest[MD5_LEN];
    char *token = NULL;
    u_char *pkt = NULL, *mdp = NULL;
    MD5_CTX mdcontext;

    th=_tac_req_header(TAC_PLUS_AUTHEN, 0);

    /* set some header options */
    if ((tac_login != NULL) && (strcmp(tac_login,"login") == 0)) {
        th->version = TAC_PLUS_VER_0;
    } else {
        th->version = TAC_PLUS_VER_1;
    }
    th->encryption = tac_encryption ? TAC_PLUS_ENCRYPTED_FLAG : TAC_PLUS_UNENCRYPTED_FLAG;

    TACDEBUG((LOG_DEBUG, "%s: user '%s', tty '%s', rem_addr '%s', encrypt: %s", \
        __FUNCTION__, user, tty, r_addr, \
        (tac_encryption) ? "yes" : "no"))        
        
    if ((tac_login != NULL) && (strcmp(tac_login,"chap") == 0)) {
        chal_len = strlen(chal);
        mdp_len = sizeof(u_char) + strlen(pass) + chal_len;
        mdp = (u_char *) xcalloc(1, mdp_len);
        mdp[0] = 5;
        memcpy(&mdp[1], pass, strlen(pass));
        memcpy(mdp + strlen(pass) + 1, chal, chal_len);
        MD5Init(&mdcontext);
        MD5Update(&mdcontext, mdp, mdp_len);
        MD5Final((u_char *) digest, &mdcontext);
        free(mdp);
        token = (char*) xcalloc(1, sizeof(u_char) + 1 + chal_len + MD5_LEN);
        token[0] = 5;
        memcpy(&token[1], chal, chal_len);
        memcpy(token + chal_len + 1, digest, MD5_LEN);
    } else {
        token = xstrdup(pass);
    }

    /* get size of submitted data */
    user_len = strlen(user);
    port_len = strlen(tty);
    r_addr_len = strlen(r_addr);
    token_len = strlen(token);

    /* fill the body of message */
    tb.action = TAC_PLUS_AUTHEN_LOGIN;
    tb.priv_lvl = tac_priv_lvl;
    if (tac_login == NULL) {
        /* default to PAP */
        tb.authen_type = TAC_PLUS_AUTHEN_TYPE_PAP;
    } else {
        if (strcmp(tac_login,"chap") == 0) {
            tb.authen_type = TAC_PLUS_AUTHEN_TYPE_CHAP;
        } else if (strcmp(tac_login,"login") == 0) {
            tb.authen_type = TAC_PLUS_AUTHEN_TYPE_ASCII;
        } else {
            tb.authen_type = TAC_PLUS_AUTHEN_TYPE_PAP;
        }
    }
    tb.service = tac_authen_service;
    tb.user_len = user_len;
    tb.port_len = port_len;
    tb.r_addr_len = r_addr_len;    /* may be e.g Caller-ID in future */
    tb.data_len = token_len;

    /* fill body length in header */
    bodylength = sizeof(tb) + user_len
        + port_len + r_addr_len + token_len;

    th->datalength = htonl(bodylength);

    /* we can now write the header */
    w = write(fd, th, TAC_PLUS_HDR_SIZE);
    if (w < 0 || w < TAC_PLUS_HDR_SIZE) {
        TACSYSLOG((LOG_ERR,\
            "%s: short write on header, wrote %d of %d: %m",\
            __FUNCTION__, w, TAC_PLUS_HDR_SIZE))
        free(token);
        free(pkt);
        free(th);
//.........这里部分代码省略.........
开发者ID:radzima,项目名称:pam_tacplus,代码行数:101,代码来源:authen_s.c

示例3: digest_nonce

/*
 * Make a nonce (NUL terminated)
 *  buf	-- buffer for result
 *  maxlen -- max length of result
 * returns final length or -1 on error
 */
static int
digest_nonce(char *buf, int maxlen)
{
	/*
	 * it shouldn't matter too much if two threads step on this counter
	 * at the same time, but mutexing it wouldn't hurt
	 */
	static int counter;
	char *dst;
	int len;
	struct chal_info {
		time_t mytime;
		unsigned char digest[16];
	} cinfo;
	MD5_CTX ctx;
	long r;
	static int set_rand = 0;
	unsigned char *p;
	int j;
	int fd;
	int got_random;

	/* initialize challenge */
	if (maxlen < 2 * sizeof (cinfo))
		return (-1);
	dst = buf;

	/* get a timestamp */
	time(&cinfo.mytime);

	/* get some randomness */

	got_random = 0;
	fd = open("/dev/urandom", O_RDONLY);
	if (fd != -1) {
	    got_random =
		(read(fd, &r, sizeof (r)) == sizeof (r));
	    close(fd);
	}

	if (!got_random) {
	    if (set_rand == 0) {
		struct timeval tv;

		r = cinfo.mytime - (getpid() *65536) + (random() & 0xffff);

		gettimeofday(&tv, NULL);
		r ^= tv.tv_usec;
		r ^= gethostid();

		srandom(r);
		set_rand = 1;
	    }

	    r = random();
	}

	MD5Init(&ctx);
	MD5Update(&ctx, (unsigned char *) &r, sizeof (r));
	MD5Update(&ctx, (unsigned char *) &counter, sizeof (counter));
	++counter;
	MD5Final(cinfo.digest, &ctx);

	/* compute hex for result */
	for (j = 0, p = (unsigned char *)&cinfo; j < sizeof (cinfo); ++j) {
		dst[j * 2]	= hextab[p[j] >> 4];
		dst[j * 2 + 1]	= hextab[p[j] & 0xf];
	}

	/* take the entire time_t, plus at least 6 bytes of MD5 output */
	len = ((sizeof (time_t) + 6) * 2);
	dst += len;
	maxlen -= len;

	*dst = '\0';

	return (dst - buf);
}
开发者ID:apprisi,项目名称:illumos-gate,代码行数:84,代码来源:digest_md5.c

示例4: uuid_generate_internal

static Datum
uuid_generate_internal(int v, unsigned char *ns, char *ptr, int len)
{
	char		strbuf[40];

	switch (v)
	{
		case 0:			/* constant-value uuids */
			strlcpy(strbuf, ptr, 37);
			break;

		case 1:			/* time/node-based uuids */
			{
#ifdef HAVE_UUID_E2FS
				uuid_t		uu;

				uuid_generate_time(uu);
				uuid_unparse(uu, strbuf);

				/*
				 * PTR, if set, replaces the trailing characters of the uuid;
				 * this is to support v1mc, where a random multicast MAC is
				 * used instead of the physical one
				 */
				if (ptr && len <= 36)
					strcpy(strbuf + (36 - len), ptr);
#else							/* BSD */
				uuid_t		uu;
				uint32_t	status = uuid_s_ok;
				char	   *str = NULL;

				uuid_create(&uu, &status);

				if (status == uuid_s_ok)
				{
					uuid_to_string(&uu, &str, &status);
					if (status == uuid_s_ok)
					{
						strlcpy(strbuf, str, 37);

						/*
						 * PTR, if set, replaces the trailing characters of
						 * the uuid; this is to support v1mc, where a random
						 * multicast MAC is used instead of the physical one
						 */
						if (ptr && len <= 36)
							strcpy(strbuf + (36 - len), ptr);
					}
					if (str)
						free(str);
				}

				if (status != uuid_s_ok)
					ereport(ERROR,
							(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
							 errmsg("uuid library failure: %d",
									(int) status)));
#endif
				break;
			}

		case 3:			/* namespace-based MD5 uuids */
		case 5:			/* namespace-based SHA1 uuids */
			{
				dce_uuid_t	uu;
#ifdef HAVE_UUID_BSD
				uint32_t	status = uuid_s_ok;
				char	   *str = NULL;
#endif

				if (v == 3)
				{
					MD5_CTX		ctx;

					MD5Init(&ctx);
					MD5Update(&ctx, ns, sizeof(uu));
					MD5Update(&ctx, (unsigned char *) ptr, len);
					/* we assume sizeof MD5 result is 16, same as UUID size */
					MD5Final((unsigned char *) &uu, &ctx);
				}
				else
				{
					SHA1_CTX	ctx;
					unsigned char sha1result[SHA1_RESULTLEN];

					SHA1Init(&ctx);
					SHA1Update(&ctx, ns, sizeof(uu));
					SHA1Update(&ctx, (unsigned char *) ptr, len);
					SHA1Final(sha1result, &ctx);
					memcpy(&uu, sha1result, sizeof(uu));
				}

				/* the calculated hash is using local order */
				UUID_TO_NETWORK(uu);
				UUID_V3_OR_V5(uu, v);

#ifdef HAVE_UUID_E2FS
				/* uuid_unparse expects local order */
				UUID_TO_LOCAL(uu);
				uuid_unparse((unsigned char *) &uu, strbuf);
//.........这里部分代码省略.........
开发者ID:kaigai,项目名称:sepgsql,代码行数:101,代码来源:uuid-ossp.c

示例5: daemon_auth

static void daemon_auth(std::string &user, std::string &key)
{
	if (user == "guest") {
		daemon_printf( "%d\n", CODE_OK );
		return;
	}
	char *buf;
	struct MD5Context ctx;
	unsigned char digest[16];
	char hex[33];
	if (user == "root") {
		std::string &root_password = stardictdMain.conf->get_str("root-user/password");
		if (root_password.empty()) {
			daemon_printf( "%d auth denied\n", CODE_DENIED );
			return;
		}
		MD5Init(&ctx);
		MD5Update(&ctx,  (const unsigned char*)"StarDict", 8); //StarDict-Protocol 0.4, add md5 salt.
		MD5Update(&ctx, (const unsigned char*)root_password.c_str(), root_password.length());
		MD5Final(digest, &ctx);
		for (int i = 0; i < 16; i++)
			snprintf( hex+2*i, 3, "%02x", digest[i] );
		hex[32] = '\0';
		buf = g_strdup_printf("%s%s", daemonStamp, hex);
	} else {
		if (init_database()) {
			daemon_printf( "%d Connect to MySQL failed!\n", CODE_DENIED );
			return;
		}
		std::string sql;
		sql = "SELECT user_id, user_md5saltpassword, level FROM stardict_users WHERE username=";
		AppendMysql(sql, user.c_str());
		if (stardictdMain.conn.query(sql.c_str(), sql.length())) {
			daemon_printf( "%d Query failed!\n", CODE_DENIED );
			return;
		}
		MySQLResult *res = stardictdMain.conn.getResult();
		if (!res) {
			daemon_printf( "%d Get result failed!\n", CODE_DENIED );
			return;
		}
		DB_ROW row = res->fetchRow();
		if (!row) {
			res->destroy();
			daemon_printf( "%d User doesn't exist!\n", CODE_DENIED );
			return;
		}
		userID = row[0];
		userLevel = atoi(row[2]);
		stardictdMain.SetUserLevel(userLevel);
		buf = g_strdup_printf("%s%s", daemonStamp, row[1]);
		res->destroy();
	}
	MD5Init(&ctx);
	MD5Update(&ctx, (const unsigned char*)buf, strlen(buf));
	MD5Final(digest, &ctx);
	for (int i = 0; i < 16; i++)
		snprintf( hex+2*i, 3, "%02x", digest[i] );
	hex[32] = '\0';
	g_free(buf);
	if (key != hex) {
		daemon_printf( "%d auth denied\n", CODE_DENIED );
		return;
	} else {
		daemon_printf( "%d authenticated\n", CODE_OK );
		auth_user=user;
		if (auth_user == "root") {
			stardictdMain.SetDictMask("", 0, 0);
		} else {
			std::string sql;
			sql = "SELECT dictmask, collatefunc, language FROM user_basic WHERE id=";
			sql+= userID;
			if (stardictdMain.conn.query(sql.c_str(), sql.length())) {
				daemon_printf( "%d Query failed!\n", CODE_DENIED );
				return;
			}
			MySQLResult *res = stardictdMain.conn.getResult();
			if (!res) {
				daemon_printf( "%d Get result failed!\n", CODE_DENIED );
				return;
			}
			DB_ROW row = res->fetchRow();
			if (row) {
				char *str = g_strdup_printf("level-%d-user/max_dict_count", userLevel);
				const int max_dict_count = stardictdMain.conf->get_int(str);
				g_free(str);
				stardictdMain.SetDictMask(row[0], max_dict_count, userLevel);
				bool enable_collate;
				if (userLevel == 0) {
					enable_collate = stardictdMain.conf->get_bool("level-0-user/enable_collate");
				} else {
					enable_collate = true;
				}
				if (enable_collate) {
					stardictdMain.SetServerCollateFunc(atoi(row[1]));
				} else {
					stardictdMain.SetServerCollateFunc(0);
				}
				stardictdMain.SetUserLang(row[2]);
			} else {
//.........这里部分代码省略.........
开发者ID:huzheng001,项目名称:stardictd,代码行数:101,代码来源:daemon.cpp

示例6: PassB

int
PassB(FILE *fd)
{
    u_char *p,*q;
    MD5_CTX ctx;
    int i,j,sep,cnt;
    u_char *md5=0,*md5before=0,*trash=0,*name=0,*uid=0,*gid=0,*mode=0;
    struct CTM_Syntax *sp;
    FILE *b = 0;	/* backup command */
    u_char buf[BUFSIZ];
    char md5_1[33];
    int ret = 0;
    int match = 0;
    struct CTM_Filter *filter = NULL;

    if(Verbose>3)
	printf("PassB -- Backing up files which would be changed.\n");

    MD5Init (&ctx);
    snprintf(buf, sizeof(buf), fmtcheck(TarCmd, TARCMD), BackupFile);
    b=popen(buf, "w");
    if(!b) { warn("%s", buf); return Exit_Garbage; }

    GETFIELD(p,' '); if(strcmp("CTM_BEGIN",p)) WRONG
    GETFIELD(p,' '); if(strcmp(Version,p)) WRONG
    GETFIELD(p,' '); if(strcmp(Name,p)) WRONG
    GETFIELD(p,' '); if(strcmp(Nbr,p)) WRONG
    GETFIELD(p,' '); if(strcmp(TimeStamp,p)) WRONG
    GETFIELD(p,'\n'); if(strcmp(Prefix,p)) WRONG

    for(;;) {
	Delete(md5);
	Delete(uid);
	Delete(gid);
	Delete(mode);
	Delete(md5before);
	Delete(trash);
	Delete(name);
	cnt = -1;

	GETFIELD(p,' ');

	if (p[0] != 'C' || p[1] != 'T' || p[2] != 'M') WRONG

	if(!strcmp(p+3,"_END"))
	    break;

	for(sp=Syntax;sp->Key;sp++)
	    if(!strcmp(p+3,sp->Key))
		goto found;
	WRONG
    found:
	for(i=0;(j = sp->List[i]);i++) {
	    if (sp->List[i+1] && (sp->List[i+1] & CTM_F_MASK) != CTM_F_Bytes)
		sep = ' ';
	    else
		sep = '\n';

	    switch (j & CTM_F_MASK) {
		case CTM_F_Name: GETNAMECOPY(name,sep,j, Verbose); break;
		case CTM_F_Uid:  GETFIELDCOPY(uid,sep); break;
		case CTM_F_Gid:  GETFIELDCOPY(gid,sep); break;
		case CTM_F_Mode: GETFIELDCOPY(mode,sep); break;
		case CTM_F_MD5:
		    if(j & CTM_Q_MD5_Before)
			GETFIELDCOPY(md5before,sep);
		    else
			GETFIELDCOPY(md5,sep);
		    break;
		case CTM_F_Count: GETBYTECNT(cnt,sep); break;
		case CTM_F_Bytes: GETDATA(trash,cnt); break;
		default: WRONG
		}
	    }
	/* XXX This should go away.  Disallow trailing '/' */
	j = strlen(name)-1;
	if(name[j] == '/') name[j] = '\0';

	if (KeepIt && 
	    (!strcmp(sp->Key,"DR") || !strcmp(sp->Key,"FR")))
	    continue;
		
	/* match the name against the elements of the filter list.  The
	   action associated with the last matched filter determines whether
	   this file should be ignored or backed up. */
	match = (FilterList ? !(FilterList->Action) : CTM_FILTER_ENABLE);
	for (filter = FilterList; filter; filter = filter->Next) {
	    if (0 == regexec(&filter->CompiledRegex, name, 0, 0, 0))
		match = filter->Action;
	}

	if (CTM_FILTER_DISABLE == match)
		continue;

	if (!strcmp(sp->Key,"FS") || !strcmp(sp->Key,"FN") ||
	    !strcmp(sp->Key,"AS") || !strcmp(sp->Key,"DR") || 
	    !strcmp(sp->Key,"FR")) {
	    /* send name to the archiver for a backup */
	    cnt = strlen(name);
	    if (cnt != fwrite(name,1,cnt,b) || EOF == fputc('\n',b)) {
//.........这里部分代码省略.........
开发者ID:2asoft,项目名称:freebsd,代码行数:101,代码来源:ctm_passb.c

示例7: saversakey

/*
 * Save an RSA key file. Return nonzero on success.
 */
int saversakey(const Filename *filename, struct RSAKey *key, char *passphrase)
{
    unsigned char buf[16384];
    unsigned char keybuf[16];
    struct MD5Context md5c;
    unsigned char *p, *estart;
    FILE *fp;

    /*
     * Write the initial signature.
     */
    p = buf;
    memcpy(p, rsa_signature, sizeof(rsa_signature));
    p += sizeof(rsa_signature);

    /*
     * One byte giving encryption type, and one reserved (zero)
     * uint32.
     */
    *p++ = (passphrase ? SSH_CIPHER_3DES : 0);
    PUT_32BIT(p, 0);
    p += 4;

    /*
     * An ordinary SSH-1 public key consists of: a uint32
     * containing the bit count, then two bignums containing the
     * modulus and exponent respectively.
     */
    PUT_32BIT(p, bignum_bitcount(key->modulus));
    p += 4;
    p += ssh1_write_bignum(p, key->modulus);
    p += ssh1_write_bignum(p, key->exponent);

    /*
     * A string containing the comment field.
     */
    if (key->comment) {
	PUT_32BIT(p, strlen(key->comment));
	p += 4;
	memcpy(p, key->comment, strlen(key->comment));
	p += strlen(key->comment);
    } else {
	PUT_32BIT(p, 0);
	p += 4;
    }

    /*
     * The encrypted portion starts here.
     */
    estart = p;

    /*
     * Two bytes, then the same two bytes repeated.
     */
    *p++ = random_byte();
    *p++ = random_byte();
    p[0] = p[-2];
    p[1] = p[-1];
    p += 2;

    /*
     * Four more bignums: the decryption exponent, then iqmp, then
     * q, then p.
     */
    p += ssh1_write_bignum(p, key->private_exponent);
    p += ssh1_write_bignum(p, key->iqmp);
    p += ssh1_write_bignum(p, key->q);
    p += ssh1_write_bignum(p, key->p);

    /*
     * Now write zeros until the encrypted portion is a multiple of
     * 8 bytes.
     */
    while ((p - estart) % 8)
	*p++ = '\0';

    /*
     * Now encrypt the encrypted portion.
     */
    if (passphrase) {
	MD5Init(&md5c);
	MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
	MD5Final(keybuf, &md5c);
	des3_encrypt_pubkey(keybuf, estart, p - estart);
	smemclr(keybuf, sizeof(keybuf));	/* burn the evidence */
    }

    /*
     * Done. Write the result to the file.
     */
    fp = f_open(filename, "wb", TRUE);
    if (fp) {
	int ret = (fwrite(buf, 1, p - buf, fp) == (size_t) (p - buf));
        if (fclose(fp))
            ret = 0;
	return ret;
    } else
//.........这里部分代码省略.........
开发者ID:opengl-ms,项目名称:Far-NetBox,代码行数:101,代码来源:SSHPUBK.c

示例8: decrypt_avp

int decrypt_avp (char *buf, struct tunnel *t)
{
    /* Decrypts a hidden AVP pointed to by buf.  The
       new header will be exptected to be two characters
       offset from the old */
    int cnt = 0;
    int len, olen, flags;
    unsigned char digest[MD_SIG_SIZE];
    char *ptr, *end;
    _u16 attr;
    struct avp_hdr *old_hdr = (struct avp_hdr *) buf;
    struct avp_hdr *new_hdr = (struct avp_hdr *) (buf + 2);
    int saved_segment_len;      /* maybe less 16; may be used if the cipher is longer than 16 octets */
    unsigned char saved_segment[MD_SIG_SIZE];
    ptr = ((char *) old_hdr) + sizeof (struct avp_hdr);
    olen = old_hdr->length & 0x0FFF;
    end = buf + olen;
    if (!t->chal_us.vector)
    {
        l2tp_log (LOG_DEBUG,
             "decrypt_avp: Hidden bit set, but no random vector specified!\n");
        return -EINVAL;
    }
    /* First, let's decrypt all the data.  We're not guaranteed
       that it will be padded to a 16 byte boundary, so we
       have to be more careful than when encrypting */
    attr = ntohs (old_hdr->attr);
    MD5Init (&t->chal_us.md5);
    MD5Update (&t->chal_us.md5, (void *) &attr, 2);
    MD5Update (&t->chal_us.md5, t->chal_us.secret,
               strlen ((char *)t->chal_us.secret));
    MD5Update (&t->chal_us.md5, t->chal_us.vector, t->chal_us.vector_len);
    MD5Final (digest, &t->chal_us.md5);
#ifdef DEBUG_HIDDEN
    l2tp_log (LOG_DEBUG, "attribute is %d and challenge is: ", attr);
    print_challenge (&t->chal_us);
    l2tp_log (LOG_DEBUG, "md5 is: ");
    print_md5 (digest);
#endif
    while (ptr < end)
    {
        if (cnt >= MD_SIG_SIZE)
        {
            MD5Init (&t->chal_us.md5);
            MD5Update (&t->chal_us.md5, t->chal_us.secret,
                       strlen ((char *)t->chal_us.secret));
            MD5Update (&t->chal_us.md5, saved_segment, MD_SIG_SIZE);
            MD5Final (digest, &t->chal_us.md5);
            cnt = 0;
        }
        /* at the beginning of each segment, we save the current segment (16 octets or less) of cipher 
         * so that the next round of MD5 (if there is a next round) hash could use it 
         */
        if (cnt == 0)
        {
            saved_segment_len =
                (end - ptr < MD_SIG_SIZE) ? (end - ptr) : MD_SIG_SIZE;
            memcpy (saved_segment, ptr, saved_segment_len);
        }
        *ptr = *ptr ^ digest[cnt++];
        ptr++;
    }
    /* Hopefully we're all nice and decrypted now.  Let's rewrite the header. 
       First save the old flags, and get the new stuff */
    flags = old_hdr->length & 0xF000 & ~HBIT;
    len = ntohs (new_hdr->attr) + sizeof (struct avp_hdr);
    if (len > olen - 2)
    {
        l2tp_log (LOG_DEBUG,
             "decrypt_avp: Decrypted length is too long (%d > %d)\n", len,
             olen - 2);
        return -EINVAL;
    }
    new_hdr->attr = old_hdr->attr;
    new_hdr->vendorid = old_hdr->vendorid;
    new_hdr->length = len | flags;
    return 0;
}
开发者ID:Disrupt6,项目名称:xavl2tp,代码行数:78,代码来源:aaa.c

示例9: auth_rx

// return 1 if error, 0 if ok
int auth_rx(OspfPacket *pkt, OspfPacketDesc *desc) {
	RcpInterface *intf = rcpFindInterfaceByKIndex(shm, desc->if_index);
	if (!intf)
		return 1;

	uint16_t type = ntohs(pkt->header.auth_type);
	if (type != intf->ospf_auth_type) {
		trap_IfAuthFailure(desc->if_index, desc->ip_source, 1, pkt->header.type);
		return 1;
	}
	
	// simple authentication
	if (type == 1) {
		if (memcmp(pkt->header.auth_data, intf->ospf_passwd, 8)) {
			trap_IfAuthFailure(desc->if_index, desc->ip_source, 0, pkt->header.type);
			return 1;
		}
		// clear the password field before checksum
		memset(pkt->header.auth_data, 0, 8);
	}
	// md5 authentication
	else if (type == 2) {
		// copy md5 header
		OspfMd5	md5;
		memcpy(&md5, pkt->header.auth_data, 8);
		md5.seq = ntohl(md5.seq);

		// check key id
		if (md5.key_id != intf->ospf_md5_key) {
			trap_IfAuthFailure(desc->if_index, desc->ip_source, 0, pkt->header.type);
			return 1;
		}

		// check sequence number
		OspfNeighbor *nb = neighborFind(desc->area_id, desc->ip_source);
		if (nb != NULL) {
			if (md5.seq < nb->ospf_md5_seq) {
				trap_IfAuthFailure(desc->if_index, desc->ip_source, 0, pkt->header.type);
				return 1;
			}
		}
			
		// check digest present
		if (desc->rx_size != (ntohs(pkt->header.length) + 20 + md5.auth_data_len)) {
			trap_IfAuthFailure(desc->if_index, desc->ip_source, 0, pkt->header.type);
			return 1;
		}
				
		// store packet digest
		uint8_t pkt_digest[16];
		uint8_t *end = (uint8_t *) &pkt->header;
		end += ntohs(pkt->header.length);
		memcpy(pkt_digest, end, 16);

		// copy our password at the end of the packet
		memcpy(end, intf->ospf_md5_passwd, 16);

		MD5_CTX context;
		uint8_t digest[16];
		MD5Init(&context);
		MD5Update(&context, (uint8_t *) &pkt->header, ntohs(pkt->header.length) + 16);
		MD5Final(digest, &context);

		// compare
		if (memcmp(digest, pkt_digest, 16) != 0) {
			trap_IfAuthFailure(desc->if_index, desc->ip_source, 0, pkt->header.type);
			return 1;
		}
			
		// update seq in neighbor structure
		if (nb != NULL)
			 nb->ospf_md5_seq = md5.seq;
			
	}
	
	return 0;
}
开发者ID:a5216652166,项目名称:rcp100,代码行数:78,代码来源:auth.c

示例10: handle_challenge

int handle_challenge (struct tunnel *t, struct challenge *chal)
{
    char *us;
    char *them;
    if (!t->lns && !t->lac)
    {
        l2tp_log (LOG_DEBUG, "%s: No LNS or LAC to handle challenge!\n",
             __FUNCTION__);
        return -1;
    }
#ifdef DEBUG_AUTH
    l2tp_log (LOG_DEBUG, "%s: making response for tunnel: %d\n", __FUNCTION__,
         t->ourtid);
#endif
    if (t->lns)
    {
        if (t->lns->hostname[0])
            us = t->lns->hostname;
        else
            us = hostname;
        if (t->lns->peername[0])
            them = t->lns->peername;
        else
            them = t->hostname;
    }
    else
    {
        if (t->lac->hostname[0])
            us = t->lac->hostname;
        else
            us = hostname;
        if (t->lac->peername[0])
            them = t->lac->peername;
        else
            them = t->hostname;
    }

    if (!get_secret (us, them, chal->secret, sizeof (chal->secret)))
    {
        l2tp_log (LOG_DEBUG, "%s: no secret found for us='%s' and them='%s'\n",
             __FUNCTION__, us, them);
        return -1;
    }

#if DEBUG_AUTH
    l2tp_log (LOG_DEBUG, "*%s: Here comes the chal->ss:\n", __FUNCTION__);
    bufferDump (&chal->ss, 1);

    l2tp_log (LOG_DEBUG, "%s: Here comes the secret\n", __FUNCTION__);
    bufferDump (chal->secret, strlen (chal->secret));

    l2tp_log (LOG_DEBUG, "%s: Here comes the challenge\n", __FUNCTION__);
    bufferDump (chal->challenge, chal->chal_len);
#endif

    memset (chal->response, 0, MD_SIG_SIZE);
    MD5Init (&chal->md5);
    MD5Update (&chal->md5, &chal->ss, 1);
    MD5Update (&chal->md5, chal->secret, strlen ((char *)chal->secret));
    MD5Update (&chal->md5, chal->challenge, chal->chal_len);
    MD5Final (chal->response, &chal->md5);
#ifdef DEBUG_AUTH
    l2tp_log (LOG_DEBUG, "response is %X%X%X%X to '%s' and %X%X%X%X, %d\n",
         *((int *) &chal->response[0]),
         *((int *) &chal->response[4]),
         *((int *) &chal->response[8]),
         *((int *) &chal->response[12]),
         chal->secret,
         *((int *) &chal->challenge[0]),
         *((int *) &chal->challenge[4]),
         *((int *) &chal->challenge[8]),
         *((int *) &chal->challenge[12]), chal->ss);
#endif
    chal->state = STATE_CHALLENGED;
    return 0;
}
开发者ID:Disrupt6,项目名称:xavl2tp,代码行数:76,代码来源:aaa.c

示例11: encrypt_avp

void encrypt_avp (struct buffer *buf, _u16 len, struct tunnel *t)
{
    /* Encrypts an AVP of len, at data.  We assume there
       are two "spare bytes" before the data pointer,l but otherwise
       this is just a normal AVP that is about to be returned from
       an avpsend routine */
    struct avp_hdr *new_hdr =
        (struct avp_hdr *) (buf->start + buf->len - len);
    struct avp_hdr *old_hdr =
        (struct avp_hdr *) (buf->start + buf->len - len + 2);
    _u16 length, flags, attr;   /* New length, old flags */
    unsigned char *ptr, *end;
    int cnt;
    unsigned char digest[MD_SIG_SIZE];
    unsigned char *previous_segment;

    /* FIXME: Should I pad more randomly? Right now I pad to nearest 16 bytes */
    length =
        ((len - sizeof (struct avp_hdr) + 1) / 16 + 1) * 16 +
        sizeof (struct avp_hdr);
    flags = htons (old_hdr->length) & 0xF000;
    new_hdr->length = htons (length | flags | HBIT);
    new_hdr->vendorid = old_hdr->vendorid;
    new_hdr->attr = attr = old_hdr->attr;
    /* This is really the length field of the hidden sub-format */
    old_hdr->attr = htons (len - sizeof (struct avp_hdr));
    /* Okay, now we've rewritten the header, as it should be.  Let's start
       encrypting the actual data now */
    buf->len -= len;
    buf->len += length;
    /* Back to the beginning of real data, including the original length AVP */

    MD5Init (&t->chal_them.md5);
    MD5Update (&t->chal_them.md5, (void *) &attr, 2);
    MD5Update (&t->chal_them.md5, t->chal_them.secret,
               strlen ((char *)t->chal_them.secret));
    MD5Update (&t->chal_them.md5, t->chal_them.vector, VECTOR_SIZE);
    MD5Final (digest, &t->chal_them.md5);

    /* Though not a "MUST" in the spec, our subformat length is always a multiple of 16 */
    ptr = ((unsigned char *) new_hdr) + sizeof (struct avp_hdr);
    end = ((unsigned char *) new_hdr) + length;
    previous_segment = ptr;
    while (ptr < end)
    {
#if DEBUG_HIDDEN
        l2tp_log (LOG_DEBUG, "%s: The digest to be XOR'ed\n", __FUNCTION__);
        bufferDump (digest, MD_SIG_SIZE);
        l2tp_log (LOG_DEBUG, "%s: The plaintext to be XOR'ed\n", __FUNCTION__);
        bufferDump (ptr, MD_SIG_SIZE);
#endif
        for (cnt = 0; cnt < MD_SIG_SIZE; cnt++, ptr++)
        {
            *ptr = *ptr ^ digest[cnt];
        }
#if DEBUG_HIDDEN
        l2tp_log (LOG_DEBUG, "%s: The result of XOR\n", __FUNCTION__);
        bufferDump (previous_segment, MD_SIG_SIZE);
#endif
        if (ptr < end)
        {
            MD5Init (&t->chal_them.md5);
            MD5Update (&t->chal_them.md5, t->chal_them.secret,
                       strlen ((char *)t->chal_them.secret));
            MD5Update (&t->chal_them.md5, previous_segment, MD_SIG_SIZE);
            MD5Final (digest, &t->chal_them.md5);
        }
        previous_segment = ptr;
    }
}
开发者ID:Disrupt6,项目名称:xavl2tp,代码行数:70,代码来源:aaa.c

示例12: nextSignature

/*
 * Returns the next product signature (MD5 checksum).
 *
 * signature               The buffer in which to put the MD5 checksum.
 */
static void nextSignature(signaturet* signature)
{
    MD5Init(md5);
    MD5Update(md5, (const unsigned char*)&prodCount, sizeof(prodCount));
    MD5Final((unsigned char*)*signature, md5);
}
开发者ID:akrherz,项目名称:LDM,代码行数:11,代码来源:fauxPqConfigFile.c

示例13: digest_md5_init

static int digest_md5_init(EVP_MD_CTX *ctx)
{
    MD5Init(data(ctx));
    return 1;
}
开发者ID:johnjohnsp1,项目名称:opensgx,代码行数:5,代码来源:rsaref.c

示例14: update_file_md5sum

/* Returns: TRUE if FileRow value has been changed */
static gboolean
update_file_md5sum (FileRow *row, const gchar *complete_filename)
{
	gboolean changed = TRUE;
	GValue *value = NULL;
    	/* MD5 computation */
	MD5_CTX context;
	unsigned char digest[16]; /* Flawfinder: ignore */
	GString *md5str;
	gint i;
	int fd;
        gpointer map;
        guint length;
        HANDLE view;
	/* file mapping in mem */
	length = g_value_get_uint (row->size_value);
	if (length == 0)
		goto md5end;
	fd = open (complete_filename, O_RDONLY); /* Flawfinder: ignore */
	if (fd < 0)
		goto md5end;
#ifndef G_OS_WIN32
	map = mmap (NULL, length, PROT_READ, MAP_PRIVATE, fd, 0);
	if (map == MAP_FAILED) {
		close (fd);
		goto md5end;
	}
#else
	 view = CreateFileMapping ((HANDLE) fd,
					 NULL, PAGE_READONLY|SEC_COMMIT, 0,0 , NULL);
	if (!view) {
		close (fd);
		goto md5end;
	}
	map = MapViewOfFile (view, FILE_MAP_READ, 0, 0, length);
	if (!map) {
		close (fd);
		goto md5end;
	}
#endif /* !G_OS_WIN32 */



	MD5Init (&context);
	MD5Update (&context, map, length);
	MD5Final (digest, &context);

	md5str = g_string_new ("");
	for (i = 0; i < 16; i++)
		g_string_append_printf (md5str, "%02x", digest[i]);
	value = gda_value_new (G_TYPE_STRING);
	g_value_take_string (value, md5str->str);
	g_string_free (md5str, FALSE);

#ifndef G_OS_WIN32
	munmap (map, length);
#else
	UnmapViewOfFile (map);
#endif /* !G_OS_WIN32 */
	close (fd);

 md5end:
	if (value) {
		if (row->md5sum_value && (G_VALUE_TYPE (row->md5sum_value) == G_TYPE_STRING)
		    && !gda_value_compare (row->md5sum_value, value))
			changed = FALSE;
		else {
			if (row->md5sum_value)
				gda_value_free (row->md5sum_value);
			row->md5sum_value = value;
		}
	}
	else {
		if (row->md5sum_value && gda_value_is_null (row->md5sum_value))
			changed = FALSE;
		else {
			if (row->md5sum_value)
				gda_value_free (row->md5sum_value);
			row->md5sum_value = gda_value_new_null ();
		}
	}

	return changed;
}
开发者ID:BabeNovelty,项目名称:glib-win32,代码行数:85,代码来源:gda-data-model-dir-vs10.c

示例15: free

/**
 * UtilSaltedMd5
 *
 * Computes the MD5 hash of a given string and returns
 * a string representation of the hash.
 *
 * @param String the string which should be hashed
 * @param Salt the salt value
 * @param BrokenAlgo whether to use the broken algorithm
 */
const char *UtilMd5(const char *String, const char *Salt, bool BrokenAlgo) {
#ifdef HAVE_LIBSSL
	MD5_CTX context;
#else /* HAVE_LIBSSL */
	sMD5_CTX context;
#endif /* HAVE_LIBSSL */
	broken_sMD5_CTX broken_context;
	unsigned char digest[16];
	char *StringAndSalt, *StringPtr;
	static char *SaltAndResult = NULL;
	int rc;

	free(SaltAndResult);

	if (Salt != NULL) {
		rc = asprintf(&StringAndSalt, "%s%s", String, Salt);
	} else {
		rc = asprintf(&StringAndSalt, "%s", String);
	}

	if (RcFailed(rc)) {
		g_Bouncer->Fatal();
	}

	if (!BrokenAlgo) {
#ifdef HAVE_LIBSSL
		MD5_Init(&context);
		MD5_Update(&context, (unsigned char *)StringAndSalt, strlen(StringAndSalt));
		MD5_Final(digest, &context);
#else /* HAVE_LIBSSL */
		MD5Init(&context);
		MD5Update(&context, (unsigned char *)StringAndSalt, strlen(StringAndSalt));
		MD5Final(digest, &context);
#endif /* HAVE_LIBSSL */
	} else {
		broken_MD5Init(&broken_context);
		broken_MD5Update(&broken_context, (unsigned char *)StringAndSalt, strlen(StringAndSalt));
		broken_MD5Final(digest, &broken_context);
	}

	free(StringAndSalt);

	if (Salt != NULL) {
		SaltAndResult = (char *)malloc(strlen(Salt) + 50);

		if (AllocFailed(SaltAndResult)) {
			g_Bouncer->Fatal();
		}

		strmcpy(SaltAndResult, Salt, strlen(Salt) + 50);
		strmcat(SaltAndResult, "$", strlen(Salt) + 50);
		StringPtr = SaltAndResult + strlen(SaltAndResult);
	} else {
		StringPtr = SaltAndResult = (char *)malloc(50);

		if (AllocFailed(SaltAndResult)) {
			g_Bouncer->Fatal();
		}
	}

	for (int i = 0; i < 16; i++) {
		/* TODO: don't use sprintf */
		sprintf(StringPtr + i * 2, "%02x", digest[i]);
	}

	return SaltAndResult;
}
开发者ID:demize,项目名称:shroudbnc,代码行数:77,代码来源:utility.cpp


注:本文中的MD5Init函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。