#!/usr/bin/env python

from __future__ import print_function

"""verify signatures

NOTE: this does not (yet) verify the signer (cert chain).
"""

"""
RCSid:
	$Id: verify.py,v 1.6 2014/08/25 22:42:16 sjg Exp $

	@(#) Copyright (c) 2012 Simon J. Gerraty

	This file is provided in the hope that it will
	be of use.  There is absolutely NO WARRANTY.
	Permission to copy, redistribute or otherwise
	use this file is hereby granted provided that 
	the above copyright notice and this notice are
	left intact. 
      
	Please send copies of changes and bug-fixes to:
	sjg@crufty.net

"""

import sys
from sign import hash_file
from conf import *
from pem import *
import os.path
import getopt

hname = 'sha256'
tname = 'EC'
debug = 0
clsname = 'OpenSSLSigner'
conf = {}

opts,args = getopt.getopt(sys.argv[1:], 'dk:h:t:c:')
for o,a in opts:
    if o == '-c':
        clsname = a
    elif o == '-d':
        debug += 1
    elif o == '-k':
        kfile = a
        conf['PublicKey'] = a
    elif o == '-h':
        hname = a
    elif o == '-t':
        tname = a

m = __import__('hashlib', fromlist=[hname])
hash = getattr(m, hname)

sm = __import__(clsname)
sc = getattr(sm, clsname)
signer = sc(None, conf)

for sfile in args:
    file,ext = os.path.splitext(sfile)

    slines = open(sfile, 'r').readlines()
    sig = pem_decode('SIG', slines)

    f = open(file, 'rb')
    h = hash()
    for line in f:
        h.update(line)
    f.close()

    try:
        signer.verify(h.digest(), sig)
        print("Verified:", sfile)
    except:
        if debug:
            raise
        print("Failed:", sfile)
    
    
