#!/bin/bash

# OPENSSL=/path/to/binary/for/openssl
OPENSSL=apps/openssl

# Setup a malicious public key for Malice.
cat <<EOF > /tmp/malice.pub
-----BEGIN PUBLIC KEY-----
MFIwEAYHKoZIzj0CAQYFK4EEABsDPgAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYf4
Vie5eHTnR+4x4G1xyq7qUvISU+X5RtBh2pE4
-----END PUBLIC KEY-----
EOF

# number of keys to generate
n=5

for (( i=1; i<=n; i++ )); do
    echo "Bob's keys: $i"
    v=0
    while [ $v -lt 128 ]; do
        $OPENSSL genpkey -algorithm EC -pkeyopt ec_paramgen_curve:sect233r1 -out /tmp/bob$i.prv
        keys=$($OPENSSL pkey -in /tmp/bob$i.prv -text -noout)
        keys=$(echo $keys | sed 's/\n//g')
        IFS=':' read -r a b c msb d <<< $keys
        v=$(echo $((16#$msb)))
    done
    $OPENSSL pkey -in /tmp/bob$i.prv -text -noout
    # deriving the shared key.
    $OPENSSL pkeyutl -derive -inkey /tmp/bob$i.prv -peerkey /tmp/malice.pub -pkeyopt ecdh_cofactor_mode:1 -out /tmp/shared.bin
done
