

infile=$1		# text file (input)
pub_hex=$2      # peer (device) public key (in hex post-script format, e.g. 0443ac12a... , 130 chars represent 65 bytes)


########## Generate local key-pair
openssl ecparam -name prime256v1 -genkey -noout -out local_prv.pem
openssl ec -in local_prv.pem -pubout -outform DER -out local_pub.der

########## Get peer (device) public key - based on the user input
# add public key prefix for prime256v1
echo 3059301306072a8648ce3d020106082a8648ce3d030107034200 | xxd -r -p > peer_pub.der
# add the binary key
echo ${pub_hex} | xxd -r -p >> peer_pub.der
openssl pkey -pubin -inform DER -in peer_pub.der -out peer_pub.pem


########## Prepare temp file (digest + raw)
# gen digest
echo openssl dgst -sha256 -out ${infile}.tmp ${infile} 
openssl dgst -sha256 -binary -out ${infile}.tmp ${infile} 

# append raw input
cat ${infile} >> ${infile}.tmp


########## Derive Key & IV
# Calc shared secret
echo openssl pkeyutl -derive -inkey local_prv.pem -peerkey peer_pub.der -out secret.bin
openssl pkeyutl -derive -inkey local_prv.pem -peerkey peer_pub.pem -out secret.bin

secret=`xxd -c 64 -ps secret.bin` 
echo secret: ${secret}

iv=${secret:32:32}
echo ____iv: ${iv}

key=${secret:0:32}

t1=0x${secret:0:8}
t2=0x${secret:32:8}
key+=`printf '%x' "$((${t1}^${t2}))"`

t1=0x${secret:8:8}
t2=0x${secret:40:8}
key+=`printf '%x' "$((${t1}^${t2}))"`

t1=0x${secret:16:8}
t2=0x${secret:48:8}
key+=`printf '%x' "$((${t1}^${t2}))"`

t1=0x${secret:24:8}
t2=0x${secret:56:8}
key+=`printf '%x' "$((${t1}^${t2}))"`
echo ___key: ${key}

########## encrypt content (tmp file)
echo openssl aes-256-cbc -base64 -K ${key} -iv ${iv} -in ${infile}.tmp -out ${infile}.tmp.enc
openssl aes-256-cbc -K ${key} -iv ${iv} -in ${infile}.tmp -out ${infile}.tmp.enc


########## Prepare output file
# write raw size
printf "%.8x" `stat -c "%s" ${infile}`  |  sed -E 's/(..)(..)(..)(..)/\4\3\2\1/' | xxd -r -p > ${infile}.enc.sl
# write raw size
printf "%.8x" 0  |  xxd -r -p >> ${infile}.enc.sl
# write (device)public key 
tail -c 65 local_pub.der >> ${infile}.enc.sl
# write encrypted content 
cat ${infile}.tmp.enc >> ${infile}.enc.sl


#od -t x1 ${infile}.enc.sl
wc ${infile}.enc.sl 
#xxd -plain -c 9999 ${infile}.enc.sl
