#!/bin/sh

# RCSid:
#	$Id: verify-sig.sh,v 1.11 2025/06/06 21:35:11 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

GPG=${GPG:-gpg}
OPENSSL=${OPENSSL:-openssl}

Error() {
    echo "ERROR: $@" >&2
    exit 1
}

VerifyCert() {
    CApem=$1
    certs=$2

    x=`$OPENSSL verify -CAfile $CApem -untrusted $certs $certs | grep OK`
    case "$x" in
    *OK) ;;
    *) Error cannot verify: $certs;;
    esac
    $OPENSSL x509 -noout -subject < $certs | sed 's,subject=,Verified:,'
}

        
# this function demonstrates how the signature verification works
# we assume that any certs have been verified already
VerifySig() {
    tf=/tmp/vs$$
    case "$1" in
    *.asc) ;;                   # assume pubkeys imported
    *)
        vk=$1; shift
        case "$vk" in
        *certs*)
            $OPENSSL x509 -noout -pubkey -in $vk > $tf.vk
            vk=$tf.vk
            ;;
        esac
        ;;
    esac

    for sig in "$@"
    do
        : sig=$sig
        case "$sig" in
        *.asc)
            $GPG --openpgp --verify $sig 2>&1 |
            sed 's,Good signature from.*,& OK,' > $tf.vs
            ;;
        *sig)
            file=${sig%.*sig}
            sed -n '/-BEGIN/,/-END/ { /---/d;p; }' $sig |
                $OPENSSL base64 -d > $tf.rs
            case $sig in
            *.esig)
                $OPENSSL dgst -sha256 < $file | sed 's,.*(stdin) *=  *,,' |
                $OPENSSL dgst -sha256 -signature $tf.rs -verify $vk > $tf.vs
                ;;
            *.sig)
                $OPENSSL dgst -sha1 -signature $tf.rs -verify $vk < $file > $tf.vs
                ;;
            esac
            ;;
        esac
        case `grep OK $tf.vs` in
        *OK) echo Verified: $sig;;
        *)  rm -f $tf.*
            Error cannot verify: $sig
            ;;
        esac
    done
    rm -f $tf.*
}

case /$0 in
*/verify-*)
    case "$1" in
    *CA.pem) 
        VerifyCert $1 $2
        shift
        ;;
    esac
    VerifySig "$@";;
esac

