ReturnValue BleApiTest_Sign(pBleDevice dev, uint32_t *ctr, int expectedSW12, bool checkOnly,
			 bool corruptKH, bool corruptAddId)
{
	ReturnValue retval;

	U2F_AUTHENTICATE_REQ authReq;
	unsigned char reply[2048];
	unsigned int replyLength = sizeof(reply);
	unsigned char request[256];
	unsigned int requestlen;
	unsigned char replyCmd;

	// pick random challenge and use registered appId.
	for (size_t i = 0; i < sizeof(authReq.nonce); ++i)
		authReq.nonce[i] = rand();
	memcpy(authReq.appId, regReq.appId, sizeof(authReq.appId));
	authReq.keyHandleLen = regRsp.keyHandleLen;
	memcpy(authReq.keyHandle, regRsp.keyHandleCertSig,
	       authReq.keyHandleLen);

	if (corruptKH)
		authReq.keyHandle[0] ^= 0x55;
	if (corruptAddId)
		authReq.appId[0] ^= 0xAA;

	uint64_t t = dev->TimeMs();

	/* prepare register request */
	request[0] = 0x00;
	request[1] = U2F_INS_AUTHENTICATE;
	request[2] = checkOnly ? U2F_AUTH_CHECK_ONLY : U2F_AUTH_ENFORCE;
	request[3] = 0x00;
	request[4] = 0x00;
	request[5] = 0x00;
	request[6] = U2F_NONCE_SIZE + U2F_APPID_SIZE + 1 + authReq.keyHandleLen;
	memcpy(request + 7, reinterpret_cast < char *>(&authReq), request[6]);
	requestlen = 7 + request[6];
	request[requestlen++] = 0x00;
	request[requestlen++] = 0x00;

	/* write command */
	retval =
	    dev->CommandWrite(FIDO_BLE_CMD_MSG, request, requestlen, &replyCmd,
			      reply, &replyLength);
	CHECK_EQ(retval, ReturnValue::BLEAPI_ERROR_SUCCESS);

	if (expectedSW12 != FIDO_RESP_SUCCESS) {
		CHECK_EQ(expectedSW12, bytes2short(reply, replyLength - 2), "Returned error does not match expected value.");
		CHECK_EQ(replyLength, 2, "Returned value does not match expected length.");
		return ReturnValue::BLEAPI_ERROR_SUCCESS;
	}

	CHECK_EQ(replyCmd, FIDO_BLE_CMD_MSG, "Reply is not a FIDO_BLE_CMD_MSG (0x83)");
	CHECK_EQ(FIDO_RESP_SUCCESS, bytes2short(reply, replyLength - 2), "Status code is not FIDO_RESP_SUCCESS (0x9000)");
	CHECK_NE(replyLength, 2, "Reply length is only status code.");
	CHECK_LE(replyLength - 2, sizeof(U2F_AUTHENTICATE_RESP), "Returned authentication response does not match expected length.");

	U2F_AUTHENTICATE_RESP resp;
	memcpy(&resp, reply, replyLength - 2);

	CHECK_EQ(resp.flags, 0x01, "Flags value in authentication response is always 1");

	INFO << "Sign: " << (replyLength - 2) << " bytes in "
	    << ((float)(dev->TimeMs() - t)) / 1000.0 << "s";

	// Parse signature from authenticate response.
	p256_int sig_r, sig_s;
	CHECK_EQ(1, dsa_sig_unpack(resp.sig,
				   replyLength - 2 - sizeof(resp.flags) -
				   sizeof(resp.ctr), &sig_r, &sig_s));

	// Compute hash as integer.
	p256_int h;
	SHA256_CTX sha;
	SHA256_init(&sha);
	SHA256_update(&sha, regReq.appId, sizeof(regReq.appId));	// O
	SHA256_update(&sha, &resp.flags, sizeof(resp.flags));	// T
	SHA256_update(&sha, &resp.ctr, sizeof(resp.ctr));	// CTR
	SHA256_update(&sha, authReq.nonce, sizeof(authReq.nonce));	// d
	p256_from_bin(SHA256_final(&sha), &h);

	// Parse public key from registration response.
	p256_int pk_x, pk_y;
	p256_from_bin(regRsp.pubKey.x, &pk_x);
	p256_from_bin(regRsp.pubKey.y, &pk_y);

	// Verify signature.
	CHECK_EQ(1, p256_ecdsa_verify(&pk_x, &pk_y, &h, &sig_r, &sig_s), "Signature does not match.");

  *ctr = ntohl(resp.ctr);

	return ReturnValue::BLEAPI_ERROR_SUCCESS;
}
// Look for an RSA signature embedded in the .ZIP file comment given
// the path to the zip.  Verify it matches one of the given public
// keys.
//
// Return VERIFY_SUCCESS, VERIFY_FAILURE (if any error is encountered
// or no key matches the signature).
int verify_file(unsigned char* addr, size_t length) {
    //ui->SetProgress(0.0);

    int numKeys;
    Certificate* pKeys = load_keys(PUBLIC_KEYS_FILE, &numKeys);
    if (pKeys == NULL) {
        LOGE("Failed to load keys\n");
        return INSTALL_CORRUPT;
    }
    LOGI("%d key(s) loaded from %s\n", numKeys, PUBLIC_KEYS_FILE);

    // An archive with a whole-file signature will end in six bytes:
    //
    //   (2-byte signature start) $ff $ff (2-byte comment size)
    //
    // (As far as the ZIP format is concerned, these are part of the
    // archive comment.)  We start by reading this footer, this tells
    // us how far back from the end we have to start reading to find
    // the whole comment.

#define FOOTER_SIZE 6

    if (length < FOOTER_SIZE) {
        LOGE("not big enough to contain footer\n");
        return VERIFY_FAILURE;
    }

    unsigned char* footer = addr + length - FOOTER_SIZE;

    if (footer[2] != 0xff || footer[3] != 0xff) {
        LOGE("footer is wrong\n");
        return VERIFY_FAILURE;
    }

    size_t comment_size = footer[4] + (footer[5] << 8);
    size_t signature_start = footer[0] + (footer[1] << 8);
    LOGI("comment is %zu bytes; signature %zu bytes from end\n",
         comment_size, signature_start);

    if (signature_start <= FOOTER_SIZE) {
        LOGE("Signature start is in the footer");
        return VERIFY_FAILURE;
    }

#define EOCD_HEADER_SIZE 22

    // The end-of-central-directory record is 22 bytes plus any
    // comment length.
    size_t eocd_size = comment_size + EOCD_HEADER_SIZE;

    if (length < eocd_size) {
        LOGE("not big enough to contain EOCD\n");
        return VERIFY_FAILURE;
    }

    // Determine how much of the file is covered by the signature.
    // This is everything except the signature data and length, which
    // includes all of the EOCD except for the comment length field (2
    // bytes) and the comment data.
    size_t signed_len = length - eocd_size + EOCD_HEADER_SIZE - 2;

    unsigned char* eocd = addr + length - eocd_size;

    // If this is really is the EOCD record, it will begin with the
    // magic number $50 $4b $05 $06.
    if (eocd[0] != 0x50 || eocd[1] != 0x4b ||
        eocd[2] != 0x05 || eocd[3] != 0x06) {
        LOGE("signature length doesn't match EOCD marker\n");
        return VERIFY_FAILURE;
    }

    size_t i;
    for (i = 4; i < eocd_size-3; ++i) {
        if (eocd[i  ] == 0x50 && eocd[i+1] == 0x4b &&
            eocd[i+2] == 0x05 && eocd[i+3] == 0x06) {
            // if the sequence $50 $4b $05 $06 appears anywhere after
            // the real one, minzip will find the later (wrong) one,
            // which could be exploitable.  Fail verification if
            // this sequence occurs anywhere after the real one.
            LOGE("EOCD marker occurs after start of EOCD\n");
            return VERIFY_FAILURE;
        }
    }

#define BUFFER_SIZE 4096

    bool need_sha1 = false;
    bool need_sha256 = false;
    for (i = 0; i < numKeys; ++i) {
        switch (pKeys[i].hash_len) {
            case SHA_DIGEST_SIZE: need_sha1 = true; break;
            case SHA256_DIGEST_SIZE: need_sha256 = true; break;
        }
    }

    SHA_CTX sha1_ctx;
    SHA256_CTX sha256_ctx;
    SHA_init(&sha1_ctx);
    SHA256_init(&sha256_ctx);

    double frac = -1.0;
    size_t so_far = 0;
    while (so_far < signed_len) {
        size_t size = signed_len - so_far;
        if (size > BUFFER_SIZE) size = BUFFER_SIZE;

        if (need_sha1) SHA_update(&sha1_ctx, addr + so_far, size);
        if (need_sha256) SHA256_update(&sha256_ctx, addr + so_far, size);
        so_far += size;

        double f = so_far / (double)signed_len;
        if (f > frac + 0.02 || size == so_far) {
            //ui->SetProgress(f);
            frac = f;
        }
    }

    const uint8_t* sha1 = SHA_final(&sha1_ctx);
    const uint8_t* sha256 = SHA256_final(&sha256_ctx);

    uint8_t* sig_der = NULL;
    size_t sig_der_length = 0;

    size_t signature_size = signature_start - FOOTER_SIZE;
    if (!read_pkcs7(eocd + eocd_size - signature_start, signature_size, &sig_der,
            &sig_der_length)) {
        LOGE("Could not find signature DER block\n");
        return VERIFY_FAILURE;
    }

    /*
     * Check to make sure at least one of the keys matches the signature. Since
     * any key can match, we need to try each before determining a verification
     * failure has happened.
     */
    for (i = 0; i < numKeys; ++i) {
        const uint8_t* hash;
        switch (pKeys[i].hash_len) {
            case SHA_DIGEST_SIZE: hash = sha1; break;
            case SHA256_DIGEST_SIZE: hash = sha256; break;
            default: continue;
        }

        // The 6 bytes is the "(signature_start) $ff $ff (comment_size)" that
        // the signing tool appends after the signature itself.
        if (pKeys[i].key_type == Certificate::RSA) {
            if (sig_der_length < RSANUMBYTES) {
                // "signature" block isn't big enough to contain an RSA block.
                LOGI("signature is too short for RSA key %zu\n", i);
                continue;
            }

            if (!RSA_verify(pKeys[i].rsa, sig_der, RSANUMBYTES,
                            hash, pKeys[i].hash_len)) {
                LOGI("failed to verify against RSA key %zu\n", i);
                continue;
            }

            LOGI("whole-file signature verified against RSA key %zu\n", i);
            free(sig_der);
            return VERIFY_SUCCESS;
        } else if (pKeys[i].key_type == Certificate::EC
                && pKeys[i].hash_len == SHA256_DIGEST_SIZE) {
            p256_int r, s;
            if (!dsa_sig_unpack(sig_der, sig_der_length, &r, &s)) {
                LOGI("Not a DSA signature block for EC key %zu\n", i);
                continue;
            }

            p256_int p256_hash;
            p256_from_bin(hash, &p256_hash);
            if (!p256_ecdsa_verify(&(pKeys[i].ec->x), &(pKeys[i].ec->y),
                                   &p256_hash, &r, &s)) {
                LOGI("failed to verify against EC key %zu\n", i);
                continue;
            }

            LOGI("whole-file signature verified against EC key %zu\n", i);
            free(sig_der);
            return VERIFY_SUCCESS;
        } else {
            LOGI("Unknown key type %d\n", pKeys[i].key_type);
        }
		LOGI("i: %i, eocd_size: %i, RSANUMBYTES: %i\n", i, eocd_size, RSANUMBYTES);
    }
    free(sig_der);
    LOGE("failed to verify whole-file signature\n");
    return VERIFY_FAILURE;
}
ReturnValue BleApiTest_Enroll(pBleDevice dev, int expectedSW12)
{
	uint64_t t = dev->TimeMs();

	ReturnValue retval;
	int i;
	unsigned char reply[2048];
	unsigned int replyLength = sizeof(reply);
	unsigned char request[256];
	unsigned int requestlen;
	unsigned char replyCmd;

	memset(reply, 0, sizeof(reply));

	/* generate appid and nonce */
	for (i = 0; i < sizeof(regReq.appId); i++)
		regReq.appId[i] = (rand() & 0xFF);
	for (i = 0; i < sizeof(regReq.nonce); i++)
		regReq.nonce[i] = (rand() & 0xFF);

	/* prepare register request */
	request[0] = 0x00;
	request[1] = 0x01;
	request[2] = 0x00;
	request[3] = 0x00;
	request[4] = 0x00;
	request[5] = 0x00;
	request[6] = sizeof(regReq.nonce) + sizeof(regReq.appId);
	memcpy(request + 7, regReq.nonce, sizeof(regReq.nonce));
	memcpy(request + 7 + sizeof(regReq.nonce), regReq.appId,
	       sizeof(regReq.appId));
	requestlen = 7 + sizeof(regReq.nonce) + sizeof(regReq.appId);
	request[requestlen++] = 0x00;
	request[requestlen++] = 0x00;

	/* write command */
	retval =
	    dev->CommandWrite(FIDO_BLE_CMD_MSG, request, requestlen, &replyCmd,
			      reply, &replyLength);
	CHECK_EQ(retval, ReturnValue::BLEAPI_ERROR_SUCCESS);

	if (expectedSW12 != FIDO_RESP_SUCCESS) {
		CHECK_EQ(expectedSW12, bytes2short(reply, replyLength - 2), "Returned error does not match expected value.");
		CHECK_EQ(replyLength, 2, "Returned value does not match expected length.");
		return ReturnValue::BLEAPI_ERROR_SUCCESS;
	}

	/* check reply */
	CHECK_EQ(replyCmd, FIDO_BLE_CMD_MSG, "Reply is not a FIDO_BLE_CMD_MSG (0x83)");
	CHECK_EQ(FIDO_RESP_SUCCESS, bytes2short(reply, replyLength - 2), "Status code is not FIDO_RESP_SUCCESS (0x9000)");
	CHECK_NE(replyLength, 2, "Reply length is only status code.");

	CHECK_LE(replyLength - 2, sizeof(U2F_REGISTER_RESP), "Returned register response does not match expected length.");

	memcpy(&regRsp, reply, replyLength - 2);

	CHECK_EQ(regRsp.registerId, U2F_REGISTER_ID, "Register ID is not 0x05");
	CHECK_EQ(regRsp.pubKey.format, UNCOMPRESSED_POINT, "Public Key format is not uncompressed point.");

	INFO << "Enroll: " << (replyLength -
			       2) << " bytes in " << ((float)(dev->TimeMs() -
							      t)) /
	    1000.0 << "s";

	// Check crypto of enroll response.
	std::string cert;
	CHECK_EQ(getCertificate(regRsp, &cert), true, "Cannot extract certificate.");
	INFO << "cert: " << bytes2ascii(cert);

	std::string pk;
	CHECK_EQ(getSubjectPublicKey(cert, &pk), true, "Cannot extract public key.");
	INFO << "pk  : " << bytes2ascii(pk);

	std::string sig;
	CHECK_EQ(getSignature(regRsp, static_cast<int>(cert.size()), &sig), true, "Cannot extract signature.");
	INFO << "sig : " << bytes2ascii(sig);

	// Parse signature into two integers.
	p256_int sig_r, sig_s;
	CHECK_EQ(1, dsa_sig_unpack((uint8_t *) (sig.data()), static_cast<int>(sig.size()),
				   &sig_r, &sig_s), "Cannot unpack signature");

	// Compute hash as integer.
	const uint8_t *hash;
	p256_int h;
	SHA256_CTX sha;
	SHA256_init(&sha);
	uint8_t rfu = 0;
	SHA256_update(&sha, &rfu, sizeof(rfu));	// 0x00
	SHA256_update(&sha, regReq.appId, sizeof(regReq.appId));	// O
	SHA256_update(&sha, regReq.nonce, sizeof(regReq.nonce));	// d
	SHA256_update(&sha, regRsp.keyHandleCertSig, regRsp.keyHandleLen);	// hk
	SHA256_update(&sha, &regRsp.pubKey, sizeof(regRsp.pubKey));	// pk
	hash = SHA256_final(&sha);
	p256_from_bin(hash, &h);

	INFO << "hash : " << bytes2ascii((char *)hash, 32);

	// Parse subject public key into two integers.
	CHECK_EQ(pk.size(), P256_POINT_SIZE, "Public key does not match P256 point size.");
	p256_int pk_x, pk_y;
	p256_from_bin((uint8_t *) pk.data() + 1, &pk_x);
	p256_from_bin((uint8_t *) pk.data() + 1 + P256_SCALAR_SIZE, &pk_y);

	// Verify signature.
	CHECK_EQ(1, p256_ecdsa_verify(&pk_x, &pk_y, &h, &sig_r, &sig_s), "Signature does not match.");

	return ReturnValue::BLEAPI_ERROR_SUCCESS;
}