using RSA Encryption to prevent tampering RRS feed

  • Question

  • I am writing a service that returns a object.  This object has properties that are read-only.  I would like to prevent these values from being changed (via reflection) and used.  

    My thought was to create a hash of the property values I want to protect at the time the object is created.  The hash is comprised of the values of the properties.
    This hash is then encrypted and  signed (RSA Encryption).  

    On the property accessor, I would compute the hash of the current property values, and validate the new  hash using the original public key, new hash value, and orignal signature. 

    if the hash was verified, the value of the properties backing field is returned.  If the has is not verified (indicating the underlying data had changed), an exception is thrown. 

    Here's my problem:  Verifying the hash utilzing the same public key, and digital signature, fails.  Even when the underlying data has not changed. 
    Here's a psuedocode example:

            const string stringToEncrypt = "Hi there.";
                var rsaKeys = GenerateKeySet();
                //Encrypt data using receiver's public key.
                var encrypted = EncryptData(rsaKeys.PublicKey, stringToEncrypt);
                //Hash the encrypted data and generate a signature on the hash   
                // using the sender's private key.
                var signature = HashAndSign(rsaKeys.PrivateKey, encrypted);
                //Verify the signature is authentic using the sender's public key.
                if (!VerifyHash(rsaKeys.PublicKey, encrypted, signature)) throw new ApplicationException("Invalid signature");
                var encrypted2 = EncryptData(rsaKeys.PublicKey, stringToEncrypt);
                if (!VerifyHash(rsaKeys.PublicKey, encrypted2, signature)) throw new ApplicationException("Encrypted Hash Is Not Valid!");

    The above code results in an ApplicationException("Encrypted Hash Is Not Valid") being thrown.

    What am I doing wrong here?

    Monday, July 6, 2009 7:49 PM

All replies

  • Could you please provide your implementations of the following methods: GenerateKeySet, EncryptData, HashAndSign, and VerifyHash?  Without them, it's a little difficult to see where the problem might lie.

    That said, I'm not sure how much value your proposed solution adds.  Are you planning to perform this verification on the client or on the server (assuming the object is sent back to the server from the client)?  If the former, what is to prevent the client from swapping out the signature and key that is used for the verification?
    Wednesday, July 8, 2009 11:56 AM