A rewrite of encode()/sign()

An almost complete rewrite of the signing operation, including an API change. No changes to the cryptographic code.