Assinar com Sha256

Projeto hbNFe (Nota Fiscal Eletronica/Danfe) para [x]Harbour

Moderador: Moderadores

malcarli
Usuário Nível 3
Usuário Nível 3
Mensagens: 239
Registrado em: 20 Ago 2015 18:14
Localização: marilia/sp

Assinar com Sha256

Mensagem por malcarli »

boa tarde mestre Quintas

Estou começando com esocial, na nfe assina com sha1 e esocial com sha256, teria como implementar este tipo de assinatura?

Att.

Marcelo A. L. Carli
Marília/SP
Capital Nacional do Alimento ®

https://malc-informatica.ueniweb.com
http://marcelo.lx.com.br
Email / Skype: malcarli@life.com.br
Avatar do usuário
sygecom
Administrador
Administrador
Mensagens: 7131
Registrado em: 21 Jul 2006 10:12
Localização: Alvorada-RS
Contato:

Assinar com Sha256

Mensagem por sygecom »

Será que algum desses abaixo não lhe ajuda ?

viewtopic.php?f=4&t=16160
Leonardo Machado
xHarbour.org + Hwgui + PostgreSql
malcarli
Usuário Nível 3
Usuário Nível 3
Mensagens: 239
Registrado em: 20 Ago 2015 18:14
Localização: marilia/sp

Assinar com Sha256

Mensagem por malcarli »

Bom ainda estou apanhando para assinar o eSocial com sha256. Estou estudando e tentanto colocar na classe do Mestre Quintas. Fiz estas alterações por enquanto e deu erro : Erro Assinatura: Template de assinatura não encontrado. Não consegui achar o pq disto, alguma sugestão?

Será que isso #define _CAPICOM_CERTIFICATE_FIND_SHA1_HASH 0 // Retorna os Dados Criptografados com Hash SH1
influenciaria para assinar com rs-sha1?

Código: Selecionar todos

* aqui inclui os evtCAT, evtMonit, evtExpRisco que são os eventos que vou usar 

   aDelimitadores := { ;
      { "<enviMDFe",              "</MDFe></enviMDFe>" }, ;
      { "<eventoMDFe",            "</eventoMDFe>" }, ;
      { "<eventoCTe",             "</eventoCTe>" }, ;
      { "<infMDFe",               "</MDFe>" }, ;
      { "<infCte",                "</CTe>" }, ;
      { "<infNFe",                "</NFe>" }, ;
      { "<infDPEC",               "</envDPEC>" }, ;
      { "<infInut",               "<inutNFe>" }, ;
      { "<infCanc",               "</cancNFe>" }, ;
      { "<infInut",               "</inutNFe>" }, ;
      { "<infInut",               "</inutCTe>" }, ;
      { "<infEvento",             "</evento>" }, ;
      { "<evtInfoEmpregador",     "</eSocial>" }, ;
      { "<evtCAT",                "</eSocial>" }, ;
      { "<evtMonit",              "</eSocial>" }, ;
      { "<evtExpRisco",           "</eSocial>" }, ;
      { "<PedidoEnvioLoteRPS",    "</RPS>" }, ;
      { "<PedidoEnvioRPS",        "</RPS>" }, ;
      { "<infPedidoCancelamento", "</Pedido>" }, ;               // NFSE ABRASF Cancelamento
      { "<LoteRps",               "</EnviarLoteRpsEnvio>" }, ;   // NFSE ABRASF Lote
      { "<infRps",                "</Rps>" } }                   // NFSE ABRASF RPS
aqui também modifiquei, baseado o que vi nas assinaturas usadas no esocial, mas com certeza não está correto

Código: Selecionar todos

STATIC FUNCTION AssinaBlocoAssinatura( cURI, lComURI )

   LOCAL cSignatureNode := ""

   IF lComURI
      cURI := "#" + cURI
   ENDIF
   cSignatureNode += [<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">]
   cSignatureNode +=    [<SignedInfo>]
   cSignatureNode +=       [<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>]
   cSignatureNode +=       [<SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />]
   cSignatureNode +=       [<Reference URI="] + cURI + [">]
   cSignatureNode +=       [<Transforms>]
   cSignatureNode +=          [<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />]
   cSignatureNode +=          [<Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />]
   cSignatureNode +=       [</Transforms>]
   cSignatureNode +=       [<DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />]
   cSignatureNode +=       [<DigestValue>]
   cSignatureNode +=       [</DigestValue>]
   cSignatureNode +=       [</Reference>]
   cSignatureNode +=    [</SignedInfo>]
   cSignatureNode +=    [<SignatureValue>]
   cSignatureNode +=    [</SignatureValue>]
   cSignatureNode +=    [<KeyInfo>]
   cSignatureNode +=    [</KeyInfo>]
   cSignatureNode += [</Signature>]

   RETURN cSignatureNode

malcarli
Usuário Nível 3
Usuário Nível 3
Mensagens: 239
Registrado em: 20 Ago 2015 18:14
Localização: marilia/sp

Assinar com Sha256

Mensagem por malcarli »

Achei esta rotina em c#, seria possível converter em c para ser usado no harbour?

Código: Selecionar todos

class Assinatura
{
    public string AssinarSHA256(Int32 lnEvento, 
        string arqXMLAssinar,
        string tagAssinatura,
        string tagAtributoId,
        X509Certificate2 x509Cert,
        string lxURI)
    {
        try
        {
            string xmlString;
            xmlString = arqXMLAssinar;

            XmlDocument doc = new XmlDocument();
            // Format the document to ignore white spaces.
            doc.PreserveWhitespace = false;

            doc.LoadXml(xmlString);

            XmlElement xmlDigitalSignature = null;

            // Load the passed XML file using it’s name.

            if (doc.GetElementsByTagName(tagAssinatura).Count == 0)
            {
                throw new Exception("A tag de assinatura " + tagAssinatura.Trim() + " não existe no XML. (Código do Erro: 5)");
            }
            else if (doc.GetElementsByTagName(tagAtributoId).Count == 0)
            {
                throw new Exception("A tag de assinatura " + tagAtributoId.Trim() + " não existe no XML. (Código do Erro: 4)");
            }
            // Existe mais de uma tag a ser assinada
            else
            {
                XmlNodeList lists = doc.GetElementsByTagName(tagAssinatura);

                if (lists.Count != 1)
                {
                    MessageBox.Show("Existe mais de uma TAG definida como tag da assinatura");
                    throw new Exception("Existe mais de uma tag de assinatura " + tagAtributoId.Trim() + " não existe no XML. (Código do Erro: 6)");
                }

                #region 
                foreach (XmlNode nodes in lists)
                {
                    foreach (XmlNode childNodes in nodes.ChildNodes)
                    {
                        if (!childNodes.Name.Equals(tagAtributoId))
                            continue;

                        // Create a reference to be signed
                        Reference reference = new Reference();

                        reference.Uri = lxURI;

                        // Create a SignedXml object.
                        SignedXml signedXml = new SignedXml(doc);

                        signedXml.SigningKey = x509Cert.GetRSAPrivateKey();

                        signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";

                        // Add an enveloped transformation to the reference.
                        XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

                        reference.AddTransform(env);

                        XmlDsigC14NTransform c14 = new XmlDsigC14NTransform();

                        reference.AddTransform(c14);

                        reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";


                        // Add the reference to the SignedXml object.
                        signedXml.AddReference(reference);

                        // Create a new KeyInfo object
                        KeyInfo keyInfo = new KeyInfo();

                        // Load the certificate into a KeyInfoX509Data object
                        // and add it to the KeyInfo object.
                        keyInfo.AddClause(new KeyInfoX509Data(x509Cert));

                        // Add the KeyInfo object to the SignedXml object.
                        signedXml.KeyInfo = keyInfo;

                        signedXml.ComputeSignature();

                        // Get the XML representation of the signature and save
                        // it to an XmlElement object.
                        xmlDigitalSignature = signedXml.GetXml();

                        // Gravar o elemento no documento XML
                        nodes.AppendChild(doc.ImportNode(xmlDigitalSignature, true));

                    }
                }

                #endregion



                // Atualizar a string do XML já assinada
                return doc.OuterXml;
            }
        }
        catch (System.Security.Cryptography.CryptographicException ex)
        {

            throw new Exception("Mensagem:" + ex.Message + "\n" +
                "Trace:" + ex.StackTrace + "\n" +
                "Dados" + ex.Data + "\n" +
                ex.ToString());// #12342 concatenar com a mensagem original
        }
        finally
        {

        }
    }
}
Avatar do usuário
jairfab
Usuário Nível 3
Usuário Nível 3
Mensagens: 252
Registrado em: 21 Mai 2007 09:43
Localização: São Paulo, Região Leste - Suzano

Assinar com Sha256

Mensagem por jairfab »

encontrei algumas funcoes em c, quem saber se alguem aqui no grupo que tenha alguma experiencia em c poderia ajudar.

Código: Selecionar todos

/ ************************************************* ********************
* Nome do arquivo: sha256.c
* Autor: Brad Conte (brad AT bradconte.com)
* Direito autoral:
* Isenção de responsabilidade: Este código é apresentado "como está" sem quaisquer garantias.
* Detalhes: Implementação do algoritmo de hash SHA-256.
              SHA-256 é um dos três algoritmos do SHA2
              especificação. Os outros, SHA-384 e SHA-512, não são
              oferecidos nesta implementação.
              A especificação do algoritmo pode ser encontrada aqui:
               * http://csrc.nist.gov/publications/fips/fips180-2/fips180-2withchangenotice.pdf
              Esta implementação usa pouca ordem de bytes endian.
**************************************************** ****************** */

/* ************************** ARQUIVOS DE CABEÇALHO ******************** ****** */
# inclui  < stdlib.h >
# inclui  < memória.h >
# inclui  " sha256.h "

/* ***************************** MACROS ****************** *********** */
# define  ROTLEFT ( a,b ) (((a) << (b)) | ((a) >> ( 32 -(b))))
# define  ROTRIGHT ( a,b ) (((a) >> (b)) | ((a) << ( 32 -(b))))

# define  CH ( x,y,z ) (((x) & (y)) ^ (~(x) & (z)))
# define  MAJ ( x,y,z ) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
# define  EP0 ( x ) (ROTRIGHT(x, 2 ) ^ ROTRIGHT(x, 13 ) ^ ROTRIGHT(x, 22 ))
# define  EP1 ( x ) (ROTRIGHT(x, 6 ) ^ ROTRIGHT(x, 11 ) ^ ROTRIGHT(x, 25 ))
# define  SIG0 ( x ) (ROTRIGHT(x, 7 ) ^ ROTRIGHT(x, 18 ) ^ ((x) >> 3 ))
# define  SIG1 ( x ) (ROTRIGHT(x, 17 ) ^ ROTRIGHT(x, 19 ) ^ ((x) >> 10 ))

/* **************************** VARIÁVEIS ******************** ******** */
static  const WORD k[ 64 ] = {
	0x428a2f98 , 0x71374491 , 0xb5c0fbcf , 0xe9b5dba5 , 0x3956c25b , 0x59f111f1 , 0x923f82a4 , 0xab1c5ed5 ,
	0xd807aa98 , 0x12835b01 , 0x243185be , 0x550c7dc3 , 0x72be5d74 , 0x80deb1fe , 0x9bdc06a7 , 0xc19bf174 ,
	0xe49b69c1 , 0xefbe4786 , 0x0fc19dc6 , 0x240ca1cc , 0x2de92c6f , 0x4a7484aa , 0x5cb0a9dc , 0x76f988da ,
	0x983e5152 , 0xa831c66d , 0xb00327c8 , 0xbf597fc7 , 0xc6e00bf3 , 0xd5a79147 , 0x06ca6351 , 0x14292967 ,
	0x27b70a85 , 0x2e1b2138 , 0x4d2c6dfc , 0x53380d13 , 0x650a7354 , 0x766a0abb , 0x81c2c92e , 0x92722c85 ,
	0xa2bfe8a1 , 0xa81a664b , 0xc24b8b70 , 0xc76c51a3 , 0xd192e819 , 0xd6990624 , 0xf40e3585 , 0x106aa070 ,
	0x19a4c116 , 0x1e376c08 , 0x2748774c , 0x34b0bcb5 , 0x391c0cb3 , 0x4ed8aa4a , 0x5b9cca4f , 0x682e6ff3 ,
	0x748f82ee , 0x78a5636f , 0x84c87814 , 0x8cc70208 , 0x90befffa , 0xa4506ceb , 0xbef9a3f7 , 0xc67178f2
};

/* ********************** DEFINIÇÕES DE FUNÇÃO ********************** */
void  sha256_transform (SHA256_CTX *ctx, const BYTE data[])
{
	PALAVRA a, b, c, d, e, f, g, h, i, j, t1, t2, m[ 64 ];

	para (i = 0 , j = 0 ; i < 16 ; ++i, j += 4 )
		m[i] = (dados[j] << 24 ) | (dados[j + 1 ] << 16 ) | (dados[j + 2 ] << 8 ) | (dados[j + 3 ]);
	para ( ; i < 64 ; ++i)
		m[i] = SIG1 (m[i - 2 ]) + m[i - 7 ] + SIG0 (m[i - 15 ]) + m[i - 16 ];

	a = ctx-> estado [ 0 ];
	b = ctx-> estado [ 1 ];
	c = ctx-> estado [ 2 ];
	d = ctx-> estado [ 3 ];
	e = ctx-> estado [ 4 ];
	f = ctx-> estado [ 5 ];
	g = ctx-> estado [ 6 ];
	h = ctx-> estado [ 7 ];

	for (i = 0 ; i < 64 ; ++i) {
		t1 = h + EP1 (e) + CH (e,f,g) + k[i] + m[i];
		t2 = EP0 (a) + MAJ (a,b,c);
		h = g;
		g = f;
		f = e;
		e = d + t1;
		d = c;
		c = b;
		b = a;
		a = t1 + t2;
	}

	ctx-> estado [ 0 ] += a;
	ctx-> estado [ 1 ] += b;
	ctx-> estado [ 2 ] += c;
	ctx-> estado [ 3 ] += d;
	ctx-> estado [ 4 ] += e;
	ctx-> estado [ 5 ] += f;
	ctx-> estado [ 6 ] += g;
	ctx-> estado [ 7 ] += h;
}

void  sha256_init (SHA256_CTX *ctx)
{
	ctx-> datalen = 0 ;
	ctx-> bitlen = 0 ;
	ctx-> estado [ 0 ] = 0x6a09e667 ;
	ctx-> estado [ 1 ] = 0xbb67ae85 ;
	ctx-> estado [ 2 ] = 0x3c6ef372 ;
	ctx-> estado [ 3 ] = 0xa54ff53a ;
	ctx-> estado [ 4 ] = 0x510e527f ;
	ctx-> estado [ 5 ] = 0x9b05688c ;
	ctx-> estado [ 6 ] = 0x1f83d9ab ;
	ctx-> estado [ 7 ] = 0x5be0cd19 ;
}

void  sha256_update (SHA256_CTX *ctx, const BYTE data[], size_t len)
{
	PALAVRA i;

	for (i = 0 ; i < len; ++i) {
		ctx-> data [ctx-> datalen ] = data[i];
		ctx-> datalen ++;
		if (ctx-> datalen == 64 ) {
			sha256_transform (ctx, ctx-> dados );
			ctx-> bitlen += 512 ;
			ctx-> datalen = 0 ;
		}
	}
}

void  sha256_final (SHA256_CTX *ctx, BYTE hash[])
{
	PALAVRA i;

	i = ctx-> datalen ;

	// Preencher quaisquer dados que restarem no buffer.
	if (ctx-> datalen < 56 ) {
		ctx-> dados [i++] = 0x80 ;
		enquanto (i < 56 )
			ctx-> dados [i++] = 0x00 ;
	}
	senão {
		ctx-> dados [i++] = 0x80 ;
		enquanto (i < 64 )
			ctx-> dados [i++] = 0x00 ;
		sha256_transform (ctx, ctx-> dados );
		memset (ctx-> data , 0 , 56 );
	}

	// Acrescenta ao preenchimento o comprimento total da mensagem em bits e transforma.
	ctx-> bitlen += ctx-> datalen * 8 ;
	ctx-> dados [ 63 ] = ctx-> bitlen ;
	ctx-> data [ 62 ] = ctx-> bitlen >> 8 ;
	ctx-> data [ 61 ] = ctx-> bitlen >> 16 ;
	ctx-> data [ 60 ] = ctx-> bitlen >> 24 ;
	ctx-> data [ 59 ] = ctx-> bitlen >> 32 ;
	ctx-> data [ 58 ] = ctx-> bitlen >> 40 ;
	ctx-> data [ 57 ] = ctx-> bitlen >> 48 ;
	ctx-> data [ 56 ] = ctx-> bitlen >> 56 ;
	sha256_transform (ctx, ctx-> dados );

	// Como essa implementação usa ordenação de bytes little endian e SHA usa big endian,
	// inverte todos os bytes ao copiar o estado final para o hash de saída.
	for (i = 0 ; i < 4 ; ++i) {
		hash[i] = (ctx-> estado [ 0 ] >> ( 24 - i * 8 )) & 0x000000ff ;
		hash[i + 4 ] = (ctx-> estado [ 1 ] >> ( 24 - i * 8 )) & 0x000000ff ;
		hash[i + 8 ] = (ctx-> estado [ 2 ] >> ( 24 - i * 8 )) & 0x000000ff ;
		hash[i + 12 ] = (ctx-> estado [ 3 ] >> ( 24 - i * 8 )) & 0x000000ff ;
		hash[i + 16 ] = (ctx-> estado [ 4 ] >> ( 24 - i * 8 )) & 0x000000ff ;
		hash[i + 20 ] = (ctx-> estado [ 5 ] >> ( 24 - i * 8 )) & 0x000000ff ;
		hash[i + 24 ] = (ctx-> estado [ 6 ] >> ( 24 - i * 8 )) & 0x000000ff ;
		hash[i + 28 ] = (ctx-> estado [ 7 ] >> ( 24 - i * 8 )) & 0x000000ff ;
	}
}
Rodapé
© 2022 GitHub, Inc.
Navegação de rodapé
Termos
Priv

Código: Selecionar todos

/ ************************************************* ********************
* Nome do arquivo: sha256.h
* Autor: Brad Conte (brad AT bradconte.com)
* Direito autoral:
* Isenção de responsabilidade: Este código é apresentado "como está" sem quaisquer garantias.
* Detalhes: define a API para a implementação SHA1 correspondente.
**************************************************** ****************** */

# ifndef SHA256_H
# define  SHA256_H

/* ************************** ARQUIVOS DE CABEÇALHO ******************** ****** */
# inclui  < stddef.h >

/* ***************************** MACROS ****************** *********** */
# define  SHA256_BLOCK_SIZE  32             // SHA256 gera um resumo de 32 bytes

/* ************************* TIPOS DE DADOS ******************** ******** */
typedef  unsigned  char BYTE;             // byte de 8 bits
typedef  unsigned  int   WORD;             // palavra de 32 bits, mude para "longa" para máquinas de 16 bits

 estrutura typedef {
	dados BYTE [ 64 ];
	PALAVRA dados;
	bitlen  longo longo  não assinado ;
	estado da PALAVRA[ 8 ];
} SHA256_CTX;

/* ********************* DECLARAÇÕES DE FUNÇÕES ********************* */
void  sha256_init (SHA256_CTX *ctx);
void  sha256_update (SHA256_CTX *ctx, const BYTE data[], size_t len);
void  sha256_final (SHA256_CTX *ctx, BYTE hash[]);

# endif    // SHA256_H

Código: Selecionar todos

/*
* Copyright 2004-2021 Os autores do projeto OpenSSL. Todos os direitos reservados.
*
* Licenciado sob a Apache License 2.0 (a "Licença"). Você não pode usar
* este arquivo, exceto em conformidade com a Licença. Você pode obter uma cópia
* no arquivo LICENSE na distribuição fonte ou em
* https://www.openssl.org/source/license.html
 */

/*
* As APIs de baixo nível SHA256 estão obsoletas para uso público, mas ainda ok para
* uso interno.
 */
# inclui  " internal/deprecated.h "

# inclui  < openssl/opensslconf.h >

# inclui  < stdlib.h >
# inclui  < string.h >

# inclui  < openssl/crypto.h >
# inclui  < openssl/sha.h >
# inclui  < openssl/opensslv.h >
# inclui  " internal/endian.h "

int  SHA224_Init (SHA256_CTX *c)
{
    memset (c, 0 , sizeof (*c));
    c-> h [ 0 ] = 0xc1059ed8UL ;
    c-> h [ 1 ] = 0x367cd507UL ;
    c-> h [ 2 ] = 0x3070dd17UL ;
    c-> h [ 3 ] = 0xf70e5939UL ;
    c-> h [ 4 ] = 0xffc00b31UL ;
    c-> h [ 5 ] = 0x68581511UL ;
    c-> h [ 6 ] = 0x64f98fa7UL ;
    c-> h [ 7 ] = 0xbefa4fa4UL ;
    c-> md_len = SHA224_DIGEST_LENGTH;
    retorno  1 ;
}

int  SHA256_Init (SHA256_CTX *c)
{
    memset (c, 0 , sizeof (*c));
    c-> h [ 0 ] = 0x6a09e667UL ;
    c-> h [ 1 ] = 0xbb67ae85UL ;
    c-> h [ 2 ] = 0x3c6ef372UL ;
    c-> h [ 3 ] = 0xa54ff53aUL ;
    c-> h [ 4 ] = 0x510e527fUL ;
    c-> h [ 5 ] = 0x9b05688cUL ;
    c-> h [ 6 ] = 0x1f83d9abUL ;
    c-> h [ 7 ] = 0x5be0cd19UL ;
    c-> md_len = SHA256_DIGEST_LENGTH;
    retorno  1 ;
}

int  SHA224_Update (SHA256_CTX *c, const  void *data, size_t len)
{
    return  SHA256_Update (c, dados, len);
}

int  SHA224_Final ( caracter não assinado  *md, SHA256_CTX *c)
{
    return  SHA256_Final (md, c);
}

# define  DATA_ORDER_IS_BIG_ENDIAN

# define  HASH_LONG                SHA_LONG
# define  HASH_CTX                 SHA256_CTX
# define  HASH_CBLOCK              SHA_CBLOCK

/*
* Observe que o FIPS180-2 discute "Truncation of the Hash Function Output".
* padrão: caso abaixo cobre para ele. Não está claro, no entanto, se é
* permitido truncar a quantidade de bytes não divisível por 4. Aposto que não,
* mas se for, então default: case deve ser estendido. Para referência.
* A ideia por trás de casos separados para comprimentos pré-definidos é deixar o
* compilador decide se é apropriado desenrolar pequenos loops.
 */
# define  HASH_MAKE_STRING ( c,s )    do { \
         ll longo não assinado ; \
        não assinado  int   nn; \
        switch ((c)-> md_len ) \
        {    case SHA224_DIGEST_LENGTH: \
                for (nn= 0 ;nn<SHA224_DIGEST_LENGTH/ 4 ;nn++) \
                { ll=(c)-> h [nn]; ( void ) HOST_l2c (ll,(s)); } \
                quebrar ; \
            caso SHA256_DIGEST_LENGTH: \
                for (nn= 0 ;nn<SHA256_DIGEST_LENGTH/ 4 ;nn++) \
                { ll=(c)-> h [nn]; ( void ) HOST_l2c (ll,(s)); } \
                quebrar ; \
            padrão : \
                if ((c)-> md_len > SHA256_DIGEST_LENGTH) \
                    retorna  0 ; \
                for (nn= 0 ;nn<(c)-> md_len / 4 ;nn++) \
                { ll=(c)-> h [nn]; ( void ) HOST_l2c (ll,(s)); } \
                quebrar ; \
        } \
        } enquanto ( 0 )

# define  HASH_UPDATE              SHA256_Update
# define  HASH_TRANSFORM           SHA256_Transform
# define  HASH_FINAL               SHA256_Final
# define  HASH_BLOCK_DATA_ORDER    sha256_block_data_order
# ifndef SHA256_ASM
estático
# endif
void  sha256_block_data_order (SHA256_CTX *ctx, const  void *in, size_t num);

# inclui  " crypto/md32_common.h "

# ifndef SHA256_ASM
 const estático SHA_LONG K256[ 64 ] = {
    0x428a2f98UL , 0x71374491UL , 0xb5c0fbcfUL , 0xe9b5dba5UL ,
    0x3956c25bUL , 0x59f111f1UL , 0x923f82a4UL , 0xab1c5ed5UL ,
    0xd807aa98UL , 0x12835b01UL , 0x243185beUL , 0x550c7dc3UL ,
    0x72be5d74UL , 0x80deb1feUL , 0x9bdc06a7UL , 0xc19bf174UL ,
    0xe49b69c1UL , 0xefbe4786UL , 0x0fc19dc6UL , 0x240ca1ccUL ,
    0x2de92c6fUL , 0x4a7484aaUL , 0x5cb0a9dcUL , 0x76f988daUL ,
    0x983e5152UL , 0xa831c66dUL , 0xb00327c8UL , 0xbf597fc7UL ,
    0xc6e00bf3UL , 0xd5a79147UL , 0x06ca6351UL , 0x14292967UL ,
    0x27b70a85UL , 0x2e1b2138UL , 0x4d2c6dfcUL , 0x53380d13UL ,
    0x650a7354UL , 0x766a0abbUL , 0x81c2c92eUL , 0x92722c85UL ,
    0xa2bfe8a1UL , 0xa81a664bUL , 0xc24b8b70UL , 0xc76c51a3UL ,
    0xd192e819UL , 0xd6990624UL , 0xf40e3585UL , 0x106aa070UL ,
    0x19a4c116UL , 0x1e376c08UL , 0x2748774cUL , 0x34b0bcb5UL ,
    0x391c0cb3UL , 0x4ed8aa4aUL , 0x5b9cca4fUL , 0x682e6ff3UL ,
    0x748f82eeUL , 0x78a5636fUL , 0x84c87814UL , 0x8cc70208UL ,
    0x90befffaUL , 0xa4506cebUL , 0xbef9a3f7UL , 0xc67178f2UL
};

# ifndef PEDÂNTICO
#   se definido(__GNUC__) && __GNUC__>=2 && \
      !definido(OPENSSL_NO_ASM) && !definido(OPENSSL_NO_INLINE_ASM)
#    se definido(__riscv_zknh)
#     define  Sigma0 ( x ) ({ MD32_REG_T ret; \
                        asm ( " sha256sum0 %0, %1 "     \
                        : " =r " (ret) \
                        : " r " (x)); ret; })
#     define  Sigma1 ( x ) ({ MD32_REG_T ret; \
                        asm ( " sha256sum1 %0, %1 "     \
                        : " =r " (ret) \
                        : " r " (x)); ret; })
#     define  sigma0 ( x ) ({ MD32_REG_T ret; \
                        asm ( " sha256sig0 %0, %1 "     \
                        : " =r " (ret) \
                        : " r " (x)); ret; })
#     define  sigma1 ( x ) ({ MD32_REG_T ret; \
                        asm ( " sha256sig1 %0, %1 "     \
                        : " =r " (ret) \
                        : " r " (x)); ret; })
#    endif
#    se definido(__riscv_zbt) || definido(__riscv_zpn)
#     define  Ch ( x,y,z ) ({ MD32_REG_T ret; \
                        asm ( " .insn r4 0x33, 1, 0x3, %0, %2, %1, %3 " \
                        : " =r " (ret) \
                        : " r " (x), " r " (y), " r " (z)); ret; })
#     define  Maj ( x,y,z ) ({ MD32_REG_T ret; \
                        asm ( " .insn r4 0x33, 1, 0x3, %0, %2, %1, %3 " \
                        : " =r " (ret) \
                        : " r " (x^z), " r " (y), " r " (x)); ret; })
#    endif
#   endif
# endif

/*
* A especificação FIPS refere-se a rotações corretas, enquanto nossa macro ROTATE
* resta um. É por isso que você pode notar que os coeficientes de rotação
* diferem dos observados no documento FIPS por 32-N...
 */
# ifndef Sigma0
#   define  Sigma0 ( x ) (ROTATE((x), 30 ) ^ ROTATE((x), 19 ) ^ ROTATE((x), 10 ))
# endif
# ifndef Sigma1
#   define  Sigma1 ( x ) (ROTATE((x), 26 ) ^ ROTATE((x), 21 ) ^ ROTATE((x), 7 ))
# endif
# ifndef sigma0
#   define  sigma0 ( x ) (ROTATE((x), 25 ) ^ ROTATE((x), 14 ) ^ ((x)>> 3 ))
# endif
# ifndef sigma1
#   define  sigma1 ( x ) (ROTATE((x), 15 ) ^ ROTATE((x), 13 ) ^ ((x)>> 10 ))
# endif
# ifndef Ch
#   define  Ch ( x,y,z ) (((x) & (y)) ^ ((~(x)) & (z)))
# endif
# ifndef maior
#   define  Maj ( x,y,z ) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
# endif

# ifdef OPENSSL_SMALL_FOOTPRINT

static  void  sha256_block_data_order (SHA256_CTX *ctx, const  void *in,
                                    size_t num)
{
    não assinado MD32_REG_T a, b, c, d, e, f, g, h, s0, s1, T1, T2;
    SHA_LONG X[ 16 ], l;
    int ;
    const  unsigned  char *data = in;

    while (num--) {

        a = ctx-> h [ 0 ];
        b = ctx-> h [ 1 ];
        c = ctx-> h [ 2 ];
        d = ctx-> h [ 3 ];
        e = ctx-> h [ 4 ];
        f = ctx-> h [ 5 ];
        g = ctx-> h [ 6 ];
        h = ctx-> h [ 7 ];

        for (i = 0 ; i < 16 ; i++) {
            ( void ) HOST_c2l (dados, l);
            T1 = X[i] = l;
            T1 += h + Sigma1 (e) + Ch (e, f, g) + K256[i];
            T2 = Sigma0 (a) + Maj (a, b, c);
            h = g;
            g = f;
            f = e;
            e = d + T1;
            d = c;
            c = b;
            b = a;
            a = T1 + T2;
        }

        for (; i < 64 ; i++) {
            s0 = X[(i + 1 ) & 0x0f ];
            s0 = sigma0 (s0);
            s1 = X[(i + 14 ) & 0x0f ];
            s1 = sigma1 (s1);

            T1 = X[i & 0xf ] += s0 + s1 + X[(i + 9 ) & 0xf ];
            T1 += h + Sigma1 (e) + Ch (e, f, g) + K256[i];
            T2 = Sigma0 (a) + Maj (a, b, c);
            h = g;
            g = f;
            f = e;
            e = d + T1;
            d = c;
            c = b;
            b = a;
            a = T1 + T2;
        }

        ctx-> h [ 0 ] += a;
        ctx-> h [ 1 ] += b;
        ctx-> h [ 2 ] += c;
        ctx-> h [ 3 ] += d;
        ctx-> h [ 4 ] += e;
        ctx-> h [ 5 ] += f;
        ctx-> h [ 6 ] += g;
        ctx-> h [ 7 ] += h;

    }
}

#mais _

#   define  ROUND_00_15 ( i,a,b,c,d,e,f,g,h )           do { \
        T1 += h + Sigma1 (e) + Ch (e,f,g) + K256[i]; \
        h = Sigma0 (a) + Maj (a,b,c); \
        d += T1; h += T1; } enquanto ( 0 )

#   define  ROUND_16_63 ( i,a,b,c,d,e,f,g,h,X )         do { \
        s0 = X[(i+ 1 )& 0x0f ]; s0 = sigma0 (s0); \
        s1 = X[(i+ 14 )& 0x0f ]; s1 = sigma1 (s1); \
        T1 = X[(i)& 0x0f ] += s0 + s1 + X[(i+ 9 )& 0x0f ]; \
        ROUND_00_15 (i,a,b,c,d,e,f,g,h); } enquanto ( 0 )

static  void  sha256_block_data_order (SHA256_CTX *ctx, const  void *in,
                                    size_t num)
{
    não assinado MD32_REG_T a, b, c, d, e, f, g, h, s0, s1, T1;
    SHA_LONG X[ 16 ];
    int ;
    const  unsigned  char *data = in;
    DECLARE_IS_ENDIAN;

    while (num--) {

        a = ctx-> h [ 0 ];
        b = ctx-> h [ 1 ];
        c = ctx-> h [ 2 ];
        d = ctx-> h [ 3 ];
        e = ctx-> h [ 4 ];
        f = ctx-> h [ 5 ];
        g = ctx-> h [ 6 ];
        h = ctx-> h [ 7 ];

        if (!IS_LITTLE_ENDIAN && sizeof (SHA_LONG) == 4
            && (( size_t ) em % 4 ) == 0 ) {
            const SHA_LONG *W = ( const SHA_LONG *)dados;

            T1 = X[ 0 ] = W[ 0 ];
            ROUND_00_15 ( 0 , a, b, c, d, e, f, g, h);
            T1 = X[ 1 ] = W[ 1 ];
            ROUND_00_15 ( 1 , h, a, b, c, d, e, f, g);
            T1 = X[ 2 ] = W[ 2 ];
            ROUND_00_15 ( 2 , g, h, a, b, c, d, e, f);
            T1 = X[ 3 ] = W[ 3 ];
            ROUND_00_15 ( 3 , f, g, h, a, b, c, d, e);
            T1 = X[ 4 ] = W[ 4 ];
            ROUND_00_15 ( 4 , e, f, g, h, a, b, c, d);
            T1 = X[ 5 ] = W[ 5 ];
            ROUND_00_15 ( 5 , d, e, f, g, h, a, b, c);
            T1 = X[ 6 ] = W[ 6 ];
            ROUND_00_15 ( 6 , c, d, e, f, g, h, a, b);
            T1 = X[ 7 ] = W[ 7 ];
            ROUND_00_15 ( 7 , b, c, d, e, f, g, h, a);
            T1 = X[ 8 ] = W[ 8 ];
            ROUND_00_15 ( 8 , a, b, c, d, e, f, g, h);
            T1 = X[ 9 ] = W[ 9 ];
            ROUND_00_15 ( 9 , h, a, b, c, d, e, f, g);
            T1 = X[ 10 ] = W[ 10 ];
            ROUND_00_15 ( 10 , g, h, a, b, c, d, e, f);
            T1 = X[ 11 ] = W[ 11 ];
            ROUND_00_15 ( 11 , f, g, h, a, b, c, d, e);
            T1 = X[ 12 ] = W[ 12 ];
            ROUND_00_15 ( 12 , e, f, g, h, a, b, c, d);
            T1 = X[ 13 ] = W[ 13 ];
            ROUND_00_15 ( 13 , d, e, f, g, h, a, b, c);
            T1 = X[ 14 ] = W[ 14 ];
            ROUND_00_15 ( 14 , c, d, e, f, g, h, a, b);
            T1 = X[ 15 ] = W[ 15 ];
            ROUND_00_15 ( 15 , b, c, d, e, f, g, h, a);

            dados += SHA256_CBLOCK;
        } senão {
            SHA_LONG l;

            ( void ) HOST_c2l (dados, l);
            T1 = X[ 0 ] = l;
            ROUND_00_15 ( 0 , a, b, c, d, e, f, g, h);
            ( void ) HOST_c2l (dados, l);
            T1 = X[ 1 ] = l;
            ROUND_00_15 ( 1 , h, a, b, c, d, e, f, g);
            ( void ) HOST_c2l (dados, l);
            T1 = X[ 2 ] = l;
            ROUND_00_15 ( 2 , g, h, a, b, c, d, e, f);
            ( void ) HOST_c2l (dados, l);
            T1 = X[ 3 ] = l;
            ROUND_00_15 ( 3 , f, g, h, a, b, c, d, e);
            ( void ) HOST_c2l (dados, l);
            T1 = X[ 4 ] = l;
            ROUND_00_15 ( 4 , e, f, g, h, a, b, c, d);
            ( void ) HOST_c2l (dados, l);
            T1 = X[ 5 ] = l;
            ROUND_00_15 ( 5 , d, e, f, g, h, a, b, c);
            ( void ) HOST_c2l (dados, l);
            T1 = X[ 6 ] = l;
            ROUND_00_15 ( 6 , c, d, e, f, g, h, a, b);
            ( void ) HOST_c2l (dados, l);
            T1 = X[ 7 ] = l;
            ROUND_00_15 ( 7 , b, c, d, e, f, g, h, a);
            ( void ) HOST_c2l (dados, l);
            T1 = X[ 8 ] = l;
            ROUND_00_15 ( 8 , a, b, c, d, e, f, g, h);
            ( void ) HOST_c2l (dados, l);
            T1 = X[ 9 ] = l;
            ROUND_00_15 ( 9 , h, a, b, c, d, e, f, g);
            ( void ) HOST_c2l (dados, l);
            T1 = X[ 10 ] = l;
            ROUND_00_15 ( 10 , g, h, a, b, c, d, e, f);
            ( void ) HOST_c2l (dados, l);
            T1 = X[ 11 ] = l;
            ROUND_00_15 ( 11 , f, g, h, a, b, c, d, e);
            ( void ) HOST_c2l (dados, l);
            T1 = X[ 12 ] = l;
            ROUND_00_15 ( 12 , e, f, g, h, a, b, c, d);
            ( void ) HOST_c2l (dados, l);
            T1 = X[ 13 ] = l;
            ROUND_00_15 ( 13 , d, e, f, g, h, a, b, c);
            ( void ) HOST_c2l (dados, l);
            T1 = X[ 14 ] = l;
            ROUND_00_15 ( 14 , c, d, e, f, g, h, a, b);
            ( void ) HOST_c2l (dados, l);
            T1 = X[ 15 ] = l;
            ROUND_00_15 ( 15 , b, c, d, e, f, g, h, a);
        }

        para (i = 16 ; i < 64 ; i += 8 ) {
            ROUND_16_63 (i + 0 , a, b, c, d, e, f, g, h, X);
            ROUND_16_63 (i + 1 , h, a, b, c, d, e, f, g, X);
            ROUND_16_63 (i + 2 , g, h, a, b, c, d, e, f, X);
            ROUND_16_63 (i + 3 , f, g, h, a, b, c, d, e, X);
            ROUND_16_63 (i + 4 , e, f, g, h, a, b, c, d, X);
            ROUND_16_63 (i + 5 , d, e, f, g, h, a, b, c, X);
            ROUND_16_63 (i + 6 , c, d, e, f, g, h, a, b, X);
            ROUND_16_63 (i + 7 , b, c, d, e, f, g, h, a, X);
        }

        ctx-> h [ 0 ] += a;
        ctx-> h [ 1 ] += b;
        ctx-> h [ 2 ] += c;
        ctx-> h [ 3 ] += d;
        ctx-> h [ 4 ] += e;
        ctx-> h [ 5 ] += f;
        ctx-> h [ 6 ] += g;
        ctx-> h [ 7 ] += h;

    }
}

# endif
# endif                          /* SHA256_ASM */


Código: Selecionar todos

/*-
 * Copyright (c) 2001-2003 Allan Saddi < allan@saddi.com >
 * Todos os direitos reservados.
 *
 * Redistribuição e uso nas formas fonte e binária, com ou sem
 * modificação, são permitidas desde que as seguintes condições
 * são atendidas:
 * 1. As redistribuições do código-fonte devem manter os direitos autorais acima
 * aviso, esta lista de condições e a seguinte isenção de responsabilidade.
 * 2. As redistribuições em formato binário devem reproduzir os direitos autorais acima
 * aviso, esta lista de condições e a seguinte isenção de responsabilidade no
 * documentação e/ou outros materiais fornecidos com a distribuição.
 *
 * ESTE SOFTWARE É FORNECIDO POR ALLAN SADDI E SEUS COLABORADORES ``COMO ESTÁ''
 * E QUAISQUER GARANTIAS EXPRESSAS OU IMPLÍCITAS, INCLUINDO, SEM LIMITAÇÃO, A
 * GARANTIAS IMPLÍCITAS DE COMERCIALIZAÇÃO E ADEQUAÇÃO A UM DETERMINADO FIM
 * SÃO ISENTOS. EM NENHUMA CIRCUNSTÂNCIA ALLAN SADDI OU SEUS COLABORADORES SERÃO
 * RESPONSÁVEL POR QUALQUER DIRETO, INDIRETO, INCIDENTAL, ESPECIAL, EXEMPLAR OU
 * DANOS CONSEQUENCIAIS (INCLUINDO, MAS NÃO SE LIMITANDO A, AQUISIÇÃO DE
 * SUBSTITUIR BENS OU SERVIÇOS; PERDA DE USO, DADOS OU LUCROS; OU NEGÓCIOS
 * INTERRUPÇÃO) POR QUALQUER TEORIA DE QUALQUER TEORIA DE RESPONSABILIDADE, SEJA EM
 * CONTRATO, RESPONSABILIDADE ESTRITA OU ATO ILÍCITO (INCLUINDO NEGLIGÊNCIA OU OUTRO)
 * DECORRENTE DE QUALQUER FORMA DO USO DESTE SOFTWARE, MESMO SE AVISADO DO
 * POSSIBILIDADE DE TAIS DANOS.
 *
 * $Id: sha256.c 680 2003-07-25 21:57:49Z asaddi $
 */

/*
 * Defina WORDS_BIGENDIAN se compilar em uma arquitetura big-endian.
 *
 * Defina SHA256_TEST para testar a implementação usando os NIST's
 * mensagens de amostra. A saída deve ser:
 *
 * ba7816bf 8f01cfea 414140de 5dae2223 b00361a3 96177a9c b410ff61 f20015ad
 * 248d6a61 d20638b8 e5c02693 0c3e6039 a33ce459 64ff2167 f6ecedd4 19db06c1
 * cdc76e5c 9914fb92 81a1c7e2 84d73e67 f1809a48 a497200e 046d39cc c7112cd0
 */

# ifdef  HAVE_CONFIG_H 
# inclui  "clamav-config.h" 
# endif  /* HAVE_CONFIG_H */

# if  HAVE_INTTYPES_H 
# inclui  <inttypes.h> 
# else 
# if  HAVE_STDINT_H 
#   inclui  <stdint.h> 
# endif 
# endif

# inclui  <string.h>

# inclui  "sha256.h"

# ifndef  lint 
static  const  char rcsid[] =
	 "$Id: sha256.c 680 2003-07-25 21:57:49Z asaddi $" ;
# endif  /* !lint */

# define  ROTL (x, n) (((x) << (n)) | ((x) >> (32 - (n))))
# define  ROTR (x, n) (((x) >> (n)) | ((x) << (32 - (n))))

# define  Ch (x, y, z) ((z) ^ ((x) & ((y) ^ (z))))
# define  Maj (x, y, z) (((x) & ((y) | (z))) | ((y) & (z)))
# define  SIGMA0 (x) (ROTR((x), 2) ^ ROTR((x), 13) ^ ROTR((x), 22))
# define  SIGMA1 (x) (ROTR((x), 6) ^ ROTR((x), 11) ^ ROTR((x), 25))
# define  sigma0 (x) (ROTR((x), 7) ^ ROTR((x), 18) ^ ((x) >> 3))
# define  sigma1 (x) (ROTR((x), 17) ^ ROTR((x), 19) ^ ((x) >> 10))

# define  DO_ROUND () { \
  t1 = h + SIGMA1(e) + Ch(e, f, g) + *(Kp++) + *(W++); \
  t2 = SIGMA0(a) + Maj(a, b, c); \
  h = g; \
  g = f; \
  f = e; \
  e = d + t1; \
  d = c; \
  c = b; \
  b = a; \
  a = t1 + t2; \
}

static  const uint32_t K[64] = {
  0x428a2f98L, 0x71374491L, 0xb5c0fbcfL, 0xe9b5dba5L,
  0x3956c25bL, 0x59f111f1L, 0x923f82a4L, 0xab1c5ed5L,
  0xd807aa98L, 0x12835b01L, 0x243185bel, 0x550c7dc3L,
  0x72be5d74L, 0x80deb1feL, 0x9bdc06a7L, 0xc19bf174L,
  0xe49b69c1L, 0xefbe4786L, 0x0fc19dc6L, 0x240ca1ccL,
  0x2de92c6fL, 0x4a7484aaL, 0x5cb0a9dcL, 0x76f988daL,
  0x983e5152L, 0xa831c66dL, 0xb00327c8L, 0xbf597fc7L,
  0xc6e00bf3L, 0xd5a79147L, 0x06ca6351L, 0x14292967L,
  0x27b70a85L, 0x2e1b2138L, 0x4d2c6dfcL, 0x53380d13L,
  0x650a7354L, 0x766a0abbL, 0x81c2c92eL, 0x92722c85L,
  0xa2bfe8a1L, 0xa81a664bL, 0xc24b8b70L, 0xc76c51a3L,
  0xd192e819L, 0xd6990624L, 0xf40e3585L, 0x106aa070L,
  0x19a4c116L, 0x1e376c08L, 0x2748774cL, 0x34b0bcb5L,
  0x391c0cb3L, 0x4ed8aa4aL, 0x5b9cca4fL, 0x682e6ff3L,
  0x748f82eeL, 0x78a5636fL, 0x84c87814L, 0x8cc70208L,
  0x90beffaL, 0xa4506cebL, 0xbef9a3f7L, 0xc67178f2L
};

# ifndef  RUNTIME_ENDIAN

# if  WORDS_BIGENDIAN == 1

# define  BYTESWAP (x) (x)
# define  BYTESWAP64 (x) (x)

# else  /* WORDS_BIGENDIAN */

# define  BYTESWAP (x) ((ROTR((x), 8) & 0xff00ff00L) | \
		     (ROTL((x), 8) & 0x00ff00ffL))
# define  BYTESWAP64 (x) _byteswap64(x)

uint64_t _byteswap64 em linha estática (uint64_t x)
{
  uint32_t a = x >> 32;
  uint32_t b = (uint32_t) x;
  return ((uint64_t) BYTESWAP(b) << 32) | (uint64_t) BYTESWAP(a);
}

# endif  /* WORDS_BIGENDIAN */

# else  /* !RUNTIME_ENDIAN */

# define  BYTESWAP (x) _byteswap(sc->littleEndian, x)
# define  BYTESWAP64 (x) _byteswap64(sc->littleEndian, x)

# define  _BYTESWAP (x) ((ROTR((x), 8) & 0xff00ff00L) | \
		      (ROTL((x), 8) & 0x00ff00ffL))
# define  _BYTESWAP64 (x) __byteswap64(x)

uint64_t __byteswap64 em linha estática (uint64_t x)
{
  uint32_t a = x >> 32;
  uint32_t b = (uint32_t) x;
  return ((uint64_t) _BYTESWAP(b) << 32) | (uint64_t) _BYTESWAP(a);
}

uint32_t _byteswap inline estático ( int littleEndian, uint32_t x)
{
  if (!littleEndian)
     return x;
  senão 
    retorna _BYTESWAP(x);
}

estático em linha uint64_t _byteswap64 ( int littleEndian, uint64_t x)
{
  if (!littleEndian)
     return x;
  senão 
    retorna _BYTESWAP64(x);
}

void  inline estático setEndian ( int *littleEndianp)
{
  união {
    uint32_t w;
    uint8_t b[4];
  } endian;

  endian.w = 1L;
  *littleEndianp = endian.b[0] != 0;
}

# endif  /* !RUNTIME_ENDIAN */

preenchimento estático  const uint8_t[64] = {
  0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};

void 
sha256_init (SHA256_CTX *sc)
{
# ifdef  RUNTIME_ENDIAN
  setEndian (&sc->littleEndian);
# endif  /* RUNTIME_ENDIAN */

  sc->comprimento total = 0LL;
  sc->hash[0] = 0x6a09e667L;
  sc->hash[1] = 0xbb67ae85L;
  sc->hash[2] = 0x3c6ef372L;
  sc->hash[3] = 0xa54ff53aL;
  sc->hash[4] = 0x510e527fL;
  sc->hash[5] = 0x9b05688cL;
  sc->hash[6] = 0x1f83d9abL;
  sc->hash[7] = 0x5be0cd19L;
  sc->bufferLength = 0L;
}

static  void 
burnStack ( tamanho int )
{
  char buf[128];

  memset (buf, 0, sizeof (buf));
  tamanho -= sizeof (buf);
  se (tamanho > 0)
    burnStack (tamanho);
}

 vazio 
estático SHA256Guts (SHA256_CTX *sc, const uint32_t *cbuf)
{
  uint32_t buf[64];
  uint32_t *W, *W2, *W7, *W15, *W16;
  uint32_t a, b, c, d, e, f, g, h;
  uint32_t t1, t2;
  const uint32_t *Kp;
  int ;

  W = buf;

  para (i = 15; i >= 0; i--) {
    *(W++) = BYTESWAP(*cbuf);
    cbuf++;
  }

  W16 = &buf[0];
  W15 = &buf[1];
  W7 = &buf[9];
  W2 = &buf[14];

  para (i = 47; i >= 0; i--) {
    *(W++) = sigma1(*W2) + *(W7++) + sigma0(*W15) + *(W16++);
    W2++;
    W15++;
  }

  a = sc->hash[0];
  b = sc->hash[1];
  c = sc->hash[2];
  d = sc->hash[3];
  e = sc->hash[4];
  f = sc->hash[5];
  g = sc->hash[6];
  h = sc->hash[7];

  Kp = K;
  W = buf;

# ifndef  SHA256_UNROLL 
# define  SHA256_UNROLL 4
# endif  /* !SHA256_UNROLL */

# if  SHA256_UNROLL == 1
   for (i = 63; i >= 0; i--)
    DO_ROUND();
# elif  SHA256_UNROLL == 2
   for (i = 31; i >= 0; i--) {
    DO_ROUND(); DO_ROUND();
  }
# elif  SHA256_UNROLL == 4
   for (i = 15; i >= 0; i--) {
    DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
  }
# elif  SHA256_UNROLL == 8
   for (i = 7; i >= 0; i--) {
    DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
    DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
  }
# elif  SHA256_UNROLL == 16
   for (i = 3; i >= 0; i--) {
    DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
    DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
    DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
    DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
  }
# elif  SHA256_UNROLL == 32
   for (i = 1; i >= 0; i--) {
    DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
    DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
    DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
    DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
    DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
    DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
    DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
    DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
  }
# elif  SHA256_UNROLL == 64
  DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
  DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
  DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
  DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
  DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
  DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
  DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
  DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
  DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
  DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
  DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
  DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
  DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
  DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
  DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
  DO_ROUND(); DO_ROUND(); DO_ROUND(); DO_ROUND();
# else 
# erro  "SHA256_UNROLL deve ser 1, 2, 4, 8, 16, 32 ou 64!" 
# endif

  sc->hash[0] += a;
  sc->hash[1] += b;
  sc->hash[2] += c;
  sc->hash[3] += d;
  sc->hash[4] += e;
  sc->hash[5] += f;
  sc->hash[6] += g;
  sc->hash[7] += h;
}

void 
sha256_update (SHA256_CTX *sc, const  void *vdata, uint32_t len)
{
  const uint8_t *data = vdata;
  uint32_t bufferBytesLeft;
  uint32_t bytesToCopy;
  int necessidadeQueima = 0;
# ifdef  SHA256_FAST_COPY 
  if (sc->bufferLength) {
    bufferBytesLeft = 64L - sc->bufferLength;

    bytesToCopy = bufferBytesLeft;
    if (bytesToCopy > len)
      bytesToCopy = len;

    memcpy (&sc->buffer.bytes[sc->bufferLength], data, bytesToCopy);

    sc->totalLength += bytesToCopy * 8L;

    sc->bufferLength += bytesToCopy;
    dados += bytesToCopy;
    len -= bytesToCopy;

    if (sc->bufferLength == 64L) {
      SHA256Guts (sc, sc->buffer.words);
      necessidade de queima = 1;
      sc->bufferLength = 0L;
    }
  }

  enquanto (len > 63L) {
    sc->comprimento total += 512L;

    SHA256Guts (sc, dados);
    necessidade de queima = 1;

    dados += 64L;
    len -= 64L;
  }

  if (len) {
    memcpy (&sc->buffer.bytes[sc->bufferLength], data, len);

    sc->comprimento total += len * 8L;

    sc->bufferLength += len;
  }
# else  /* SHA256_FAST_COPY */ 
  while (len) {
    bufferBytesLeft = 64L - sc->bufferLength;

    bytesToCopy = bufferBytesLeft;
    if (bytesToCopy > len)
      bytesToCopy = len;

    memcpy (&sc->buffer.bytes[sc->bufferLength], data, bytesToCopy);

    sc->totalLength += bytesToCopy * 8L;

    sc->bufferLength += bytesToCopy;
    dados += bytesToCopy;
    len -= bytesToCopy;

    if (sc->bufferLength == 64L) {
      SHA256Guts (sc, sc->buffer.words);
      necessidade de queima = 1;
      sc->bufferLength = 0L;
    }
  }
# endif  /* SHA256_FAST_COPY */

  se (precisarQueimar)
    burnStack ( sizeof (uint32_t[74]) + sizeof (uint32_t *[6]) + sizeof ( int ));
}

void 
sha256_final (SHA256_CTX *sc, uint8_t hash[SHA256_HASH_SIZE])
{
  uint32_t bytesToPad;
  uint64_t comprimentoPad;
  int ;

  bytesToPad = 120L - sc->bufferLength;
  if (bytesToPad > 64L)
    bytesToPad -= 64L;

  comprimentoPad = BYTESWAP64(sc->totalLength);

  sha256_update (sc, preenchimento, bytesToPad);
  sha256_update (sc, &lengthPad, 8L);

  if (hash) {
     for (i = 0; i < SHA256_HASH_WORDS; i++) {
# ifdef  SHA256_FAST_COPY
      *((uint32_t *) hash) = BYTESWAP(sc->hash[i]);
# else  /* SHA256_FAST_COPY */
      hash[0] = (uint8_t) (sc->hash[i] >> 24);
      hash[1] = (uint8_t) (sc->hash[i] >> 16);
      hash[2] = (uint8_t) (sc->hash[i] >> 8);
      hash[3] = (uint8_t) sc->hash[i];
# endif  /* SHA256_FAST_COPY */
      hash += 4;
    }
  }
}

# ifdef  SHA256_TEST

# include  <stdio.h> 
# include  <stdlib.h> 
# include  <string.h>

int 
main ( int argc, char *argv[])
{
  SHA256_CTX foo;
  uint8_t hash[SHA256_HASH_SIZE];
  char buf[1000];
  int ;

  sha256_init (&foo);
  sha256_update (&foo, "abc" , 3);
  sha256_final (&foo, hash);

  for (i = 0; i < SHA256_HASH_SIZE;) {
    printf( "%02x" , hash[i++]);
    se (!(i % 4))
      printf( " " );
  }
  printf( "\n" );

  sha256_init (&foo);
  sha256_update (&foo,
		"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" ,
		56);
  sha256_final (&foo, hash);

  for (i = 0; i < SHA256_HASH_SIZE;) {
    printf( "%02x" , hash[i++]);
    se (!(i % 4))
      printf( " " );
  }
  printf( "\n" );

  sha256_init (&foo);
  memset (buf, 'a' , sizeof (buf));
  para (i = 0; i < 1000; i++)
    sha256_update (&foo, buf, sizeof (buf));
  sha256_final (&foo, hash);

  for (i = 0; i < SHA256_HASH_SIZE;) {
    printf( "%02x" , hash[i++]);
    se (!(i % 4))
      printf( " " );
  }
  printf( "\n" );

  saída (0);
}

# endif  /* SHA256_TEST */




aqui tambem tem alguma coisa... https://web.mit.edu/freebsd/head/contri ... rc/crypto/
Delpji 7, harbour 3.2, xharbour 1.2.3, Bcc7, Minigw, Minigui 19.11, hwgui 2.20, FiveWin 19.05 Gtwvw, Gtwvg, C# VS 2017
malcarli
Usuário Nível 3
Usuário Nível 3
Mensagens: 239
Registrado em: 20 Ago 2015 18:14
Localização: marilia/sp

Assinar com Sha256

Mensagem por malcarli »

a primeira função consegui compilar no harbour (tem umas pequenas alterações de tradução), mas agora tentando entender como chamar
Avatar do usuário
Itamar M. Lins Jr.
Administrador
Administrador
Mensagens: 7928
Registrado em: 30 Mai 2007 11:31
Localização: Ilheus Bahia
Curtiu: 1 vez

Assinar com Sha256

Mensagem por Itamar M. Lins Jr. »

Olá!
O Harbour tem a função hb_sha256().

Código: Selecionar todos

itamar@itamar-desktop:~$ hbmk2 -find sha256
Núcleo Harbour (instalado):
   hb_HMAC_SHA256()
   hb_SHA256()
hbcrypto.hbc (não instalado):
   hb_pbkdf2_sha256()
itamar@itamar-desktop:~$ 
Saudações,
Itamar M. Lins Jr.
Saudações,
Itamar M. Lins Jr.
Avatar do usuário
Itamar M. Lins Jr.
Administrador
Administrador
Mensagens: 7928
Registrado em: 30 Mai 2007 11:31
Localização: Ilheus Bahia
Curtiu: 1 vez

Assinar com Sha256

Mensagem por Itamar M. Lins Jr. »

Olá!
Achei esse aqui que assina com PFX.
https://groups.google.com/g/harbour-use ... pFwjQQBgAJ

Código: Selecionar todos

HB_FUNC( HB_CMS_SIGNFILE_PFX )
{
	// HB_SignFile( Archivo a firmar, Archivo .pfx, clave, Archivo Firmado)
    BIO *in = NULL, *out = NULL;
    CMS_ContentInfo *cms = NULL;
	X509 *x509;
	EVP_PKEY *priKey;
	FILE *fp;
	PKCS12 *p12;
	STACK_OF(X509) *ca = NULL;
	OpenSSL_add_all_algorithms();
	OpenSSL_add_all_ciphers();
	int flags = CMS_PARTIAL;

    if ((fp = fopen(hb_parc(2), "rb")) == NULL) {
        hb_retni( 2 );
        return;
    }
    p12 = d2i_PKCS12_fp(fp, NULL);
    fclose(fp);
    if (!p12) {
        hb_retni( 3 );
        return;
    }
    if (!PKCS12_parse(p12, hb_parc(3), &priKey, &x509, &ca)) {
        hb_retni( 4 );
        return;
	}
    PKCS12_free(p12);	

//abre el archivo a firmar	
    in = BIO_new_file(hb_parc(1), "r");
    if (!in) {
		hb_retni(5); //error al crear objeto in
		return;		
	}

//crea el cms
    cms = CMS_sign(NULL, NULL, NULL, in, flags);
    if (!cms) {
		hb_retni(6); //error al crear objeto cms
		return;		
	}
	
	CMS_SignerInfo *si;
    si = CMS_add1_signer(cms, x509, priKey, EVP_sha1(), flags);
	if (!si) {
		hb_retni(8); //error al crear objeto cms
		return;		
	}

	if (!CMS_final(cms, in, NULL, flags)) {
		hb_retni(9); //error al crear objeto cms
		return;		
	}
 	
	
	out = BIO_new_file(hb_parc(4), "wb");
    if (!out) {
		hb_retni(10); //error al abrir el archivo toSignFile
		return;		
	}
    BIO_reset(in);
	
	
	//if(!PEM_write_bio_CMS_stream(out,cms, in, flags)) {//lo graba en formato PEM
	//if (!SMIME_write_CMS(out, cms, in, flags)) { //lo graba en formato SMIME
	if (!i2d_CMS_bio_stream(out,cms, in, flags)) {//lo graba en formato DER
		hb_retni(11); //error al grabar el archivo toSignFile
		return;		
	}
    CMS_ContentInfo_free(cms);
	X509_free(x509);
    BIO_free(in);
    BIO_free(out);
	hb_retni( 1 );
	return;	

Código: Selecionar todos

/*
   hbmk2 tip4.prg hbssl.hbc

*/
#require "hbssl"
#include "hbssl.ch"

Function main()
Local ERROR
setmode(25,80)
clear


/*RESULTADO
		 1: Signing OK
		 2: error opening .pfx file
		 3: error opening key file
		 4: error creating PrivateKey object
		 5: the Key does not correspond to the Certificate
		 6: error opening file to sign
		 7: error creating cms object
		 8: error asigning data to cms object
		 9: error closing data structure of cms object
		10: error creating out file
		11: error generating final cms file*/

ERROR:=HB_CMS_SignFile( "TRA.XML", "CERT.PFX", "CERT.KEY", "TRA.TMP")
if (ERROR!=1)
	? ERROR
endif

return
Saudações,
Itamar M. Lins Jr.
Saudações,
Itamar M. Lins Jr.
malcarli
Usuário Nível 3
Usuário Nível 3
Mensagens: 239
Registrado em: 20 Ago 2015 18:14
Localização: marilia/sp

Assinar com Sha256

Mensagem por malcarli »

Excelente amigo, valeu, agora estudar para adaptar na classe do mestre quintas para assinar o esocial.
malcarli
Usuário Nível 3
Usuário Nível 3
Mensagens: 239
Registrado em: 20 Ago 2015 18:14
Localização: marilia/sp

Assinar com Sha256

Mensagem por malcarli »

Voltando a saga de assinar o esocial que usa sha256, ao invés de sha1 da nfe. Estudando melhor um exemplo do Mestre Quintas, consegui gerar a chave de assinatura. Criei as tags, mas [<SignatureValue>] + cSignatureValue + [</SignatureValue>] está errada, pois é o mesmo conteúdo do certificado em [<X509Certificate>] + cPublicKey + [</X509Certificate>]. Como fazer, eis a questão. Ajuda será vem vindo.

Código: Selecionar todos

/*
https://pctoledo.org/forum/viewtopic.php?f=43&t=18664
*/

#define __TESTE__
#include "minigui.ch"

#include "sefaz_capicom.ch"
#include "hbclass.ch"
#ifdef __TESTE__

PROCEDURE TesteCapicom
   LOCAL cTexto, cSignatureValue, cDigestValue, cPublicKey

   cTexto    := [<?xml version="1.0" encoding="UTF-8"?><eSocial xmlns="http://www.esocial.gov.br/schema/lote/eventos/envio/v1_1_1"><envioLoteEventos grupo="2"><ideEmpregador><tpInsc>1</tpInsc><nrInsc>11956884</nrInsc></ideEmpregador><ideTransmissor><tpInsc>1</tpInsc><nrInsc>08743913000100</nrInsc></ideTransmissor><eventos><evento Id="ID1119568840000002022090509510600001"><eSocial xmlns="http://www.esocial.gov.br/schema/evt/evtExpRisco/v_S_01_00_00"><evtExpRisco Id="ID1119568840000002022090509510600001"><ideEvento><indRetif>1</indRetif><tpAmb>2</tpAmb><procEmi>1</procEmi><verProc>Versao22085</verProc></ideEvento><ideEmpregador><tpInsc>1</tpInsc><nrInsc>11956884</nrInsc></ideEmpregador><ideVinculo><cpfTrab>03606687982</cpfTrab><matricula>22</matricula></ideVinculo><infoExpRisco><dtIniCondicao>2022-01-10</dtIniCondicao><infoAmb><localAmb>1</localAmb><dscSetor>ADMINISTRACAO</dscSetor><tpInsc>1</tpInsc><nrInsc>11956884000179</nrInsc></infoAmb><infoAtiv><dscAtivDes>Responsavel por presta suporte na gestao da empresa auxiliando principalmente gestores de financas gestao de pessoal e da area operacional na realizacao de atividades de controle e emissao de documentos</dscAtivDes></infoAtiv><agNoc><codAgNoc>09.01.001</codAgNoc></agNoc><respReg><cpfResp>11417960400</cpfResp><ideOC>1</ideOC><nrOC>4847</nrOC><ufOC>PR</ufOC></respReg></infoExpRisco></evtExpRisco>]

   cDigestValue    := CapicomClass():HashData( cTexto )
   cSignatureValue := CapicomClass():Sign( cDigestValue, , , @cPublicKey )

   cPublicKey     := StrTran(cPublicKey, Chr(13) + Chr(10), [])
   cDigestValue   := StrTran(cDigestValue, Chr(13) + Chr(10), [])
   cSignatureValue:= StrTran(cSignatureValue, Chr(13) + Chr(10), [])

   cURI:= []

   cTexto += [<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">]
   cTexto +=    [<SignedInfo>]
   cTexto +=       [<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>]
   cTexto +=       [<SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />] 
   cTexto +=       [<Reference URI="] + cURI + [">]
   cTexto +=       [<Transforms>]
   cTexto +=          [<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />]
   cTexto +=          [<Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />]
   cTexto +=       [</Transforms>]
   cTexto +=       [<DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />]
   cTexto +=       [<DigestValue>] + cDigestValue + [</DigestValue>]
   cTexto +=       [</Reference>]
   cTexto +=    [</SignedInfo>]
   cTexto +=    [<SignatureValue>] + cSignatureValue + [</SignatureValue>]
   cTexto +=    [<KeyInfo>]
   cTexto +=       [<X509Data>]
   cTexto +=          [<X509Certificate>] + cPublicKey + [</X509Certificate>]
   cTexto +=       [</X509Data>]
   cTexto +=    [</KeyInfo>]
   cTexto += [</Signature>]
   cTexto += [</eSocial></evento></eventos></envioLoteEventos></eSocial>]

   Hb_memowrit(".\assinado-esocial-loteevt.xml", cTexto)

   RETURN
#endif

FUNCTION IsValidSignatureCapicom( cDigestValue, cSignatureValue )

   IF cDigestValue = NIL .OR. cSignatureValue = NIL
      RETURN .F.
   ENDIF

   RETURN CapicomClass():VerifySignature( cSignatureValue ) == cDigestValue

CREATE CLASS CapicomClass

   METHOD SelectCertificate()
   METHOD VerifySignature( cSignedData )
   METHOD HashData( cData, nAlgorithm )
   METHOD PublicKey( oCAPICOMCert )
   METHOD Sign( cDigestValue, oCAPICOMcert, nEncode, cPublicKey )

   ENDCLASS

METHOD SelectCertificate() CLASS CapicomClass

   LOCAL oCapicom, oCertificate

   oCapicom:= win_OleCreateObject( "CAPICOM.Store" )
   oCapicom:Open( CAPICOM_CURRENT_USER_STORE, "My", CAPICOM_STORE_OPEN_READ_ONLY )
   BEGIN SEQUENCE WITH { || __BreakBlock() }
      oCertificate := oCapicom:Certificates:Select( "Selecione um certificado digital", "Algoritmo de Assinatura SHA256RSA" )
   ENDSEQUENCE

   IF oCapicom:Certificates:Count() == 0
      RETURN NIL
   ENDIF

   RETURN oCertificate:Item( 1 )

METHOD VerifySignature( cSignedData ) CLASS CapicomClass

   LOCAL oCapicom

   IF cSignedData == NIL
      RETURN NIL
   ENDIF

   oCapicom := win_OleCreateObject( "CAPICOM.SignedData.1" )
   oCapicom:Verify( cSignedData, .F., CAPICOM_VERIFY_SIGNATURE_ONLY )

   RETURN oCapicom:Content

METHOD HashData( cData, nAlgorithm ) CLASS CapicomClass

   LOCAL oCapicom, oUtil

   IF cData = NIL
      cData := Dtos( Date() ) + Time()
   ENDIF

   IF nAlgorithm = NIL
      nAlgorithm := CAPICOM_HASH_ALGORITHM_SHA1 // 256
   ENDIF

   oUtil    := win_OleCreateObject( "CAPICOM.Utilities" )
   oCapicom := win_OleCreateObject( "CAPICOM.HashedData.1" )
   oCapicom:Algorithm := nAlgorithm
   oCapicom:Hash( cData )

   RETURN oUtil:Base64Encode( outil:HexToBinary( oCapicom:Value ) )
   // RETURN oCapicom:Value

METHOD PublicKey( oCapicomCert ) CLASS CapicomClass

   LOCAL cPublicKey

   //oCapicom := win_OleCreateObject( "CAPICOM.Signer.2" )
   //oCapicom:Signer:Certificate := oCAPICOMCert
   //oCapicom:Signer:Options := CAPICOM_CERTIFICATE_INCLUDE_CHAIN_EXCEPT_ROOT
   cPublicKey := StrTran( /* oCapicom:Certificate:*/ oCapicomCert:Export( CAPICOM_ENCODE_BASE64 ), Chr(13) + Chr(10), "" )

   RETURN cPublicKey

METHOD Sign( cDigestValue, oCAPICOMCert, nEncode, cPublicKey ) CLASS CapicomClass

   LOCAL oCAPICOMSignedData, oCAPICOMSigner, oCAPICOMTimeStamp, cSignature

   IF cDigestValue = NIL
      RETURN NIL
   ENDIF

   IF nEncode = NIL
      nEncode := CAPICOM_ENCODE_BASE64
   ENDIF

   oCAPICOMSigner := win_OleCreateObject( "CAPICOM.Signer.2" ) // versao 2

   IF oCAPICOMCert = NIL
      oCAPICOMCert := ::SelectCertificate()
      IF oCAPICOMCert = NIL
         RETURN NIL
      ENDIF
      oCAPICOMSigner:Certificate := oCAPICOMcert
   ELSE
      oCAPICOMSigner:Certificate := oCAPICOMcert:DefaultInterface
   ENDIF

   IF ! ( oCAPICOMSigner:Certificate:HasPrivateKey ;
         .AND. Dtos( oCAPICOMSigner:Certificate:ValidFromDate ) <= Dtos( Date() ) ;
         .AND. Dtos( oCAPICOMSigner:Certificate:ValidToDate ) >= Dtos( Date() ) )
      RETURN NIL
   ENDIF

   oCAPICOMSigner:Options := CAPICOM_CERTIFICATE_INCLUDE_CHAIN_EXCEPT_ROOT
   cPublicKey             := StrTran( oCAPICOMSigner:Certificate:Export( CAPICOM_ENCODE_BASE64 ), Chr(13) + Chr(10), "" )

   oCAPICOMTimeStamp := win_OleCreateObject( "CAPICOM.Attribute" )
   oCAPICOMTimeStamp:Name  := CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME
   oCAPICOMTimeStamp:Value := hb_DateTime()

   oCAPICOMSigner:AuthenticatedAttributes:Add( oCAPICOMTimeStamp )

   oCAPICOMSignedData := win_OleCreateObject( "CAPICOM.SignedData.1" )
   oCAPICOMSignedData:Content := cDigestValue

   // segundo parametro falso, apenas retona assinatura do texto, não inclui no texto
   cSignature := oCAPICOMSignedData:Sign( oCAPICOMSigner, .F., nEncode )

   RETURN cSignature

Anexos
02503687000103_20220930T164803-ret-esocial-consloteevt.xml
(1.9 KiB) Baixado 297 vezes
Avatar do usuário
JoséQuintas
Administrador
Administrador
Mensagens: 20267
Registrado em: 26 Fev 2007 11:59
Localização: São Paulo-SP

Assinar com Sha256

Mensagem por JoséQuintas »

Por esse caminho vai ser mais difícil conseguir.
Faça igual sefazclass, e troque somente o bloco de assinatura.
Se não der certo, é partir pra outra solução, ACBR ou outra.
NÃO SEI se no fórum internacional podem dar alguma dica.
Aquelas informações no bloco de assinatura indicam como deve ser feita, e carregar para o objeto DOMDOC faz ajustes no XML que sejam necessários, assim como algum detalhe de codepage.

Tentei muito desse jeito pra NFE, na época, sem sucesso.

Mas se por acaso descobrir como fazer, até mudamos a sefazclass pra não precisar do MSXML5.
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"

https://github.com/JoseQuintas/
Avatar do usuário
JoséQuintas
Administrador
Administrador
Mensagens: 20267
Registrado em: 26 Fev 2007 11:59
Localização: São Paulo-SP

Assinar com Sha256

Mensagem por JoséQuintas »

Acrescentando:

MSXML5 é o único que trata assinatura, e saiu como parte do Office.
MSXML2, MSXML3, MSXML4 e MSXML6 fazem parte do Windows.

NÃO SEI se a Microsoft lançou alguma coisa nova depois.
Quem sabe não pode existir versão nova equivalente, que tenha recurso a mais.
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"

https://github.com/JoseQuintas/
Avatar do usuário
JoséQuintas
Administrador
Administrador
Mensagens: 20267
Registrado em: 26 Fev 2007 11:59
Localização: São Paulo-SP

Assinar com Sha256

Mensagem por JoséQuintas »

Também faltou dizer:

Confirme se está usando a última versão da CAPICOM.
Se não me engano, sha256 foi adicionado na última.
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"

https://github.com/JoseQuintas/
Avatar do usuário
JoséQuintas
Administrador
Administrador
Mensagens: 20267
Registrado em: 26 Fev 2007 11:59
Localização: São Paulo-SP

Assinar com Sha256

Mensagem por JoséQuintas »

capicom.png
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"

https://github.com/JoseQuintas/
malcarli
Usuário Nível 3
Usuário Nível 3
Mensagens: 239
Registrado em: 20 Ago 2015 18:14
Localização: marilia/sp

Assinar com Sha256

Mensagem por malcarli »

Bom dia mestre, usando a capicom 2.1.0.2,que assina sha256. A minha incompentencia está em colocar o bloco de assinatura no arquivo.
Responder