sha256.cpp 2.15 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
#include <openssl/sha.h>
#include <openssl/evp.h>
#include <stdlib.h>

#include "crypto.h"

int sha256_digest(const uint8_t *p_src, uint32_t src_len, sgx_sha256_hash_t *p_hash) {
    if ((p_src == NULL) || (p_hash == NULL)) {
        return -1;
    }

    if (SHA256((const unsigned char *)p_src, src_len, (unsigned char *)p_hash) == NULL) {
    	return -1;
    }

    return 0;
}

int sha256_init(sha_state_handle_t* p_sha_handle) {
    if (p_sha_handle == NULL) {
        return -1;
    }

    EVP_MD_CTX* evp_ctx = NULL;
    const EVP_MD* sha256_md = NULL;
    sgx_status_t retval = SGX_ERROR_UNEXPECTED;

    do {
	    /* allocates, initializes and returns a digest context */
	    evp_ctx = EVP_MD_CTX_new();
	    if (evp_ctx == NULL) {
			break;
	    }

	    /* return EVP_MD structures for SHA256 digest algorithm */
	    sha256_md = EVP_sha256();
	    if (sha256_md == NULL) {
			break;
	    }

	    /* sets up digest context ctx to use a digest type, if impl is NULL then the default implementation of digest type is used */
	    if (EVP_DigestInit_ex(evp_ctx, sha256_md, NULL) != 1) {
			break;
	    }

	    *p_sha_handle = evp_ctx;
	    retval = SGX_SUCCESS;
    } while(0);

    if (SGX_SUCCESS != retval) {
        if (evp_ctx != NULL) {
            EVP_MD_CTX_free(evp_ctx);
        }
    }

    return retval;
}

int sha256_update(const uint8_t *p_src, uint32_t src_len, sha_state_handle_t sha_handle) {
    if ((p_src == NULL) || (sha_handle == NULL)) {
        return -1;
    }

    if(EVP_DigestUpdate((EVP_MD_CTX*)sha_handle, p_src, src_len) != 1) {
		return -1;
    }

    return 0;
}

int sha256_finish(sha_state_handle_t sha_handle, sgx_sha256_hash_t *p_hash) {
	unsigned int hash_len;
    if ((sha_handle == NULL) || (p_hash == NULL)) {
        return -1;
    }

    if (EVP_DigestFinal_ex((EVP_MD_CTX*)sha_handle, (unsigned char *)p_hash, &hash_len) != 1) {
		return -1;
    }

    if (SGX_SHA256_HASH_SIZE != hash_len) {
		return -1;
    }

    return 0;
}

void sha256_close(sha_state_handle_t sha_handle) {
    if (sha_handle) {
        EVP_MD_CTX_free((EVP_MD_CTX*)sha_handle);
    }
}