def sign(hash,priv,k=0):
    '''
    Returns a DER-encoded signature from a input of a hash and private
    key, and optionally a K value.

    Hash and private key inputs must be 64-char hex strings,
    k input is an int/long.

    >>> h = 'f7011e94125b5bba7f62eb25efe23339eb1637539206c87df3ee61b5ec6b023e'
    >>> p = 'c05694a7af0e01dceb63e5912a415c28d3fc823ca1fd3fa34d41afde03740466'
    >>> k = 4 # chosen by fair dice roll, guaranteed to be random
    >>> sign(h,p,k)
    '3045022100e493dbf1c10d80f3581e4904930b1404cc6c13900ee0758474fa94abe8c4cd130220598e37e2e66277ef4d0caf0e32d095debb3c744219508cd394b9747e548662b7'
    '''

    if k == 0:
        k = generate_k(priv, hash)

    hash = int(hash,16)
    priv = int(priv,16)

    r = int(privtopub(dechex(k,32),True)[2:],16) % N
    s = ((hash + (r*priv)) * modinv(k,N)) % N

    # High S value is non-standard (soon to be invalid)
    if s > (N / 2):
        s = N - s

    r, s = inttoDER(r), inttoDER(s)
    olen = dechex(len(r+s)//2,1)
    return '30' + olen + r + s
Returns a DER-encoded signature from a input of a hash and private
    key, and optionally a K value.

    Hash and private key inputs must be 64-char hex strings,
    k input is an int/long.

    >>> h = 'f7011e94125b5bba7f62eb25efe23339eb1637539206c87df3ee61b5ec6b023e'
    >>> p = 'c05694a7af0e01dceb63e5912a415c28d3fc823ca1fd3fa34d41afde03740466'
    >>> k = 4 # chosen by fair dice roll, guaranteed to be random
    >>> sign(h,p,k)
    '3045022100e493dbf1c10d80f3581e4904930b1404cc6c13900ee0758474fa94abe8c4cd130220598e37e2e66277ef4d0caf0e32d095debb3c744219508cd394b9747e548662b7'