Encrypting a string with SHA1 does not return the expected value

Posted on

Question :

I am consuming a webservice nfse (electronic service invoice), and the nfse batch receiving function exists, the password is encrypted using the algorithm SHA1 .

The Manual thus exemplifies:

The password: “1234” should look like this: cRDtpNCeBiql5KOQsKVyrA0sAiA =

I came to use the code below:

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

   return senhaHash;
}

But the returned value is a byte array, which has nothing to do with what value I should get.

    

Answer :

cRDtpNCeBiql5KOQsKVyrA0sAiA= is a base64 of the SHA-1 result.

Unfortunately, I can not help you with the exact code. But if you have the byte array of SHA-1, just encode this result for Base64. I made an example of this in another language so maybe it will help.

If SHA-1 is correct Base64 of the result of SHA-1 will have to give cRDtpNCeBiql5KOQsKVyrA0sAiA= . You may be able to use Convert.ToBase64String to convert to encoding correct.

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;
}

    

Leave a Reply

Your email address will not be published. Required fields are marked *