c# - How to properly verify data with rsa? -
i want sign message private key , verify public key, can't work..
here how sign data (edited, still not working):
public static string signdata(string message, string privatekey) { byte[] plaintext = asciiencoding.unicode.getbytes(message); var rsawrite = new rsacryptoserviceprovider(); rsawrite.fromxmlstring(privatekey); byte[] signature = rsawrite.signdata(plaintext, new sha1cryptoserviceprovider()); return convert.tobase64string(signature); }
here how test data (edited, still not working):
public static bool verifydata(string sign, string publickey, string orig) { byte[] signature = convert.frombase64string(sign); byte[] original = asciiencoding.unicode.getbytes(orig); var rsaread = new rsacryptoserviceprovider(); rsaread.fromxmlstring(publickey); if (rsaread.verifydata(original, new sha1cryptoserviceprovider(), signature)) { return true; } else { return false; } }
i store keypair xml string inside account class. function executed in constructor of account.cs:
public void addkeys() { rsacryptoserviceprovider provider = new rsacryptoserviceprovider(1024); privatekey = provider.toxmlstring(true); publickey = provider.toxmlstring(false); }
i test overall thing this:
string signedhash = utility.signdata("test" ,account.privatekey); if (utility.verifydata(signedhash, account.publickey, "test")) { console.writeline("working!"); } else { console.writeline("signing not working"); }
why isn't overall thing working? guess doesn't work because of encoding stuff.
return asciiencoding.unicode.getstring(signature);
the signature arbitrary binary data, isn't legal unicode/ucs-2. need use arbitrary encoding (https://en.wikipedia.org/wiki/binary-to-text_encoding#encoding_standards) encode of arbitrary data. popular transport signatures base64, you'd want
return convert.tobase64string(signature);
and, of course, use convert.frombase64string
in verify method.
if you're compiling target of .net 4.6 or higher can make use of newer sign/verify api:
rsaread.verifydata(original, new sha1cryptoserviceprovider(), signature)
would be
rsaread.verifydata(original, signature, hashalgorithmname.sha1, rsasignaturepadding.pkcs1)
while might not simpler, prevents allocation , finalization of sha1cryptoserviceprovider other method did, , sets future when may want switch pkcs1 signature padding pss signature padding. (but real advantage method on rsa
base class instead of rsacryptoserviceprovider
specific type).
Comments
Post a Comment