#!/bin/bash -e
# Copyright (C) 2022 Simo Sorce <simo@redhat.com>
# SPDX-License-Identifier: Apache-2.0

source "${TESTSSRCDIR}/helpers.sh"

if [[ "$NSS_FIPS" = "1" ]] && [[ "$TOKENTYPE" = "softokn" ]]; then
    title "ECDH tests are not supported in FIPS for softokn token -- skipping"
    exit 77;
fi

title PARA "ECDH Exchange"
ossl '
pkeyutl -derive -inkey ${ECBASEURI}
                -peerkey ${ECPEERPUBURI}
                -out ${TMPPDIR}/secret.ecdh.bin'

title PARA "Additional test with EC keys"
$CHECKER "${TESTBLDDIR}/tecx" "${ECPRIURI}" "${ECPEERPUBURI}"

if [[  "$TOKENTYPE" = "softhsm" ]]; then
    title "ECDH forced on token deadlocks SoftHSM2 so we skip those tests"
    exit 0
fi

# Now test by forcing all operations on the token
title PARA "ECDH Exchange forcing PKCS11 Provider"
ORIG_OPENSSL_CONF=${OPENSSL_CONF}
sed -e "s/#MORECONF/alg_section = algorithm_sec\n\n[algorithm_sec]\ndefault_properties = ?provider=pkcs11/" \
    "${OPENSSL_CONF}" > "${OPENSSL_CONF}.forcetoken"
OPENSSL_CONF=${OPENSSL_CONF}.forcetoken
title PARA "ECDH Exchange forced: public key in file"
ossl '
pkeyutl -derive -inkey ${ECBASEURI}
                -peerkey ${TESTSSRCDIR}/testp256.pub.pem
                -out ${TMPPDIR}/forced.pub.ecdh.bin'

title PARA "ECDH Exchange forced: private key in file"
ossl '
pkeyutl -derive -inkey ${TESTSSRCDIR}/testp256.pri.pem
                -peerkey ${ECPEERPUBURI}
                -out ${TMPPDIR}/forced.pri.ecdh.bin'

title PARA "ECDH Exchange forced: both key in file"
ossl '
pkeyutl -derive -inkey ${TESTSSRCDIR}/testp256.pri.pem
                -peerkey ${TESTSSRCDIR}/testp256.pub.pem
                -out ${TMPPDIR}/forced.both.ecdh.bin'
OPENSSL_CONF=${ORIG_OPENSSL_CONF}

exit 0
