Exemple #1
0
int CommonHKDF(int argc, char *const *argv)
{
	size_t i, n;
	int err;
	
	plan_tests(10 * 2);
		
	n = sizeof(hkdf_sha256_tests) / sizeof(*hkdf_sha256_tests);
	for(i = 0; i < n; ++i) {
		const test_vector_t *			tv   = &hkdf_sha256_tests[ i ];
		byteBuffer						ikm  = hexStringToBytes(tv->ikm);
		byteBuffer						salt = hexStringToBytes(tv->salt);
		byteBuffer						info = hexStringToBytes(tv->info);
		byteBuffer						okmActual = mallocByteBuffer(tv->len);
		byteBuffer						okmExpected = hexStringToBytes(tv->okm);
		CCDigestAlgorithm				digestType;
		
		if(     tv->type == type_sha1)   digestType = kCCDigestSHA1;
		else if(tv->type == type_sha256) digestType = kCCDigestSHA256;
		else if(tv->type == type_sha512) digestType = kCCDigestSHA512;
		else abort();
		
		err = CCKeyDerivationHMac(kCCKDFAlgorithmHKDF, digestType, 0, ikm->bytes, ikm->len, NULL, 0, 
			info->bytes, info->len, NULL, 0, salt->bytes, salt->len, okmActual->bytes, okmActual->len );
		ok(!err, "check return value");
		ok(bytesAreEqual(okmActual, okmExpected), "compare memory of answer");
		
		free(ikm);
		free(salt);
		free(info);
		free(okmActual);
		free(okmExpected);
	}
	return 0;
}
Exemple #2
0
void MainWindow::handle_pushButton_decrypt_onClick()
{
  int size = 0;
  QString q_key = ui->textEdit_key->toPlainText();
  string s_key = string((const char *)q_key.toLocal8Bit()); 
  size = formatString(s_key);
  byte key[size];
  hexStringToBytes(s_key,key);
  //pnt_byte(key,16);

  QString q_in = ui->textEdit_input->toPlainText();
  string s_in = string((const char *)q_in.toLocal8Bit()); 
  size = formatString(s_in);
  byte in[size];
  hexStringToBytes(s_in,in);
  //pnt_byte(in,70);

  byte *out = NULL;
  CRYPTER *crypter = new CRYPTER(key);	
  int len = crypter->decrypt(in,size,out);
  //pnt_byte(out,len);

  string s_out = bytesToHexString(out,len);
  QString q_out = QString(QString::fromLocal8Bit(s_out.c_str()));
  ui->textEdit_output->setPlainText(q_out);
  //std::cout << "handle_pushButton_decrypt_onClick" << std::endl;

  delete out;
  delete crypter;
}
static int test_oneshot(const struct ccmode_cbc *cbc, char *mode_name, test_vector *vector) {
    uint8_t answer[CMAC_BLOCKSIZE];
    byteBuffer key = hexStringToBytes(vector->keyStr);
    byteBuffer in = hexStringToBytes(vector->inStr);
    cccmac(cbc, key->bytes, in->len, in->bytes, answer);
    ok(test_answer(mode_name, vector, answer, "one-shot"), "check answer");
    return 1;
}
Exemple #4
0
void rewriteMacGw( char* argv, int len, char* mac_gw )
{
    PETH_HDR ether;

    ether = (PETH_HDR)argv;
    memcpy( ether->ether_dhost, hexStringToBytes( mac_gw ), ETHER_ADDR_LEN );
}
static int test_answer(const struct ccdigest_info *di, test_vector *vector, void*answer) {
    uint8_t *correct_answer = NULL;
    if(ccdigest_oid_equal(di, (ccoid_t) CC_DIGEST_OID_MD2)) correct_answer = vector->md2_answer;
    else if(ccdigest_oid_equal(di, (ccoid_t) CC_DIGEST_OID_MD4)) correct_answer = vector->md4_answer;
    else if(ccdigest_oid_equal(di, (ccoid_t) CC_DIGEST_OID_MD5)) correct_answer = vector->md5_answer;
    else if(ccdigest_oid_equal(di, (ccoid_t) CC_DIGEST_OID_SHA1)) correct_answer = vector->sha1_answer;
    else if(ccdigest_oid_equal(di, (ccoid_t) CC_DIGEST_OID_SHA224)) correct_answer = vector->sha224_answer;
    else if(ccdigest_oid_equal(di, (ccoid_t) CC_DIGEST_OID_SHA256)) correct_answer = vector->sha256_answer;
    else if(ccdigest_oid_equal(di, (ccoid_t) CC_DIGEST_OID_SHA384)) correct_answer = vector->sha384_answer;
    else if(ccdigest_oid_equal(di, (ccoid_t) CC_DIGEST_OID_SHA512)) correct_answer = vector->sha512_answer;
    else if(ccdigest_oid_equal(di, (ccoid_t) CC_DIGEST_OID_RMD128)) correct_answer = vector->rmd128_answer;
    else if(ccdigest_oid_equal(di, (ccoid_t) CC_DIGEST_OID_RMD160)) correct_answer = vector->rmd160_answer;
    else if(ccdigest_oid_equal(di, (ccoid_t) CC_DIGEST_OID_RMD256)) correct_answer = vector->rmd256_answer;
    else correct_answer = vector->rmd320_answer; // hack
    byteBuffer answer_bb = bytesToBytes(answer, di->output_size);
    if(correct_answer == NULL) {
        printByteBuffer(answer_bb, "Answer Provided");
        return 1;
    }
    byteBuffer correct_answer_bb = hexStringToBytes((char *) correct_answer);
    ok(bytesAreEqual(correct_answer_bb, answer_bb), "compare memory of answer");
    if(bytesAreEqual(correct_answer_bb, answer_bb) == 0) {
        printByteBuffer(correct_answer_bb, "Correct Answer");
        printByteBuffer(answer_bb, "Provided Answer");
    }
    free(correct_answer_bb);
    free(answer_bb);
    return 1;
}
int CommonCryptoSymOffset(int argc, char *const *argv) {
    int accum = 0;
    uint8_t iLikeBigBuffs[ILIKEEMDISBIG];
    uint8_t andICannotLie[ILIKEEMDISBIG];
    uint8_t iLikeEmRoundandBig[ILIKEEMDISBIG];
    int i;
    size_t moved;
    CCCryptorStatus retval;
    byteBuffer key = hexStringToBytes("010203040506070809000a0b0c0d0e0f");
    
    plan_tests(kTestTestCount);

    
    for(i=0; i<ALITTLEONTHESIDE; i++) {
        retval = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, 0, key->bytes, key->len, NULL, iLikeBigBuffs+i, ILIKEEMDISBIG-16, andICannotLie+i, ILIKEEMDISBIG, &moved);
        retval = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, 0, key->bytes, key->len, NULL, andICannotLie+i, moved, iLikeEmRoundandBig+i, ILIKEEMDISBIG, &moved);
        if(moved != (ILIKEEMDISBIG-16))
            retval = 99;
        else if(memcmp(iLikeBigBuffs+i, iLikeEmRoundandBig+i, moved))
            retval = 999;
        ok(retval == 0, "Encrypt/Decrypt Cycle");
        accum += retval;
    }
    
    return accum != 0;
}
static int testI()
{
    CCStatus status;
    uint32_t I=0x10203040;
    char *hexstring = "10203040";
    byteBuffer bb = hexStringToBytes(hexstring);
    CCBigNumRef num1 = CCCreateBigNum(&status);
    char *output;
    
    ok(status == 0, "BigNum Created");
    status = CCBigNumSetI(num1, I);
    ok(status == 0, "BigNum Set to I");
    output = CCBigNumToHexString(&status, num1);
    ok(status == 0, "Value retrieved");
    ok(strcmp(output, hexstring) == 0, "strings are equal");
    if(strcmp(output, hexstring)) {
        printf("output: %s\n", output);
        printf("input : %s\n", hexstring);
    }
    free(output);
    
    uint32_t outI = CCBigNumGetI(&status, num1);
    ok(status == 0, "Value retrieved 2");
    
    ok(outI == I, "input == output");
    free(bb);
    CCBigNumFree(num1);
    
    return 0;
    
}
static int testCreateFree()
{
    CCStatus status;
    CCBigNumRef stress[STRESSSIZE];
    for(size_t i=0; i<STRESSSIZE; i++) stress[i] = NULL;
    byteBuffer bb = hexStringToBytes("0102030405060708091011121314151617181920");
    for(int i=0; i<100; i++) {
        for(int j=0; j<100; j++) {
            CCBigNumRef r = CCBigNumCreateRandom(&status, 31, 31, 0);
            ok(status == kCCSuccess, "Created Random Number");
            size_t ri = CCBigNumGetI(&status, r);
            ok(status == kCCSuccess, "translated to int");
            
            ri %= STRESSSIZE;

            if(stress[ri] == NULL) {
                int sel = ri % 3;
                switch(sel) {
                    case 0: /* printf("(%lu) BigNum\n", ri); */ stress[ri] = CCCreateBigNum(&status); break;
                    case 1: /* printf("(%lu) FromHex\n", ri); */ stress[ri] = CCBigNumFromHexString(&status, "0003"); break;
                    case 2: /* printf("(%lu) FromData\n", ri); */ stress[ri] = CCBigNumFromData(&status, bb->bytes, bb->len); break;
                }
                ok(status == kCCSuccess, "BigNum Created");
            } else {
                /* printf("(%lu) Freeing\n", ri); */
                CCBigNumClear(stress[ri]);
                CCBigNumFree(stress[ri]);
                stress[ri] = NULL;
            }
            CCBigNumFree(r);
        }
    }
    return 0;
}
static int testData()
{
    CCStatus status;
    char *hexstring = "1002030405060708090021222324252627282920";
    byteBuffer bb = hexStringToBytes(hexstring);
    CCBigNumRef num1 = CCBigNumFromData(&status, bb->bytes, bb->len);
    char *output;
    
    ok(status == 0, "BigNum Created");
    output = CCBigNumToHexString(&status, num1);
    ok(status == 0, "Value retrieved");
    ok(strcmp(output, hexstring) == 0, "strings are equal");
    if(strcmp(output, hexstring)) {
        printf("output: %s\n", output);
        printf("input : %s\n", hexstring);
    }
    free(output);
    
    byteBuffer outbuf = mallocByteBuffer(64);
    outbuf->len = CCBigNumToData(&status, num1, outbuf->bytes);
    ok(status == 0, "Value retrieved 2");
    
    ok(bytesAreEqual(bb, outbuf), "input == output");
    free(bb);
    free(outbuf);
    CCBigNumFree(num1);

    return 0;
    
}
static int test_oneshot(const struct ccdigest_info *di, test_vector *vector) {
    uint8_t answer[vector->result_len];
    byteBuffer salt = hexStringToBytes(vector->saltStr);
    ccpbkdf2_hmac(di, strlen(vector->password), vector->password, salt->len, salt->bytes, vector->iterations, vector->result_len, answer);
    ok(test_answer(di, vector, vector->result_len, answer), "check answer");
    free(salt);
    return 1;
}
Exemple #11
0
int main(int argc, char* argv[])
{
	if(argc!=5)
	{
		printf("Invalid number of arguments.\n");
		return 1;
	}
	if(strlen(argv[1])!=16){
		printf("Invalid upper key length.\n");
		return 2;
	}
	if(strlen(argv[2])!=16){
		printf("Invalid lower key length.\n");
		return 3;
	}
	if(strlen(argv[3])!=16){
		printf("Invalid plaintext length.\n");
		return 4;
	}
	if(!isHexNumber(argv[1])||!isHexNumber(argv[2])){
		printf("Invalid key format.\n");
		return 5;
	}
	if(!isHexNumber(argv[3]))
	{
		printf("Invalid plaintext format.\n");
		return 6;
	}
	if(!isNumber(argv[4]))
	{
		printf("Invalid input for number of iterations.");
		return 7;
	}
	uint8_t keyBytes[16];
	uint64_t subkeys[101];
	uint8_t plaintextBytes[8];
	hexStringToBytes(keyBytes, argv[1], strlen(argv[1]));
	hexStringToBytes(keyBytes+8, argv[2], strlen(argv[2]));
	hexStringToBytes(plaintextBytes, argv[3], strlen(argv[3]));
	
	uint64_t numIterations = toLL(argv[4]);
	generateSubkeys(keyBytes, subkeys);
	printf("%016llx\n", encrypt(join(plaintextBytes), numIterations, subkeys));
	return 0;
}
Exemple #12
0
Hash stringToHash(const std::string& in)
	{
	lassert(in.size() == sizeof(Hash) * 2);

	Hash tr;

	hexStringToBytes((unsigned char*)in.c_str(), (unsigned char*)&tr, in.size());

	return tr;
	}
Exemple #13
0
static int test_discreet(const struct ccmode_cbc *cbc, char *mode_name, test_vector *vector) {

    uint8_t answer[CMAC_BLOCKSIZE];
    uint8_t ctxfrontguard[4096];
    cccmac_mode_decl(cbc, cmac);
    uint8_t ctxrearguard[4096];
    memset(ctxfrontguard, 0xee, 4096);
    memset(ctxrearguard, 0xee, 4096);
    
    byteBuffer key = hexStringToBytes(vector->keyStr);
    byteBuffer in = hexStringToBytes(vector->inStr);
    size_t nblocks = in->len/CMAC_BLOCKSIZE;
    size_t partial = in->len%CMAC_BLOCKSIZE;
    uint8_t *data = in->bytes;
    
    if(nblocks < 2) nblocks = 0; // must have >= 1 block for final
    else if(!partial) nblocks--; // have to have data for final
    cccmac_init(cbc, cmac, key->bytes);
    ok(guard_ok(ctxfrontguard, 0xee, 4096), "context is safe");
    ok(guard_ok(ctxrearguard, 0xee, 4096), "context is safe");
    byteBuffer correct_answer_k1 = hexStringToBytes(vector->k1Str);
    byteBuffer correct_answer_k2 = hexStringToBytes(vector->k2Str);
    byteBuffer answer_k1 = bytesToBytes(cccmac_k1(cmac), 16);
    byteBuffer answer_k2 = bytesToBytes(cccmac_k2(cmac), 16);
    showBytesAreEqual(correct_answer_k1, answer_k1, "Subkey K1 is correct");
    showBytesAreEqual(correct_answer_k2, answer_k2, "Subkey K2 is correct");

    for(size_t i=0; i<nblocks; i++) {
        cccmac_block_update(cbc, cmac, 1, data);
        data+=CMAC_BLOCKSIZE;
    }
    ok(guard_ok(ctxfrontguard, 0xee, 4096), "context is safe");
    ok(guard_ok(ctxrearguard, 0xee, 4096), "context is safe");
    
    cccmac_final(cbc, cmac, in->len - nblocks * CMAC_BLOCKSIZE, data, answer);
    
    ok(guard_ok(ctxfrontguard, 0xee, 4096), "context is safe");
    ok(guard_ok(ctxrearguard, 0xee, 4096), "context is safe");
    ok(test_answer(mode_name, vector, answer, "discreet calls"), "check answer");
    return 1;
}
Exemple #14
0
int cchkdftest(TM_UNUSED int argc, TM_UNUSED char *const *argv) {
	size_t i, n;
	int err;
	
	plan_tests(10 * 2);
	
	if(verbose) diag("Starting hkdf tests\n");
	
	n = sizeof(hkdf_sha256_tests) / sizeof(*hkdf_sha256_tests);
	for(i = 0; i < n; ++i) {
		const test_vector_t *			tv   = &hkdf_sha256_tests[ i ];
		byteBuffer						ikm  = hexStringToBytes(tv->ikm);
		byteBuffer						salt = hexStringToBytes(tv->salt);
		byteBuffer						info = hexStringToBytes(tv->info);
		byteBuffer						okmActual = mallocByteBuffer(tv->len);
		byteBuffer						okmExpected = hexStringToBytes(tv->okm);
		const struct ccdigest_info *	di;
		
		if(     tv->type == type_sha1)   di = ccsha1_di();
		else if(tv->type == type_sha256) di = ccsha256_di();
		else if(tv->type == type_sha512) di = ccsha512_di();
		else abort();
		
		err = cchkdf(di, ikm->len, ikm->bytes, salt->len, salt->bytes, info->len, info->bytes, 
			okmActual->len, okmActual->bytes);
		ok(!err, "check return value");
		ok(bytesAreEqual(okmActual, okmExpected), "compare memory of answer");
		
		free(ikm);
		free(salt);
		free(info);
		free(okmActual);
		free(okmExpected);
	}
	return 0;
}
Exemple #15
0
static int test_answer(char *mode_name, test_vector *vector, void*answer, char *test_type) {
    byteBuffer answer_bb = bytesToBytes(answer, CMAC_BLOCKSIZE);
    if(vector->outStr == NULL) {
        diag("/* CMAC-128 test %d */", vector->cnt);
        diag("\t\t\"%s\",\n", bytesToHexString(answer_bb));
        return 1;
    }
    byteBuffer correct_answer_bb = hexStringToBytes((char *) vector->outStr);
    ok(bytesAreEqual(correct_answer_bb, answer_bb), "compare memory of answer");
    if(bytesAreEqual(correct_answer_bb, answer_bb) == 0) {
        diag("Failed Test (%d) for CMAC-128-%s %s\n", vector->cnt, mode_name, test_type);
        printByteBuffer(correct_answer_bb, "Correct Answer");
        printByteBuffer(answer_bb, "Provided Answer");
    }
    free(correct_answer_bb);
    free(answer_bb);
    return 1;
}
Exemple #16
0
static int tests_rng(const char *seed) {
    byteBuffer entropyBuffer;
    int status=-1; // Allocation error;

    if (seed==NULL || strlen(seed)<=0) {
        // If the seed is not in the argument, we generate one
        struct ccrng_system_state system_rng;
        size_t entropy_size=16; // Default size of the seed
        cc_require((entropyBuffer=mallocByteBuffer(entropy_size))!=NULL,errOut);
        cc_require((status=ccrng_system_init(&system_rng))==0, errOut);
        cc_require((status=ccrng_generate((struct ccrng_state *)&system_rng, entropyBuffer->len, entropyBuffer->bytes))==0, errOut);
        ccrng_system_done(&system_rng);
        cc_print("random seed value:",entropyBuffer->len,entropyBuffer->bytes);
    } else {
        // Otherwise, take the value from the arguments
        entropyBuffer = hexStringToBytes(seed);
        cc_print("input seed value:",entropyBuffer->len,entropyBuffer->bytes);
    }
    cc_require((status=ccrng_test_init(&test_rng, entropyBuffer->len,entropyBuffer->bytes))==0, errOut);
    return status;
errOut:
    printf("Error initializing test rng: %d\n",status);
    return -1;
}
Exemple #17
0
void
request_work(char * url){
    char *init_resp;
    json_t *json_resp;
    json_error_t json_error;
    json_t *data_error = NULL, *result = NULL, *data = NULL, *target = NULL, *midstate = NULL;

    init_resp = request(url, req);
    if(!init_resp){
        die("initial repsonse failed check args");
    }

    json_resp = json_loads(init_resp, 0, &json_error);

    if(!json_resp){
        json_die(json_error.line, json_error.text);
    }

    data_error = json_object_get(json_resp, "error");

    json_data_error(json_integer_value(data_error), init_resp);

    //{"error": null, 
    //  "id": "curltest",
    //  "result":
    //  {"hash1": "00000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000010000",
    //    "data": "
    //000000029b39574cb8a5c25e94cdd844f7d3b942384af65fb264d5a000000000
    //000000008adb353c754fe07c40341728c5efe6e3782d994e0e3ebcb4879106de
    //94dd1db0533b2c461900db990000000000000080000000000000000000000000
    //0000000000000000000000000000000000000000000000000000000080020000",
    //    "target": "0000000000000000000000000000000000000000000000000000ffff00000000", 
    //    "midstate": "49bc9ada38ba6b43814a3275edfa09b796be70080d5c641d32b80776aef13f78"}
    //}

    result = json_object_get(json_resp, "result");
    data = json_object_get(result, "data");
    target = json_object_get(result, "target");
    midstate = json_object_get(result, "midstate");

    // printf("%s\n", json_string_value(midstate));

    if(!result || !data || !target || !midstate){
        fprintf(stderr, "%s\n", init_resp);
        die("initial repsonse format error");
    }

    //prefered that data is sent as big endien
    // data is in little endien hex format
    // printf("%s\n", json_string_value(data));
    // data must be back through the net work as little endien
    // data must be converted from string representation to bits
    
    //data_write((char *)json_string_value(data));
    
uint8_t *data_bytes = hexStringToBytes(endian_flip_32_bit_chunks(json_string_value(data)));
uint8_t *midstate_bytes = hexStringToBytes(endian_flip_32_bit_chunks(json_string_value(midstate)));
	
//    uint8_t *data_bytes = hexStringToBytes(endian_flip_32_bit_chunks(data_test));
//    uint8_t *midstate_bytes = hexStringToBytes(endian_flip_32_bit_chunks(midstate_test));
	
    uint8_t header_buffer[sizeof(data_bytes)+sizeof(midstate_bytes)];
    memcpy(header_buffer, midstate_bytes, sizeof(midstate_bytes));
    memcpy(header_buffer+sizeof(midstate_bytes), data_bytes, sizeof(data_bytes)); 

    write_segments(header_buffer);
    print_segment_info();

    //used for error printing
    printf("%s\n", init_resp); //for testing

    json_decref(json_resp);
    free(init_resp);

    // !! create thread for listening for success from miners
    // upon success send a proof of work to the network with params set to solution
    // eg. {"method":"getwork","params":["0000000141a0e898cf6554fd344a37b2917a6c7a6561c20733b09c8000009eef00000000d559e21 882efc6f76bbfad4cd13639f4067cd904fe4ecc3351dc9cc5358f1cd54db84e7a1b00b5acba97b6 0400000080000000000000000000000000000000000000000000000000000000000000000000000 0000000000080020000"],"id":1}
    // data must be back through the net work as little endien

}
void MoonlightInstance::HandleStartStream(int32_t callbackId, pp::VarArray args) {
    std::string host = args.Get(0).AsString();
    std::string width = args.Get(1).AsString();
    std::string height = args.Get(2).AsString();
    std::string fps = args.Get(3).AsString();
    std::string bitrate = args.Get(4).AsString();
    std::string rikey = args.Get(5).AsString();
    std::string rikeyid = args.Get(6).AsString();
    std::string appversion = args.Get(7).AsString();

    pp::Var response("Setting stream width to: " + width);
    PostMessage(response);
    response = ("Setting stream height to: " + height);
    PostMessage(response);
    response = ("Setting stream fps to: " + fps);
    PostMessage(response);
    response = ("Setting stream host to: " + host);
    PostMessage(response);
    response = ("Setting stream bitrate to: " + bitrate);
    PostMessage(response);
    response = ("Setting rikey to: " + rikey);
    PostMessage(response);
    response = ("Setting rikeyid to: " + rikeyid);
    PostMessage(response);
    response = ("Setting appversion to: " + appversion);
    PostMessage(response);

    // Populate the stream configuration
    LiInitializeStreamConfiguration(&m_StreamConfig);
    m_StreamConfig.width = stoi(width);
    m_StreamConfig.height = stoi(height);
    m_StreamConfig.fps = stoi(fps);
    m_StreamConfig.bitrate = stoi(bitrate); // kilobits per second
    m_StreamConfig.streamingRemotely = 0;
    m_StreamConfig.audioConfiguration = AUDIO_CONFIGURATION_STEREO;

    // The overhead of receiving a packet is much higher in NaCl because we must
    // pass through various layers of abstraction on each recv() call. We're using a
    // higher than normal default video packet size here to reduce CPU cycles wasted
    // receiving packets. The possible cost is greater network losses.
    m_StreamConfig.packetSize = 1392;

    // Load the rikey and rikeyid into the stream configuration
    hexStringToBytes(rikey.c_str(), m_StreamConfig.remoteInputAesKey);
    int rikeyiv = htonl(stoi(rikeyid));
    memcpy(m_StreamConfig.remoteInputAesIv, &rikeyiv, sizeof(rikeyiv));

    // Store the parameters from the start message
    m_Host = host;
    m_AppVersion = appversion;

    // Initialize the rendering surface before starting the connection
    if (InitializeRenderingSurface(m_StreamConfig.width, m_StreamConfig.height)) {
        // Start the worker thread to establish the connection
        pthread_create(&m_ConnectionThread, NULL, MoonlightInstance::ConnectionThreadFunc, this);
    } else {
        // Failed to initialize renderer
        OnConnectionStopped(0);
    }

    pp::VarDictionary ret;
    ret.Set("callbackId", pp::Var(callbackId));
    ret.Set("type", pp::Var("resolve"));
    ret.Set("ret", pp::VarDictionary());
    PostMessage(ret);
}
int CommonEC(int argc, char *const *argv) {
	CCCryptorStatus retval;
    size_t keysize;
    CCECCryptorRef publicKey, privateKey;
    CCECCryptorRef publicKey2;
    // byteBuffer keydata, dekeydata;
    byteBuffer hash;
    char encryptedKey[8192];
    size_t encryptedKeyLen = 8192;
    // char decryptedKey[8192];
    // size_t decryptedKeyLen = 8192;
    char signature[8192];
    size_t signatureLen = 8192;
    char importexport[8192];
    size_t importexportLen = 8192;
    uint32_t valid;
    int accum = 0;
    int debug = 0;
    
	plan_tests(kTestTestCount);
    
    keysize = 256;
    
    retval = CCECCryptorGeneratePair(keysize, &publicKey, &privateKey);
    if(debug) printf("Keys Generated\n");
    ok(retval == 0, "Generate an EC Key Pair");
	accum |= retval;

#ifdef ECDH
    keydata = hexStringToBytes("000102030405060708090a0b0c0d0e0f");
    
    retval = CCECCryptorWrapKey(publicKey, keydata->bytes, keydata->len, encryptedKey, &encryptedKeyLen, kCCDigestSHA1);
    
    ok(retval == 0, "Wrap Key Data with EC Encryption - ccPKCS1Padding");
    accum |= retval;
    
    retval = CCECCryptorUnwrapKey(privateKey, encryptedKey, encryptedKeyLen,
                        decryptedKey, &decryptedKeyLen);
    
    ok(retval == 0, "Unwrap Key Data with EC Encryption - ccPKCS1Padding");
    accum |= retval;

	dekeydata = bytesToBytes(decryptedKey, decryptedKeyLen);
    
	ok(bytesAreEqual(dekeydata, keydata), "Round Trip CCECCryptorWrapKey/CCECCryptorUnwrapKey");
    accum |= retval;
#endif

    
    hash = hexStringToBytes("000102030405060708090a0b0c0d0e0f");

    retval = CCECCryptorSignHash(privateKey, 
                     hash->bytes, hash->len,
                     signature, &signatureLen);
                     
    ok(retval == 0, "EC Signing");
    valid = 0;
    accum |= retval;
    if(debug) printf("Signing Complete\n");
    
    retval = CCECCryptorVerifyHash(publicKey,
                       hash->bytes, hash->len, 
                       signature, signatureLen, &valid);
    ok(retval == 0, "EC Verifying");
    accum |= retval;
	ok(valid, "EC Validity");
    accum |= retval;
    if(debug) printf("Verify Complete\n");
   
    // Mess with the sig - see what happens
    signature[signatureLen-3] += 3;
    retval = CCECCryptorVerifyHash(publicKey,
                                   hash->bytes, hash->len, 
                                   signature, signatureLen, &valid);
    ok(retval == 0, "EC Verifying");
    accum |= retval;
	ok(!valid, "EC Invalid Signature");
    accum |= retval;
    
    if(debug) printf("Verify2 Complete\n");
    
    encryptedKeyLen = 8192;
	retval = CCECCryptorExportPublicKey(publicKey, importexport, &importexportLen);
    
    ok(retval == 0, "EC Export Public Key");
    accum |= retval;

    retval = CCECCryptorImportPublicKey(importexport, importexportLen, &publicKey2);
    
    ok(retval == 0, "EC Import Public Key");
    accum |= retval;
                          
	encryptedKeyLen = 8192;
    retval = CCECCryptorComputeSharedSecret(privateKey, publicKey, encryptedKey, &encryptedKeyLen);

    ok(retval == 0, "EC Shared Secret");
    accum |= retval;

    return accum;
}
Exemple #20
0
int main()
{
	char data[1024];
	char *buf[8];	//目前有8行数据,指针数组,每一个数组元素都指向一行字符串
	FILE *fp;
	int index = 0;
	int line = 0;
	int i;

	//g_ARR_A0
	if((fp = fopen("/home/work/1.cfg", "a+")) == NULL)
	{
		perror("write2file");
		return -1;
	}

	while(fgets(data, 1024, fp) != NULL)
	{
		for(i = 0; i < strlen(data); i++)
		{
			if(data[i] == '\r' || data[i] == '\n' || data[i] == '#')
			{
				data[i] = '\0';
				break;
			}
		}
		printf("strlen[data]: %d, fgets: %s\n", strlen(data), data);
		printf("index: %d, line: %d\n", index, line);
		if(line > 0)
		{
			buf[index] = malloc(strlen(data) + 1);
			strcpy(buf[index], data);
			str_trim(buf[index]);
			printf("buf[%d]: %s\n", index, buf[index]);

			line--;
			index++;
		}
		if(strcmp(data, "A0:") == 0){
			line = 1;
		}
		if(strcmp(data, "A1:") == 0){
			line = 1;
		}
		if(strcmp(data, "A2:") == 0){
			line = 2;
		}
		if(strcmp(data, "A3:") == 0){
			line = 2;
		}
		if(strcmp(data, "A4:") == 0){
			line = 1;
		}
		if(strcmp(data, "A5:") == 0){
			line = 1;
		}
	}

	fclose(fp);

	printf("result: \n");
	for(i = 0; i < 8; i++)
	{
		printf("%s\n", buf[i]);
	}

	
	//心跳间隔数组
	hexStringToBytes(buf[0], g_ARR_A0);


	//心跳内容数组,数字+普通字符(ID+车站名)
	char res[64];
	str_slice(buf[1], 0, 6, res);
	//AS,SS赋值
	hexStringToBytes(res, g_ARR_A1);
	//ID,车站名
	str_slice(buf[1], 6, strlen(buf[1]), res);
	i = 0;
	while(res[i] != '\0')
	{
		g_ARR_A1[i + 3] = res[i];
		i++;
	}

	//二维数组
	hexStringToBytes(buf[2], g_ARR_A2[0]);
	hexStringToBytes(buf[3], g_ARR_A2[1]);
	//二维数组
	hexStringToBytes(buf[4], g_ARR_A3[0]);
	hexStringToBytes(buf[5], g_ARR_A3[1]);

	//两路can的控制参数
	hexStringToBytes(buf[6], g_ARR_A4);
	hexStringToBytes(buf[7], g_ARR_A5);

	/*u8 g_ARR_A0[2];		//心跳间隔,初始值
	u8 g_ARR_A1[64];	//心跳帧内容初始值
	u8 g_ARR_A2[2][64];	//CAN1,设备列表
	u8 g_ARR_A3[2][64];	//CAN2,设备列表
	u8 g_ARR_A4[4];		//CAN1, 设备控制参数初始值
	u8 g_ARR_A5[4];		//CAN2,设备控制参数初始值*/
	
	printf("g_ARR_A0: ");
	print_arr(g_ARR_A0, 2);
	printf("g_ARR_A1: ");
	print_arr(g_ARR_A1, 64);
	printf("g_ARR_A4: ");
	print_arr(g_ARR_A4, 4);
	printf("g_ARR_A5: ");
	print_arr(g_ARR_A5, 4);

	return 0;
}
Exemple #21
0
static uint32_t executePRNG_TestVector(PRNG_Vector vector, uint32_t idx)
{
	uint32_t result = TC_PASS;
	uint8_t * entropy    = hexStringToBytes(vector.entropyString);
	uint32_t  entropylen = strlen(vector.entropyString) / 2U;

	uint8_t * expected    = hexStringToBytes(vector.expectedString);
	uint32_t  expectedlen = strlen(vector.expectedString) / 2U;

	uint8_t * personalization   = 0;
	uint32_t  plen              = 0U;

	uint8_t * additional_input1 = 0;
	uint32_t  additionallen1    = 0U;

	uint8_t * additional_input2 = 0;
	uint32_t  additionallen2    = 0U;

	uint8_t * output = (uint8_t *)malloc(expectedlen);

	uint32_t i;
	TCCtrPrng_t ctx;

	if (0 != vector.personalizationString)
	{
		personalization = hexStringToBytes(vector.personalizationString);
		plen = strlen(vector.personalizationString) / 2U;
	}

	if (0 != vector.additionalInputString1)
	{
		additional_input1 = hexStringToBytes(vector.additionalInputString1);
		additionallen1 = strlen(vector.additionalInputString1) / 2U;
	}

	if (0 != vector.additionalInputString2)
	{
		additional_input2 = hexStringToBytes(vector.additionalInputString2);
		additionallen2 = strlen(vector.additionalInputString2) / 2U;
	}

	(void)tc_ctr_prng_init(&ctx, entropy, entropylen, personalization, plen);

	(void)tc_ctr_prng_generate(&ctx, additional_input1, additionallen1, output, expectedlen);
	(void)tc_ctr_prng_generate(&ctx, additional_input2, additionallen2, output, expectedlen);

	for (i = 0U; i < expectedlen; i++)
	{
		if (output[i] != expected[i])
		{
			TC_ERROR("CTR PRNG test #%d failed\n", idx);
			result = TC_FAIL;
			break;
		}
	}

	free(entropy);
	free(expected);
	free(personalization);
	free(additional_input1);
	free(additional_input2);
	free(output);

	return result;
}