#!/usr/bin/env python3

import sys
import os
sys.path.append('./obj/'+os.getenv('HOST_TARGET',''))
sys.path.append('..')
if sys.version_info[0] == 2:
    try:
        import ossl2 as ossl
    except:
        import signer as ossl
else:
    import ossl3 as ossl

import hashlib
import p3compat
import conf as cf
import getopt

def usage():
    print("""Signer Test:
You need to generate a key and certificate to use this test.
For example:

	% openssl genrsa -out key.pem 2048
        % openssl x509 -new -subj /CN=test -key key.pem -out cert.pem -days 5000

Then (if you generated those in /tmp):

	% ./signer-test.py -k /tmp/key.pem -p /tmp/cert.pem -N
        Verified OK
        Unverified OK
        %

The -N runs a negative test - modifying the hash after
successful verification to show that it no longer verifies.

""")
        
conf = { 'key': 'key.pem', 'pubkey': 'cert.pem' }
conf = cf.loadConfig('${progdir}/${progname:R}.rc', conf, False)

try:
    opts,args = getopt.getopt(sys.argv[1:], 'c:k:Np:')
except getopt.GetoptError as err:
    usage()
    sys.exit(1)

for o,a in opts:
    if o == '-c':
        conf = cf.loadConfig(a, conf)
    elif o == '-k':
        conf['key'] = a
    elif o == '-N':
        conf['Nflag'] = True
    elif o == '-p':
        conf['pubkey'] = a

key = ossl.load_key(conf.get('key'))
pubkey = ossl.load_pubkey(conf.get('pubkey'))
h = hashlib.sha256()
h.update(b'Hello, World\n')
d = h.digest()

s = ossl.sign_digest(key, b'sha256', d)
# that should verify - obviously
x = ossl.verify_digest(pubkey, b'sha256', d, s) 
if x > 0:
    print("Verified OK")

    if 'Nflag' in conf:
        # test that modified hash fails to verify
        h.update(b'Oops')
        d = h.digest()
        x = ossl.verify_digest(pubkey, b'sha256', d, s)
        if x == 0:
            print("Unverified OK")
else:
    print("Unverified: {}".format(ossl.error_string()))




