Search code examples
c#compact-framework

Hash and sign a message with RSA algo in c# for compact framework


Hy everybody,

I try to sign one message with RSA algorithm, i'm working to compact Framwork this is my Code:

private void Signer_Click(object sender, EventArgs e)
{
    ///cle de string ver byte[]
    string clePriveeFile = @"\Program Files\PrivateKey.pem";

    StreamReader reader = new StreamReader(clePriveeFile);
    string contenuKeyPrivate = reader.ReadToEnd();
    byte[] keyByte = Certification.DecodeOpenSSLPrivateKey(contenuKeyPrivate);

    string Data = "Salut tout le monde";

    byte[] DataBytes = System.Text.Encoding.UTF8.GetBytes(Data);//.UTF7.GetBytes(Data);

    //Hasher le message
    SHA1Managed sha1 = new SHA1Managed();
    byte[] hash = sha1.ComputeHash(DataBytes);

    string hach = Convert.ToBase64String(hash);



    RSACryptoServiceProvider Rsa = Certification.DecodeRSAPrivateKey(keyByte);

    byte[] sign = Rsa.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));

    string resultat = Convert.ToBase64String(sign);

    this.label1.Text = this.resultat;

}

with 'DecodeOpenSSLPrivateKey' and 'DecodeRSAPrivateKey' it's the sames functions use here: http://www.jensign.com/opensslkey/index.html

for the result of my Hash i obtain: hash = "I4t474liO6H+p8SeDsoIkxmi8b0="

if i do same things with openSSL command: $ echo "Salut tout le monde"| openssl dgst -sha1 | openssl enc -base64

I obtain this: "NjFlOWI4Y2NjN2U2MzFkNTQwNTRmZjE1ZGUyYzk2MDczYTM2ZjRjZAo="

same with my sign result, with this command:

$ echo "Salut tout le monde"| openssl dgst -sha1 -sign PrivateKey.pem | openssl enc -base64

I Have a signature like this: "V6c6XNK7O8+IKKuGTGENdZwoWxhQLIEFHW7XSdoXzMAp1gLu8B5UxXi0lr6JhVDW6SI8p8PtlT+fxEoafY+ZCigIq4xW6e32f6hxYWeYi7silh44I1m7LF7JYR1lfcegnO0Cw+YPqLPRrZUbdcrvMo1ijUGH3SuK+iot2lait9s="

with My Code I obtain this:

result = "YlbnppFDP5ejdYOPoUI/1W6i+ClrKrxbIdA24IqllGDRWGBrWLtGwlfNkh4+B+gzcrX8HI7PkNP1Pq2ud1jE4EhfUVjBkZJwXj/ZYI3fPF41oiIMdF63lZiR/SEHQ5rMTbdsfQtkkBmFTr8udCJNnmnSimRQ458nZvIsYOUW6j4="

I can't to find my error :( can someone help me?


Solution

  • One problem is that the echo output contains a newline suffix. Try hashing "Salut tout le monde\n". Another is that OpenSSL outputs the SHA1 digest in hex-encoded format, so encoding the result in Base64 is meaningless.