+ Start a Discussion
greg.aylinggreg.ayling 

Encrypting password to match encrypted nvarchar in SQL

Here are my steps:
1. Take in a username and password from a Visualforce page.
2. With Apex, I'm encrypting the password using the following function.


private string Encrypt(string preHashValue){
       Blob bPrehash = Blob.valueOf(preHashValue);
       Blob bsig = Crypto.generateDigest('SHA1', bPrehash);

       return EncodingUtil.convertToHex(bsig);        
}

 

3. This gives me a 40-digit hex number.

4. I store that number in Salesforce.

Now the problem:

 

Currently, I've got an encrypted (SHA1) password in my SQL database that I want to compare to the encrypted password in Salesforce.
The issue is that these values, after encrypting the same plaintext password, are not the same.

After some digging, I've found that when the SQL stored procedure is encrypting the plaintext password, it's storing it as an nvarchar(255). Then encrypting it using       HashBytes('SHA1',@Password)

So,

       HashBytes( 'SHA1', Cast( 'TestPassword' as nvarchar(255) ) )

and
       HashBytes( 'SHA1', 'TestPassword' )

give two different values.

My Question:
Is there a way to encrypt the value in Apex so that it matches the encrypted nvarchar(255) in the SQL database?

Any help would be greatly appreciated,

Greg

forcedotcomforcedotcom

Hi Greg,

 

Have you considered getting salesforce to enable encrypted fields for you, which should/could make this process slightly more straightfoward (at a guess!) - apologies you've already tried this approach.

greg.aylinggreg.ayling

Thanks for the suggestion!

The complication isn't the actual encryption part, though.
I need the field to have the same character encoding (I believe) as an nvarchar before I encrypt it, so that it matches the encrypted value in our own database.