void sha256_str(const char *string, char out[65]) { unsigned char hash[SHA256_DIGEST_LENGTH]; SHA256_CTX sha256; SHA256_Init(&sha256); SHA256_Update(&sha256, string, strlen(string)); SHA256_Final(hash, &sha256); sha256_hash(hash, out); }
static int scryptenc_setup(uint8_t header[96], uint8_t dk[64], const uint8_t * passwd, size_t passwdlen, size_t maxmem, double maxmemfrac, double maxtime) { uint8_t salt[32]; uint8_t hbuf[32]; int logN; uint64_t N; uint32_t r; uint32_t p; SHA256_CTX ctx; uint8_t * key_hmac = &dk[32]; HMAC_SHA256_CTX hctx; int rc; /* Pick values for N, r, p. */ if ((rc = pickparams(maxmem, maxmemfrac, maxtime, &logN, &r, &p)) != 0) return (rc); N = (uint64_t)(1) << logN; /* Get some salt. */ if ((rc = getsalt(salt)) != 0) return (rc); /* Generate the derived keys. */ if (crypto_scrypt(passwd, passwdlen, salt, 32, N, r, p, dk, 64)) return (3); /* Construct the file header. */ memcpy(header, "scrypt", 6); header[6] = 0; header[7] = logN; be32enc(&header[8], r); be32enc(&header[12], p); memcpy(&header[16], salt, 32); /* Add header checksum. */ SHA256_Init(&ctx); SHA256_Update(&ctx, header, 48); SHA256_Final(hbuf, &ctx); memcpy(&header[48], hbuf, 16); /* Add header signature (used for verifying password). */ HMAC_SHA256_Init(&hctx, key_hmac, 32); HMAC_SHA256_Update(&hctx, header, 64); HMAC_SHA256_Final(hbuf, &hctx); memcpy(&header[64], hbuf, 32); /* Success! */ return (0); }
/* * Applies sha256 using the given context and input/length, and returns * a double in the range [0...1[ based on the hash. */ static double vdi_random_sha(const char *input, ssize_t len) { struct SHA256Context ctx; uint8_t sign[SHA256_LEN]; AN(input); SHA256_Init(&ctx); SHA256_Update(&ctx, input, len); SHA256_Final(sign, &ctx); return (vle32dec(sign) / exp2(32)); }
static void crypt_all(int count) { int index = 0; #ifdef _OPENMP #pragma omp parallel for for (index = 0; index < count; index++) #endif { SHA256_CTX ctx; int i; SHA256_Init(&ctx); SHA256_Update(&ctx, saved_key[index], strlen(saved_key[index])); SHA256_Update(&ctx, cur_salt->salt, 32); SHA256_Final((unsigned char*)crypt_out[index], &ctx); for(i = 0; i <= cur_salt->iterations; i++) { SHA256_Init(&ctx); SHA256_Update(&ctx, (unsigned char*)crypt_out[index], 32); SHA256_Final((unsigned char*)crypt_out[index], &ctx); } } }
static gboolean hash_stream(FILE *stream, uint8_t *hash, GError **error) { uint8_t buf[1024]; SHA256_CTX ctx; gboolean ret = TRUE; if (!SHA256_Init(&ctx)) { g_set_error(error, CRYPT_ERROR, CRYPT_ERROR_INIT, "Failed to initialise an SHA256 context"); ret = FALSE; } else { int final_result; while (TRUE) { size_t got = fread(buf, 1, sizeof(buf), stream); if (!SHA256_Update(&ctx, buf, got)) { g_set_error(error, CRYPT_ERROR, CRYPT_ERROR_HASH, "Error calculating the SHA256 hash"); ret = FALSE; } else if (got != sizeof(buf)) { if (ferror(stream)) { g_set_error_literal(error, G_FILE_ERROR, g_file_error_from_errno(errno), strerror(errno)); ret = FALSE; } break; } } /* I think we have to call this regardless of whether there was * an error in order to clear up the resources */ final_result = SHA256_Final((unsigned char *)hash, &ctx); if (!final_result && ret) { g_set_error(error, CRYPT_ERROR, CRYPT_ERROR_HASH, "Error calculating the SHA256 hash"); ret = FALSE; } } return ret; }
unsigned char *SHA224(const unsigned char *d, size_t n, unsigned char *md) { SHA256_CTX c; static unsigned char m[SHA224_DIGEST_LENGTH]; if (md == NULL) md=m; SHA224_Init(&c); SHA256_Update(&c,d,n); SHA256_Final(md,&c); OPENSSL_cleanse(&c,sizeof(c)); return(md); }
char* SHA256FromHash(ArrayOfHash *array) { unsigned char* hash = malloc(SHA256_DIGEST_LENGTH); SHA256_CTX sha256; SHA256_Init(&sha256); int i; for(i = 0; i < array->size; i++) { SHA256_Update(&sha256, array->arrayOfHash[i], array->sizeBlock); } SHA256_Final(hash, &sha256); return hash; }
/* *Register */ int register_user(packet *in_pkt, int fd) { int i = 0; char *args[16]; char cpy[BUFFERSIZE]; char *tmp = cpy; strcpy(tmp, in_pkt->buf); args[i] = strsep(&tmp, " \t"); while ((i < sizeof(args) - 1) && (args[i] != '\0')) { args[++i] = strsep(&tmp, " \t"); } // Check there are enough arguements to safely inspect them if (i > 3) { // Ensure requested username is valid if (!validUsername(args[1], fd)) { return 0; } // Check if the requested username is unique if(strcmp(get_real_name(®istered_users_list, args[1], registered_users_mutex), "ERROR") !=0 || \ !(strcmp(SERVER_NAME, args[1])) || \ strcmp(args[2], args[3]) != 0) { sendError("Username unavailable.", fd); return 0; } // Ensure password requested is valid if (!validPassword(args[2], args[3], fd)) { return 0; } // Allocate memory space for new user node, populate node with new user data User *user = (User *)malloc(sizeof(User)); strcpy(user->username, args[1]); strcpy(user->real_name, args[1]); // Hash password SHA256_CTX sha256; SHA256_Init(&sha256); SHA256_Update(&sha256, args[2], strlen(args[2])); SHA256_Final(user->password, &sha256); user->sock = fd; user->next = NULL; // Insert user as registered user, write new user data to file insertUser(®istered_users_list, user, registered_users_mutex); writeUserFile(®istered_users_list, USERS_FILE, registered_users_mutex); // Reform packet as valid login, pass new user data to login memset(&in_pkt->buf, 0, sizeof(in_pkt->buf)); sprintf(in_pkt->buf, "/login %s %s", args[1], args[2]); return login(in_pkt, fd); } // There were not enough arguements received to correctly read them else { printf("%s --- %sError:%s Malformed reg packet received from %s on %d, ignoring.\n", \ WHITE, RED, NORMAL, args[1], fd); } return 0; }
void read_bitcoin_transaction(struct space *space, struct bitcoin_transaction *trans, struct file *f, off_t *poff) { size_t i; off_t start = *poff; SHA256_CTX sha256; trans->version = pull_u32(f, poff); trans->input_count = pull_varint(f, poff); trans->input = space_alloc_arr(space, struct bitcoin_transaction_input, trans->input_count); for (i = 0; i < trans->input_count; i++) read_input(space, f, poff, trans->input + i); trans->output_count = pull_varint(f, poff); trans->output = space_alloc_arr(space, struct bitcoin_transaction_output, trans->output_count); for (i = 0; i < trans->output_count; i++) read_output(space, f, poff, trans->output + i); trans->lock_time = pull_u32(f, poff); /* Bitcoin uses double sha (it's not quite known why...) */ SHA256_Init(&sha256); if (likely(f->mmap)) { SHA256_Update(&sha256, f->mmap + start, *poff - start); } else { u8 *buf = tal_arr(NULL, u8, *poff - start); file_read(f, start, *poff - start, buf); SHA256_Update(&sha256, buf, *poff - start); tal_free(buf); } SHA256_Final(trans->sha256, &sha256); SHA256_Init(&sha256); SHA256_Update(&sha256, trans->sha256, sizeof(trans->sha256)); SHA256_Final(trans->sha256, &sha256); trans->len = *poff - start; }
void Identity::generate() { delete [] _keyPair; // Generate key pair and derive address do { _keyPair = new EllipticCurveKeyPair(); _keyPair->generate(); _address = deriveAddress(_keyPair->pub().data(),_keyPair->pub().size()); } while (_address.isReserved()); _publicKey = _keyPair->pub(); // Sign address, key type, and public key with private key (with a zero // byte between each field). Including this extra data means simply editing // the address of an identity will be detected as its signature will be // invalid. Of course, deep verification of address/key relationship is // required to cover the more elaborate address claim jump attempt case. SHA256_CTX sha; unsigned char dig[32]; unsigned char idtype = IDENTITY_TYPE_NIST_P_521,zero = 0; SHA256_Init(&sha); SHA256_Update(&sha,_address.data(),ZT_ADDRESS_LENGTH); SHA256_Update(&sha,&zero,1); SHA256_Update(&sha,&idtype,1); SHA256_Update(&sha,&zero,1); SHA256_Update(&sha,_publicKey.data(),_publicKey.size()); SHA256_Update(&sha,&zero,1); SHA256_Final(dig,&sha); _signature = _keyPair->sign(dig); }
transform_key(char *PASSWORD, final_key) { // First, hash the PASSWORD SHA256_CTX ctx; AES_KEY akey; SHA256_Init(&ctx); SHA256_Update(&ctx, PASSWORD, strlen(PASSWORD)); SHA256_Final(hash, &ctx); if(version == 2) { /* 2.x database */ SHA256_Init(&ctx); SHA256_Update(&ctx, hash, 32); SHA256_Final(hash, &ctx); } AES_set_encrypt_key(TRS, 256, &akey); // Next, encrypt the created hash for(i = 0; i < ITERATIONSl; i++) { AES_encrypt(hash, hash, &akey); AES_encrypt(hash+16, hash+16, &akey); } // Finally, hash it again... SHA256_Init(&ctx); SHA256_Update(&ctx, hash, 32); SHA256_Final(hash, &ctx); // and hash the result together with the Final Random Seed SHA256_Init(&ctx); if(version == 1) { SHA256_Update(&ctx, FRS, 16); } else { SHA256_Update(&ctx, FRS, 32); } SHA256_Update(&ctx, hash, 32); SHA256_Final(final_key, &ctx); }
static int scryptdec_setup(const uint8_t header[96], uint8_t dk[64], const uint8_t * passwd, size_t passwdlen, size_t maxmem, double maxmemfrac, double maxtime) { uint8_t salt[32]; uint8_t hbuf[32]; int logN; uint32_t r; uint32_t p; uint64_t N; SHA256_CTX ctx; uint8_t * key_hmac = &dk[32]; HMAC_SHA256_CTX hctx; int rc; /* Parse N, r, p, salt. */ logN = header[7]; r = be32dec(&header[8]); p = be32dec(&header[12]); memcpy(salt, &header[16], 32); /* Verify header checksum. */ SHA256_Init(&ctx); SHA256_Update(&ctx, header, 48); SHA256_Final(hbuf, &ctx); if (memcmp(&header[48], hbuf, 16)) return (7); /* * Check whether the provided parameters are valid and whether the * key derivation function can be computed within the allowed memory * and CPU time. */ if ((rc = checkparams(maxmem, maxmemfrac, maxtime, logN, r, p)) != 0) return (rc); /* Compute the derived keys. */ N = (uint64_t)(1) << logN; if (crypto_scrypt(passwd, passwdlen, salt, 32, N, r, p, dk, 64)) return (3); /* Check header signature (i.e., verify password). */ HMAC_SHA256_Init(&hctx, key_hmac, 32); HMAC_SHA256_Update(&hctx, header, 64); HMAC_SHA256_Final(hbuf, &hctx); if (memcmp(hbuf, &header[64], 32)) return (11); /* Success! */ return (0); }
// Deprecated on OSX... figure out the proper thing with their internal lib later... // Using technique from http://stackoverflow.com/questions/13784434/gcc-use-openssls-sha256-functions inline std::string sha256(std::string str) { unsigned char hbuf[SHA256_DIGEST_LENGTH]; std::stringstream ss; SHA256_CTX h; SHA256_Init(&h); SHA256_Update(&h, str.c_str(), str.size()); SHA256_Final(hbuf, &h); for(int i = 0; i < SHA256_DIGEST_LENGTH; i++) { ss << std::hex << std::setw(2) << std::setfill('0') << (int)hbuf[i]; } return ss.str(); };
void hash(char *string, char *result) { unsigned char hash[SHA256_DIGEST_LENGTH]; int i = 0; SHA256_CTX handler; SHA256_Init(&handler); SHA256_Update(&handler, string, strlen(string)); SHA256_Final(hash, &handler); memset(result, '\0', strlen(result)); for (i = 0; i < SHA256_DIGEST_LENGTH; i++) { sprintf(result, "%s%02x", result, hash[i]); }; }
void heavy_hash(void* output, const void* input, int len) { uint32_t hash1[16], hash2[16], hash3[16], hash4[16], hash5[16]; HEFTY1(input, len, (unsigned char *)hash1); /* HEFTY1 is new, so take an extra security measure to eliminate * the possiblity of collisions: * * Hash(x) = SHA256(x + HEFTY1(x)) * * N.B. '+' is concatenation. */ SHA256_CTX sha256; SHA256_Init(&sha256); SHA256_Update(&sha256, input, len); SHA256_Update(&sha256, hash1, sizeof(hash1)); SHA256_Final((unsigned char*)hash2, &sha256); /* Additional security: Do not rely on a single cryptographic hash * function. Instead, combine the outputs of 4 of the most secure * cryptographic hash functions-- SHA256, KECCAK512, GROESTL512 * and BLAKE512. */ sph_keccak512(&ctx.keccak, input, len); sph_keccak512(&ctx.keccak, hash1, sizeof(hash1)); sph_keccak512_close(&ctx.keccak, hash3); sph_groestl512(&ctx.groestl, input, len); sph_groestl512(&ctx.groestl, hash1, sizeof(hash1)); sph_groestl512_close(&ctx.groestl, hash4); sph_blake512(&ctx.blake, input, len); sph_blake512(&ctx.blake, hash1, sizeof(hash1)); sph_blake512_close(&ctx.blake, hash5); combine_hashes((uint32_t *)output, hash2, hash3, hash4, hash5); }
int sha(void* input, unsigned long length, unsigned char* md) { SHA256_CTX context; if(!SHA256_Init(&context)) return 0; if(!SHA256_Update(&context, (unsigned char*)input, length)) return 0; if(!SHA256_Final(md, &context)) return 0; return 1; }
void hss_update_hash_context(int h, union hash_context *ctx, const void *msg, size_t len_msg) { #if ALLOW_VERBOSE if (hss_verbose) { int i; for (i=0; i<len_msg; i++) printf( " %02x", ((unsigned char*)msg)[i] ); } #endif switch (h) { case HASH_SHA256: SHA256_Update(&ctx->sha256, msg, len_msg); break; } }
inline static int pub2hash160(unsigned char *pub_chr) { /* compute hash160 for uncompressed public key */ /* sha256(pub) */ SHA256_Init(sha256_ctx); SHA256_Update(sha256_ctx, pub_chr, 65); SHA256_Final(hash256, sha256_ctx); /* ripemd160(sha256(pub)) */ ripemd160_256(hash256, hash160_uncmp.uc); /* quick and dirty public key compression */ pub_chr[0] = 0x02 | (pub_chr[64] & 0x01); /* compute hash160 for compressed public key */ /* sha256(pub) */ SHA256_Init(sha256_ctx); SHA256_Update(sha256_ctx, pub_chr, 33); SHA256_Final(hash256, sha256_ctx); /* ripemd160(sha256(pub)) */ ripemd160_256(hash256, hash160_compr.uc); return 0; }
void sha256(unsigned char * data_chunks[], unsigned int data_chunck_length[], unsigned char *digest) { SHA256_CTX ctx; SHA256_Init( &ctx); while(*data_chunks) { SHA256_Update(&ctx, *data_chunks, *data_chunck_length); data_chunks++; data_chunck_length++; } SHA256_Final(digest, &ctx); }
static int hash_update( SRP_HashAlgorithm alg, HashCTX *c, const void *data, size_t len ) { switch (alg) { case SRP_SHA1 : return SHA1_Update( &c->sha, data, len ); case SRP_SHA224: return SHA224_Update( &c->sha256, data, len ); case SRP_SHA256: return SHA256_Update( &c->sha256, data, len ); case SRP_SHA384: return SHA384_Update( &c->sha512, data, len ); case SRP_SHA512: return SHA512_Update( &c->sha512, data, len ); default: return -1; } }
static int hast_sha256_checksum(const unsigned char *data, size_t size, unsigned char *hash, size_t *hsizep) { SHA256_CTX ctx; SHA256_Init(&ctx); SHA256_Update(&ctx, data, size); SHA256_Final(hash, &ctx); *hsizep = SHA256_DIGEST_LENGTH; return (0); }
string sha256(const string &str) { unsigned char hash[SHA256_DIGEST_LENGTH]; SHA256_CTX sha256; SHA256_Init(&sha256); SHA256_Update(&sha256, str.c_str(), str.size()); SHA256_Final(hash, &sha256); stringstream ret; for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) { ret << hex << setw(2) << setfill('0') << static_cast<int>(hash[i]); } return ret.str(); }
std::string Security::ShaProvider::CreateSha256(const std::string& data) const { unsigned char hash[SHA256_DIGEST_LENGTH]; SHA256_CTX sha256; SHA256_Init(&sha256); SHA256_Update(&sha256, data.c_str(), data.size()); SHA256_Final(hash, &sha256); HexUtils hexUtils; std::string shaHash = hexUtils.HexToString(hash, SHA256_DIGEST_LENGTH); return shaHash; }
static int verify_file(struct ucred *cred, struct vnode *vp) { char buffer[256]; char hash[SHA256_DIGEST_LENGTH > uECC_BYTES ? SHA256_DIGEST_LENGTH : uECC_BYTES]; char signature[2*uECC_BYTES]; int error, len; ssize_t resid; off_t i, size; SHA256_CTX ctx; struct stat stat; i = 0; error = vn_stat(vp, &stat, cred, NOCRED, curthread); size = stat.st_size; if (error) return (EPERM); len = sizeof(signature); error = vn_extattr_get(vp, IO_NODELOCKED, EXTATTR_NAMESPACE_SYSTEM, "signature", &len, signature, curthread); if (error) return (EPERM); #ifdef DEBUG printf("Signature: "); print_hex(signature, sizeof(signature)); #endif SHA256_Init(&ctx); while(i < size && !error) { len = size - i > sizeof(buffer) ? sizeof(buffer) : size - i; error = vn_rdwr(UIO_READ, vp, buffer, len, i, UIO_SYSSPACE, IO_NODELOCKED, cred, NOCRED, &resid, curthread); SHA256_Update(&ctx, buffer, len); i += len; } if (error) return (EPERM); SHA256_Final(hash, &ctx); #ifdef DEBUG printf("Hash: "); print_hex(hash, sizeof(hash)); #endif if (!uECC_verify(pubkey, hash, signature)) return (EPERM); return (0); }
void genkey(const Memblock &string, uint8_t *key, uint32_t length) const { SHA256_CTX ctx; uint32_t numHashes = (length + SHA256_DIGEST_LENGTH - 1) / SHA256_DIGEST_LENGTH; // TODO: This is not very efficient with multiple hashes for (uint32_t i = 0; i < numHashes; i++) { SHA256_Init(&ctx); for (uint32_t j = 0; j < i; j++) { SHA256_Update(&ctx, "\0", 1); } // Find multiplicator int32_t tl = string.length + 8; int32_t mul = 1; while (mul < tl && ((64 * mul) % tl)) { ++mul; } // Try to feed the hash function with 64-byte blocks const int32_t bs = mul * 64; assert(bs <= KEYBUFFER_LENGTH); uint8_t *bptr = m_keybuf + tl; int32_t n = bs / tl; memcpy(m_keybuf + 8, string.data, string.length); while (n-- > 1) { memcpy(bptr, m_keybuf, tl); bptr += tl; } n = m_count / bs; while (n-- > 0) { SHA256_Update(&ctx, m_keybuf, bs); } SHA256_Update(&ctx, m_keybuf, m_count % bs); SHA256_Final(key + (i * SHA256_DIGEST_LENGTH), &ctx); } }
static int compute_key(char *key, size_t klen, const char *seed, const size_t slen) { SHA256_CTX sha; char buf[VERSION_SIZE]; int len; long long time_ns; char *tmp_key = key; unsigned char results[SHA256_DIGEST_LENGTH]; size_t i; if (!key || !seed || !slen) return -1; if (klen > SHA256_DIGEST_LENGTH * 2 || !klen) return -1; SHA256_Init(&sha); time_ns = get_uptime(); len = snprintf(buf, VERSION_SIZE, "%s%s%lld", gbuildversion, guuid, time_ns); if (s_not_expect(len , VERSION_SIZE)) return -1; SHA256_Update(&sha, (unsigned char *)buf, strnlen(buf, VERSION_SIZE)); SHA256_Update(&sha, (unsigned char *)seed, strnlen(seed, slen)); SHA256_Final(results, &sha); for (i = 0; i < klen / 2; i++) { len = snprintf(tmp_key, 3, "%02x", results[i]); if (s_not_expect(len, 3)) return -1; tmp_key += 2; } *tmp_key = 0; return 0; }
/** * crypto_hash_data_2(key, data0, len0, data1, len1, buf): * Hash the concatenation of two buffers, as in crypto_hash_data. */ int crypto_hash_data_2(int key, const uint8_t * data0, size_t len0, const uint8_t * data1, size_t len1, uint8_t buf[32]) { HMAC_SHA256_CTX hctx; SHA256_CTX ctx; struct crypto_hmac_key * hkey; if (key == CRYPTO_KEY_HMAC_SHA256) { /* Hash the data. */ SHA256_Init(&ctx); SHA256_Update(&ctx, data0, len0); SHA256_Update(&ctx, data1, len1); SHA256_Final(buf, &ctx); /* Clean the stack. */ memset(&ctx, 0, sizeof(SHA256_CTX)); } else { if ((hkey = crypto_keys_lookup_HMAC(key)) == NULL) goto err0; /* Do the HMAC. */ HMAC_SHA256_Init(&hctx, hkey->key, hkey->len); HMAC_SHA256_Update(&hctx, data0, len0); HMAC_SHA256_Update(&hctx, data1, len1); HMAC_SHA256_Final(buf, &hctx); /* Clean the stack. */ memset(&hctx, 0, sizeof(HMAC_SHA256_CTX)); } /* Success! */ return (0); err0: /* Failure! */ return (-1); }
void sha256(char *string, char outputBuffer[65]) { unsigned char hash[SHA256_DIGEST_LENGTH]; SHA256_CTX sha256; SHA256_Init(&sha256); SHA256_Update(&sha256, string, strlen(string)); SHA256_Final(hash, &sha256); int i = 0; for(i = 0; i < SHA256_DIGEST_LENGTH; i++) { sprintf(outputBuffer + (i * 2), "%02x", hash[i]); } outputBuffer[64] = 0; }
void SHA256_Test(void) { struct SHA256Context c; const struct sha256test *p; unsigned char o[32]; for (p = sha256test; p->input != NULL; p++) { SHA256_Init(&c); SHA256_Update(&c, p->input, strlen(p->input)); SHA256_Final(o, &c); assert(!memcmp(o, p->output, 32)); } }
uint8_t *SHA224(const uint8_t *data, size_t len, uint8_t *out) { SHA256_CTX ctx; static uint8_t buf[SHA224_DIGEST_LENGTH]; /* TODO(fork): remove this static buffer. */ if (out == NULL) { out = buf; } SHA224_Init(&ctx); SHA256_Update(&ctx, data, len); SHA256_Final(out, &ctx); OPENSSL_cleanse(&ctx, sizeof(ctx)); return out; }