Jump to content

SHA1 em C# compativel com SHA-1 (Java)


Recommended Posts

Posted

Boa tarde amigos... Tenho esta situação em java:
 

private byte[] buildPasswordDigest(byte[] simetricKey, String timestamp, String password) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        byte[] bytesNonce = simetricKey;
        byte[] bytesCreated = timestamp.getBytes("UTF-8");
        byte[] bytesPassword = password.getBytes("UTF-8");

        byte[] digestInput = new byte[bytesNonce.length + bytesCreated.length + bytesPassword.length];
        System.arraycopy(bytesNonce, 0, digestInput, 0, bytesNonce.length);
        System.arraycopy(bytesCreated, 0, digestInput, bytesNonce.length, bytesCreated.length);
        System.arraycopy(bytesPassword, 0, digestInput, bytesNonce.length + bytesCreated.length, bytesPassword.length);

        MessageDigest md = MessageDigest.getInstance("SHA-1");
        return md.digest(digestInput);
    }

E quero reproduzi-la em c#: 

 

// Geração do DIGEST
// Concatenação dos array's bytes da Ks + Created + SenhaPF
byte[] bytesNonce = Chave;
byte[] bytesCreated = Encoding.UTF8.GetBytes(Created);
byte[] bytesPassword =  Encoding.UTF8.GetBytes(SenhaPF);

byte[] digestInput = new byte[bytesNonce.length + bytesCreated.length + bytesPassword.length];
Array.Copy(bytesNonce, 0, digestInput, 0, bytesNonce.length);
Array.Copy(bytesCreated, 0, digestInput, bytesNonce.length, bytesCreated.length);
Array.Copy(bytesPassword, 0, digestInput, bytesNonce.length + bytesCreated.length, bytesPassword.length);

// Função de cálculo de Digest usando o algoritmo SHA-1
SHA1 sha1 = SHA1Managed.Create();
byte[] SHA1Bytes = sha1.ComputeHash(digestArray);

O meu problema aqui é que os bytes de um e de outro não são compatíveis...
O do java devolve até bits negativos e o do C# não.
Não consigo vos dar um exemplo de concreto porque a data é a data atual de sistema.

Isto é o código para utilização dos webeservices da AT. 

Obrigado desde já pela vossa disponibilidade

Posted

http://stackoverflow.com/questions/18428891/java-code-negative-byte-in-byte-array-to-c-sharp

 

c#:

 -sbyte: https://msdn.microsoft.com/en-us/library/d86he86x.aspx 

 -byte: https://msdn.microsoft.com/en-us/library/5bdb6693.aspx

 

Acho que isso te ajuda.

O problema é que o byte de java é representado como signed, enquanto que em c#, é um unsigned.

No lado do c#, podes usar o sbyte.

Cumprimentos,
iron

Posted (edited)

Olá iron ao passar de byte[] para sbyte[] realmente obtenho os valores negativos no entanto o digest gerado continua errado.

 

// Geração do DIGEST
            // Concatenação dos array's bytes da Ks + Created + SenhaPF
            byte[] bytesNonce = Ks;
            byte[] bytesCreated = Encoding.UTF8.GetBytes(Created);
            byte[] bytesPassword = Encoding.UTF8.GetBytes(SenhaPF);

            byte[] digestInput = new byte[bytesNonce.Length + bytesCreated.Length + bytesPassword.Length];
            Array.Copy(bytesNonce, 0, digestInput, 0, bytesNonce.Length);
            Array.Copy(bytesCreated, 0, digestInput, bytesNonce.Length, bytesCreated.Length);
            Array.Copy(bytesPassword, 0, digestInput, bytesNonce.Length + bytesCreated.Length, bytesPassword.Length);



            var sha1 = SHA1CryptoServiceProvider.Create();
            byte[] hashBytes = sha1.ComputeHash(digestInput);
           
            sbyte[] signed = hashBytes.Select(b => (sbyte)b).ToArray();


            // Fluxo de memória de Digest
            MemoryStream msDigest = new MemoryStream();
            // Função que cifra o Digest utilizando o algoritmo AES, Modelo ECB, PKCS5Padding e a chave simétrica do pedido Ks
            CryptoStream csDigest = new CryptoStream(msDigest, rijndaelCipher.CreateEncryptor(Ks, rijndaelCipher.IV), CryptoStreamMode.Write);
            using (StreamWriter swDigest = new StreamWriter(csDigest))
            {
                swDigest.Write(signed);
            }
::::ERROR::::
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns="http://autenticacao.portaldasfinancas.gov.pt/services/ValidateCredencialService/2012/11" xmlns:wss="http://schemas.xmlsoap.org/ws/2002/12/secext">
  <SOAP-ENV:Header />
  <SOAP-ENV:Body>
    <SOAP-ENV:Fault>
      <faultcode>Client.Authentication</faultcode>
      <faultstring>Ocorreu um erro na autenticação dos contribuintes.</faultstring>
      <faultactor />
      <detail>
        <ns:AuthenticationException>
          <AuthenticationFailed xmlns:ns0="http://autenticacao.portaldasfinancas.gov.pt/services/ValidateCredencialService/2012/11" xmlns:ns3="http://at.pt/wsp/auth" xmlns:ns1="http://schemas.xmlsoap.org/ws/2002/12/secext" xmlns:ns2="http://schemas.xmlsoap.org/soap/envelope/" xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
            <Code>15</Code>
            <Message>O Digest não corresponde ao esperado</Message>
            <NumberOfTriesRemaining>-1</NumberOfTriesRemaining>
            <Actor>http://at.pt/actor/SPA</Actor>
          </AuthenticationFailed>
        </ns:AuthenticationException>
      </detail>
    </SOAP-ENV:Fault>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Edited by General

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.