from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
message = b"A message I want to sign"
signature = private_key.sign(
message,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
converting the signature using base64 encode and decode methods to string. This is a requires process in the application for serialization.
But not sure how can I convert back to bytes to verify the signature.
Hi Raj,
I’m not sure what you want to do here, but know that you only can verify a (received) signature by generating it again using the same technique and then compare it with what you created. You cannot ‘decode’ a signature.
N.
I am working on small blockchain assignment which requires me to cast the signature from bytes to string and the vice versa. When I call the verify signature method I have only string representation of the string as per my statement in the original thread.
What sort of results do you expect when you cast your bytes to strings?
The bytes b’abc’ have a natural interpretation as ASCII text, ‘abc’, but
what happens if your bytes include non-text bytes?
b'\0\x03\xFF\xE1'
What string do you want? Normally we decode bytes to string using a
text-based codec, such as ASCII, Latin-1, UTF-8, UTF-16 etc. But most of
those will not work for arbitrary binary byte strings, and the few that
do (such as Latin-1 and a few other legacy codecs) will give you
meaningless mojibake as the result.
So we need more information about what you expect to happen when you
decode the bytes to a string. Do you also expect to encode the string
back to the bytes, and do you expect it to losslessly roundtrip?
hash_string = ‘-’.join([
str(self._index),
json.dumps(self._transactions, sort_keys=True)
])
… verify signature goes here by iterating all transactions …
json,dump fails if I do not convert signature bytes into string. And want convert it back to its original form bytes to verify the signature using public_key.verify method.
b64encode will only ever output byte values in the ASCII range, so
it’s probably more appropriate to use ‘ascii’ instead of ‘utf8’ when
recasting to/from a str type.
Another simpler solution is to just use hexidecimal string
representation: