Encrypting a string with SHA1 does not return the expected value

Asked

Viewed 144 times

3

I’m consuming a webservice of nfse (electronic service invoice), and the nfse batch receipt function, there is that the password is encrypted using the algorithm SHA1.

The Handbook exemplifies this:

The password: "1234", should look like this: cRDtpNCeBiql5KOQsKVyrA0sAiA=

I even used the code below:

public string SenhaHash(senha){
   var hash = new SHA1CryptoServiceProvider();
   var senhaBytes = Encoding.Default.GetBytes(senha);
   var senhaHash = hash.ComputeHash(senhaBytes );

   return senhaHash;
}

However the value returned is a byte array, which has nothing to do with the value I should arrive at.

1 answer

4


The cRDtpNCeBiql5KOQsKVyrA0sAiA= is a Base64 of the result of SHA-1.


Unfortunately I can’t help you with the exact code. But if you have the byte array from SHA-1, simply encode this result to Base64. I made an example of this, in another language, so it might help.

If SHA-1 is correct Base64 of the SHA-1 result will have to give the cRDtpNCeBiql5KOQsKVyrA0sAiA=. Apparently you can use the Convert.ToBase64String, to convert to correct encoding.

The correct algorithm would look like this:

public string SenhaHash(senha){
  var hash = new SHA1CryptoServiceProvider();
  var senhaBytes = Encoding.Default.GetBytes(senha);
  var senhaHash = hash.ComputeHash(senhaBytes );
  var senhaHashBase64 = Convert.ToBase64String(senhaHash);

  return senhaHash;
}
  • I got it, it worked, I’m going to edit your answer to show you how my code came to be with your solution.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.