FirmaSAT .NET Class Library 10.50.0

Classes | Methods | Enumerations | Index
FirmaSAT Namespace

A .NET interface for FirmaSAT

Classes

Methods

General Class Methods

Sat Class Methods

Tfd Class Methods


General.Comments Method

Get additional information about the core DLL module.

Syntax

[C#]
public static string Comments()
[VB.NET]
Public Shared Function Comments As String

Return Value

Comments string

Example

[C#]
Console.WriteLine(General.Comments());
// Licensed Developer Edition | Edicion de Desarrollador Licenciado.

General.CompileTime Method

Get date and time the core DLL module was last compiled.

Syntax

[C#]
public static string CompileTime()
[VB.NET]
Public Shared Function CompileTime As String

Return Value

Date and time string.

Example

[C#]
Console.WriteLine(General.CompileTime());  // Feb 28 2021 18:29:46

General.ErrorLookup Method

Look up error code.

Syntax

[C#]
public static string ErrorLookup(
	int errCode
)
[VB.NET]
Public Shared Function ErrorLookup ( _
	errCode As Integer _
) As String

Parameters

errCode
Code number (may be positive or negative)

Return Value

Corresponding error message

Example

[C#]
Console.WriteLine(General.ErrorLookup(-10));
// Required data not found/Datos necesarios no encontrados (MISSING_ERROR)

General.FormatErrorMessage Method

Return an error message string for the last error.

Syntax

[C#]
public static string FormatErrorMessage(
	int errCode
)
[VB.NET]
Public Shared Function FormatErrorMessage ( _
	errCode As Integer _
) As String

Parameters

errCode
Error code returned by last call (optional)

Return Value

Error message as a string Error ({errCode}): {errorlookup}[: {lasterror}]

Example

[C#]
// Error (-28): XML restriction is violated/XML restriccion es violada (XML_FACET_ERROR):
// Bad attribute/atributo mal [iedu:instEducativas/@CURP] (line 30):
// 'JUAN01010101GTOHMD0' is too long/es demasiado largo, maximum length/longitud maxima=18

General.LastError Method

Retrieve the last error message.

Syntax

[C#]
public static string LastError()
[VB.NET]
Public Shared Function LastError As String

Return Value

Error message from last call (may be empty)

Remarks

Call this immediately when an error is indicated. Calling another method will overwrite the message. This is the same as Sat.LastError().

Example

[C#]
int n = Sat.ValidateXml("cfdv33a-badspec.xml");
Console.WriteLine("Sat.ValidateXml returns {0}", n);
// Sat.ValidateXml returns -27
Console.WriteLine(General.ErrorLookup(n));
// Invalid XML format/No valido formato XML (BAD_XML_ERROR)
Console.WriteLine(General.LastError());
// XML validation error/Error al validar XML: Required attribute 'Importe' missing for element 'cfdi:Concepto' (Line/numero de linea: 12); 
// XML validation error/Error al validar XML: Required attribute 'Importe' missing for element 'cfdi:Concepto' (Line/numero de linea: 13)

General.LicenceType Method

Get licence type.

Syntax

[C#]
public static char LicenceType()
[VB.NET]
Public Shared Function LicenceType As Char

Return Value

D=Developer T=Trial

General.ModuleName Method

Get full path name of core diFirmaSat DLL module.

Syntax

[C#]
public static string ModuleName()
[VB.NET]
Public Shared Function ModuleName As String

Return Value

File path.

Example

[C#]
Console.WriteLine(General.ModuleName());  // C:\WINDOWS\SYSTEM32\diFirmaSAT2.dll

General.Platform Method

Get the platform for which the core native DLL was compiled.

Syntax

[C#]
public static string Platform()
[VB.NET]
Public Shared Function Platform As String

Return Value

"Win32" or "Win64"

General.Version Method

Return version number of core diFirmaSat DLL.

Syntax

[C#]
public static int Version()
[VB.NET]
Public Shared Function Version As Integer

Return Value

Version number in form Major*10000 + Minor*100 + Release

Remarks

For example, version 9.2.15 returns 90215

Example

[C#]
int n = General.Version();
Console.WriteLine("Version = {0}", n);  // Version = 90215

Sat.Asciify Method (Byte[])

Replace any non-ASCII characters in an XML document (as a byte array) with XML character references (where permitted).

Syntax

[C#]
public static string Asciify(
	byte[] xmlData
)
[VB.NET]
Public Shared Function Asciify ( _
	xmlData As Byte() _
) As String

Parameters

xmlData
Byte array containing XML data

Return Value

XML document as a string with non-ASCII characters replaced by XML character references.

Remarks

(bytes) --> (string)

Example

[C#]
byte[] b = File.ReadAllBytes("cfdv40-ejemplo.xml");
string s = Sat.Asciify(b);
Console.WriteLine(s);
// <?xml version="1.0"?>
// <cfdi:Comprobante ... >
//   <cfdi:Emisor Rfc=" AAA010101AAA" Nombre="Esta es una demostraci&#xF3;n" RegimenFiscal="622"></cfdi:Emisor>
// ... [etc]

Sat.Asciify Method (String)

Replace non-ASCII characters in an XML document with XML numeric character references (where permitted).

Syntax

[C#]
public static string Asciify(
	string xmlFile
)
[VB.NET]
Public Shared Function Asciify ( _
	xmlFile As String _
) As String

Parameters

xmlFile
Name of XML file (or a string containing XML data)

Return Value

XML document as a string with non-ASCII characters replaced by XML numeric character references.

Remarks

In almost all cases, the output contains only US-ASCII characters and can safely be used as input to other functions without concern for character encoding issues. For example, the character "ó" (U+00F3 LATIN SMALL LETTER O WITH ACUTE) is replaced by the XML character reference "&#xF3;".

In certain cases, some characters in an XML document cannot be replaced by a numeric character reference, for example where they are used in an element or attribute name, such as Año="2016". In these cases, they are left as UTF-8-encoded characters.

Example

[C#]
Console.WriteLine(Sat.Asciify("cfdv40-ejemplo.xml");
// <?xml version="1.0" ?>
// <cfdi:Comprobante ... >
//   <cfdi:Emisor Rfc=" AAA010101AAA" Nombre="Esta es una demostraci&#xF3;n" RegimenFiscal="622"></cfdi:Emisor>
// ... [etc]

Sat.CheckKeyAndCert Method

Verify that the public key in an X.509 certificate matches the private key.

Syntax

[C#]
public static int CheckKeyAndCert(
	string keyFile,
	string password,
	string certFile
)
[VB.NET]
Public Shared Function CheckKeyAndCert ( _
	keyFile As String, _
	password As String, _
	certFile As String _
) As Integer

Parameters

keyFile
Name of private key file
password
Password for encrypted private key
certFile
X.509 certificate file or XML document with embedded certificado node

Return Value

Zero (0) if keys match or a negative error code.

Example

[C#]
int n = Sat.CheckKeyAndCert("emisor.key", "12345678a", "emisor.cer");
Console.WriteLine("Sat.CheckKeyAndCert returns {0}", n);
// Sat.CheckKeyAndCert returns 0

// Cert and key do not match ...
n = Sat.CheckKeyAndCert("emisor.key", "12345678a", "pac.cer");
Console.WriteLine("Sat.CheckKeyAndCert returns {0}", n);
// Sat.CheckKeyAndCert returns -21
Console.WriteLine(General.ErrorLookup(n));
// Match not found/No se pudo encontrar datos coincidente (NO_MATCH_ERROR)
Console.WriteLine(General.LastError());
// Private key does not match key in certificate/La clave privada no coincide con la clave del certificado

Sat.DefaultDigestAlg Method

Return default digest (hash) algorithm for the XML document type.

Syntax

[C#]
public static string DefaultDigestAlg(
	string xmlFile
)
[VB.NET]
Public Shared Function DefaultDigestAlg ( _
	xmlFile As String _
) As String

Parameters

xmlFile
Name of XML file

Return Value

"SHA-1" or "SHA-256"; or "!ERROR!" if an error occurred.

Example

[C#]
Console.WriteLine(Sat.DefaultDigestAlg("cfdv40-ejemplo.xml"));  // SHA-256

Sat.ExtractDigestFromSignature Method

Extract message digest from the signature (sello) in an XML file.

Syntax

[C#]
public static string ExtractDigestFromSignature(
	string xmlFile,
	string certFile
)
[VB.NET]
Public Shared Function ExtractDigestFromSignature ( _
	xmlFile As String, _
	certFile As String _
) As String

Parameters

xmlFile
Name of input XML file to be processed (or a string containing XML data)
certFile
X.509 certificate file (optional) to override embedded Certificado node.

Return Value

Message digest in hex format or empty string on error

Remarks

This is the actual digest value computed over the original document and used to sign it. To re-compute the digest value over the current document, use MakeDigestFromXml(String).

Example

[C#]
Console.WriteLine(Sat.ExtractDigestFromSignature("cfdv40-ejemplo-signed-tfd.xml"));
// 0FF1274E51FBB090489588D832BB1B5B36543302DECBB0A5490839B8C99E8755

Sat.FixBom Method

Add UTF-8 byte order mark (BOM) to a file if not already present.

Syntax

[C#]
public static int FixBom(
	string outputFile,
	string inputFile
)
[VB.NET]
Public Shared Function FixBom ( _
	outputFile As String, _
	inputFile As String _
) As Integer

Parameters

outputFile
Name of output file to be created with BOM.
inputFile
Name of input file.

Return Value

Zero (0) on success or a negative error code.

Remarks

It is an error if the input file contains invalid UTF-8 characters.

Example

[C#]
int n = Sat.FixBom("cfdv40_new-signed-with-BOM.xml", "cfdv40-signed-nobom.xml");
Console.WriteLine("Sat.FixBom returns {0}", n);
// Read in new file as bytes, truncate, and display first 3 bytes: expecting EF-BB-BF
byte[] b = File.ReadAllBytes("cfdv40_new-signed-with-BOM.xml");
Array.Resize(ref b, 3);
Console.WriteLine(BitConverter.ToString(b));
// EF-BB-BF

Sat.GetCertAsString Method

Get certificate data as a base64 string.

Syntax

[C#]
public static string GetCertAsString(
	string fileName
)
[VB.NET]
Public Shared Function GetCertAsString ( _
	fileName As String _
) As String

Parameters

fileName
X.509 certificate file or XML file with Certificado node

Return Value

Certificate data as a string of base64 characters

Remarks

Use to obtain the value for the Certificado node from a .CER file. If input is an XML file, this is equivalent to Sat.GetXmlAttribute(fileName, "Certificado", "Comprobante")

Example

[C#]
Console.WriteLine(Sat.GetCertAsString("emisor.cer"));
// MIIF+TCCA+GgAwIBAgIUMzAwMDEwMDAwMDAzMDAw ...

Sat.GetCertExpiry Method

Get expiry date of the X.509 certificate in ISO time format.

Syntax

[C#]
public static string GetCertExpiry(
	string fileName
)
[VB.NET]
Public Shared Function GetCertExpiry ( _
	fileName As String _
) As String

Parameters

fileName
X.509 certificate file or XML file with certificado node

Return Value

Certificate expiry date

Example

[C#]
Console.WriteLine(Sat.GetCertExpiry("emisor.cer"));
// 2021-05-18T03:54:56Z

Sat.GetCertNumber Method

Get serial number of the X.509 certificate in "special" SAT format.

Syntax

[C#]
public static string GetCertNumber(
	string fileName
)
[VB.NET]
Public Shared Function GetCertNumber ( _
	fileName As String _
) As String

Parameters

fileName
X.509 certificate file or XML file with certificado node

Return Value

Certificate serial number

Remarks

Expected format is 20 decimal digits encoded in ASCII format

Example

[C#]
// From certificate file directly
Console.WriteLine(Sat.GetCertNumber("emisor.cer"));
// 30001000000300023708
// From embedded Certificado attribute
Console.WriteLine(Sat.GetCertNumber("cfdv40-ejemplo-signed-tfd.xml"));
// 30001000000300023708

Sat.GetCertStart Method

Get start date of the X.509 certificate in ISO time format.

Syntax

[C#]
public static string GetCertStart(
	string fileName
)
[VB.NET]
Public Shared Function GetCertStart ( _
	fileName As String _
) As String

Parameters

fileName
X.509 certificate file or XML file with certificado node

Return Value

Certificate start date

Example

[C#]
Console.WriteLine(Sat.GetCertStart("emisor.cer"));
// 2017-05-18T03:54:56Z

Sat.GetKeyAsString Method

Get private key data as a base64 string suitable for a llaveCertificado element in a Cancelacion XML document

Syntax

[C#]
public static string GetKeyAsString(
	string fileName,
	string password,
	KeyOption keyOpt
)
[VB.NET]
Public Shared Function GetKeyAsString ( _
	fileName As String, _
	password As String, _
	keyOpt As KeyOption _
) As String

Parameters

fileName
Encrypted private key file
password
Password for encrypted private key
keyOpt
Type: KeyOption
Output format (optional, default=UnencryptedBase64)

Return Value

Private key data as a string or empty string on error

Remarks

CAUTION: the unencrypted default option reveals your private key in unsecured form. Use with care!

Example

[C#]
Console.WriteLine(Sat.GetKeyAsString("emisor.key", "12345678a"));
// PFJTQUtleVZhbHVlPjxNb2R1bHVzP ... WYWx1ZT4=
Console.WriteLine(Sat.GetKeyAsString("emisor.key", "12345678a", KeyOption.EncryptedPEM));
// -----BEGIN ENCRYPTED PRIVATE KEY-----
// MIIFDjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQIAgEAAoIBAQACAggA
// ... rbw=
// -----END ENCRYPTED PRIVATE KEY-----

Sat.GetXmlAttribute Method

Extract attribute data from an XML file.

Syntax

[C#]
public static string GetXmlAttribute(
	string xmlFile,
	string attributeName,
	string elementName
)
[VB.NET]
Public Shared Function GetXmlAttribute ( _
	xmlFile As String, _
	attributeName As String, _
	elementName As String _
) As String

Parameters

xmlFile
Name of input XML file to be processed (or a string containing XML data)
attributeName
Name of attribute
elementName
Name of element or xpath expression (see remarks)

Return Value

Attribute value, if found; or "!NO MATCH!" if not found (see XmlNoMatch()()()); or empty string on error (the empty string may be the correct result if attr="", so check for an error using LastError()()()).

Remarks

For a simple element name, the default behaviour is to get the attribute from the first element found with the given name. Specify the element name in the form "element[N]" to extract the attribute for the N'th element found in the XML document, where N is a positive decimal integer (N=1,2,3,...). Setting elementName="" will output the value of the named attribute from the root element of the XML document. Setting both elementName="" and attributeName="" will output the name of the root element itself.

XPath expression: Alternatively, specify an path expression in elementName using the "/" and "//" operators and optional predicate [N] where N is a positive integer. For example "/Comprobante/Emisor" or "//Concepto[2]//Retencion[3]". This is a simplified form of XPath that selects the first occurrence of the element matching the path expression (whereas XPath would select all matching elements). Path expressions must start with a "/" or "//" and must not end with a "/". No other XPath function or operator is accepted. Do not use namespace prefixes (e.g. "cfdi:") in the path expression.

Simplified Xpath syntax:

To test for the existence of an element, set attributeName="". This will return the name of the element if it exists, or "!NO MATCH!" if not found. This message can be changed using SetXmlNoMatch(String).

Example

[C#]
Console.WriteLine(Sat.GetXmlAttribute("cfdv40-ejemplo.xml", "Nombre", "cfdi:Emisor"));
// Esta es una demostración

Sat.InsertCert Method

Insert certificate information into an XML document and output to a new file.

Syntax

[C#]
public static int InsertCert(
	string newFile,
	string baseFile,
	string certFile
)
[VB.NET]
Public Shared Function InsertCert ( _
	newFile As String, _
	baseFile As String, _
	certFile As String _
) As Integer

Parameters

newFile
Name of new file to be created.
baseFile
Name of input XML file to be processed (or a string containing XML data).
certFile
X.509 certificate file.

Return Value

0 if successful or non-zero error code if failed

Example

[C#]
// Take an XML file without a NoCertificado...
string fname = cfdv40-ejemplo-nocertnum.xml";
Console.WriteLine("Start file '{0}'.NoCertificado=[{1}]", fname, Sat.GetXmlAttribute(fname, "NoCertificado", "cfdi:Comprobante"));
Console.WriteLine("Start file '{0}'.Certificado={1} bytes", fname, Sat.GetXmlAttribute(fname, "Certificado", "cfdi:Comprobante").Length);
// Insert certificate details into intermediate file...
string interfile = "cfdv40_new-base-pluscert.xml";
int n = Sat.InsertCert(interfile, fname, "emisor.cer");
Console.WriteLine("Sat.InsertCert() returns {0} (expecting 0)", n);
Debug.Assert(0 == n, "Sat.InsertCert failed");
Console.WriteLine("Inter file '{0}'.NoCertificado=[{1}]", interfile, Sat.GetXmlAttribute(interfile, "NoCertificado", "cfdi:Comprobante"));
Console.WriteLine("Inter file '{0}'.Certificado={1} bytes", interfile, Sat.GetXmlAttribute(interfile, "Certificado", "cfdi:Comprobante").Length);
// Start file 'cfdv40-ejemplo-nocertnum.xml'.NoCertificado=[]
// Start file 'cfdv40-ejemplo-nocertnum.xml'.Certificado=0 bytes
// Sat.InsertCert() returns 0 (expecting 0)
// Inter file 'cfdv40_new-base-pluscert.xml'.NoCertificado=[30001000000300023708]
// Inter file 'cfdv40_new-base-pluscert.xml'.Certificado=1836 bytes

Sat.InsertCertToBytes Method (Byte[], String)

Insert certificate information into an XML document (as a byte array) and output to memory.

Syntax

[C#]
public static byte[] InsertCertToBytes(
	byte[] xmlData,
	string certFile
)
[VB.NET]
Public Shared Function InsertCertToBytes ( _
	xmlData As Byte(), _
	certFile As String _
) As Byte()

Parameters

xmlData
Byte array containing XML data
certFile
X.509 certificate file

Return Value

XML data as a byte array.

Remarks

(bytes) --> (bytes)

Example

[C#]
// Pass input XML data as a byte array
byte[] xmlArr = File.ReadAllBytes("cfdv40-ejemplo-nocertnum.xml");
string cerStr = Sat.GetCertAsString("emisor.cer");
byte[] b = Sat.InsertCertToBytes(xmlArr, cerStr);
Console.WriteLine(System.Text.Encoding.UTF8.GetString(b));
// <cfdi:Comprobante 
// ...
// NoCertificado="30001000000300023708" Sello="" Certificado="MIIF+TCCA+GgAwIBAgIU ...

Sat.InsertCertToBytes Method (String, String)

Insert certificate information into an XML document (as a file) and output to memory.

Syntax

[C#]
public static byte[] InsertCertToBytes(
	string xmlFile,
	string certFile
)
[VB.NET]
Public Shared Function InsertCertToBytes ( _
	xmlFile As String, _
	certFile As String _
) As Byte()

Parameters

xmlFile
Name of input XML file to be processed (or a string containing XML data)
certFile
X.509 certificate file

Return Value

XML data as a byte array.

Remarks

(file) --> (bytes)

Example

[C#]
// Pass input XML data as a string
string xmlStr = File.ReadAllText("cfdv40-ejemplo-nocertnum.xml");
string cerStr = Sat.GetCertAsString("emisor.cer");
byte[] b = Sat.InsertCertToBytes(xmlStr, cerStr);
Console.WriteLine(System.Text.Encoding.UTF8.GetString(b)); 
// <cfdi:Comprobante 
// ...
// NoCertificado="30001000000300023708" Sello="" Certificado="MIIF+TCCA+GgAwIBAgIU ...

Sat.LastError Method

Retrieve the last error message.

Syntax

[C#]
public static string LastError()
[VB.NET]
Public Shared Function LastError As String

Return Value

Error message from last call (may be empty)

Remarks

Call this immediately when an error is indicated. Calling another method will overwrite the message. This is the same as General.LastError().

Example

[C#]
// Attempt to sign but input file does not comply with CFDi specifications
int n = satSignXml("cfdv33a-out.xml", "cfdv33a-badspec.xml", "emisor.key", "12345678a", "emisor.cer");
Console.WriteLine("Error {0}: {1}", n, Sat.ErrorLookup(n));
// Error -10: Required data not found/Datos necesarios no encontrados (MISSING_ERROR)
Console.WriteLine(Sat.LastError());
// Attribute 'Importe' is mandatory/Atributo es obligatorio

Sat.MakeDigestFromXml Method

Form message digest of piped string (cadena) from an XML file.

Syntax

[C#]
public static string MakeDigestFromXml(
	string xmlFile
)
[VB.NET]
Public Shared Function MakeDigestFromXml ( _
	xmlFile As String _
) As String

Parameters

xmlFile
Name of input XML file to be processed (or a string containing XML data)

Return Value

Message digest in hex format or empty string on error

Example

[C#]
Console.WriteLine(Sat.MakeDigestFromXml("cfdv40-ejemplo-signed-tfd.xml"));
// 0ff1274e51fbb090489588d832bb1b5b36543302decbb0a5490839b8c99e8755

Sat.MakePipeStringFromXml Method

Create the piped string (cadena) from an XML file.

Syntax

[C#]
public static string MakePipeStringFromXml(
	string xmlFile
)
[VB.NET]
Public Shared Function MakePipeStringFromXml ( _
	xmlFile As String _
) As String

Parameters

xmlFile
Name of input XML file to be processed (or a string containing XML data)

Return Value

Piped string.

Example

[C#]
string s = Sat.MakePipeStringFromXml("cfdv40-ejemplo.xml");
Console.WriteLine(s);
// ||3.3|A|123ABC|2017-12-04T01:23:59|02|...[cut]...||

Sat.MakeSignatureFromXml Method

Create signature as a base64 string from data in an XML file ready to be inserted as a sello node.

Syntax

[C#]
public static string MakeSignatureFromXml(
	string xmlFile,
	string keyFile,
	string password
)
[VB.NET]
Public Shared Function MakeSignatureFromXml ( _
	xmlFile As String, _
	keyFile As String, _
	password As String _
) As String

Parameters

xmlFile
Name of input XML file to be processed (or a string containing XML data)
keyFile
Name of private key file
password
Password

Return Value

Signature in base64 format or empty string on error

Example

[C#]
string s = Sat.MakeSignatureFromXml("cfdv40-ejemplo.xml", "emisor.key", "12345678a");
Console.WriteLine(s);
// JQJd6rbiMZj1tZVb1Ta8l88bE7pTDm/aAl ...

Sat.NewKeyFile Method

Save keyfile with a new password.

Syntax

[C#]
public static int NewKeyFile(
	string newFile,
	string newPassword,
	string keyFile,
	string keyPassword,
	KeyFormat format
)
[VB.NET]
Public Shared Function NewKeyFile ( _
	newFile As String, _
	newPassword As String, _
	keyFile As String, _
	keyPassword As String, _
	format As KeyFormat _
) As Integer

Parameters

newFile
Name of new output file to be created.
newPassword
Password for new key file.
keyFile
Name of input key file (or a string containing the key in PEM form).
keyPassword
Password for existing key file.
format
Type: KeyFormat
Format to save file [default = DER binary].

Return Value

Zero (0) if output file is successfully created, or a negative error code.

Example

[C#]
string password = "12345678a";
string newpassword = "password123";
int n = Sat.NewKeyFile("emisor_new.pem", newpassword, "emisor.key", password, KeyFormat.PEM);
Debug.Assert(n == 0, "Sat.NewKeyFile failed");
Console.WriteLine(File.ReadAllText("emisor_new.pem"));
// -----BEGIN ENCRYPTED PRIVATE KEY-----
// MIIFDjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQIn2sl+Cj3VtgCAggA ...
// -----END ENCRYPTED PRIVATE KEY-----

Sat.QueryCert Method

Query an X.509 certificate.

Syntax

[C#]
public static string QueryCert(
	string fileName,
	Query query
)
[VB.NET]
Public Shared Function QueryCert ( _
	fileName As String, _
	query As Query _
) As String

Parameters

fileName
X.509 certificate file or XML file with certificado node
query
Type: Query
Query

Return Value

Result of query or an empty string on error

Sat.SetXmlNoMatch Method

Modify the string returned when GetXmlAttribute(String, String, String) fails to find a match.

Syntax

[C#]
public static void SetXmlNoMatch(
	string value
)
[VB.NET]
Public Shared Sub SetXmlNoMatch ( _
	value As String _
)

Parameters

value
New string value.

Example

[C#]
// Show default NoMatch string
Console.WriteLine(Sat.XmlNoMatch());
// !NO MATCH!
string fname = "cfdv40-ejemplo-signed-tfd.xml";
// Look for element that isn't there
Console.WriteLine(Sat.GetXmlAttribute(fname, "", "/Comprobante/notthere"));
// !NO MATCH!
// Set a new NoMatch string
Sat.SetXmlNoMatch("##No coinciden##");
Console.WriteLine(Sat.GetXmlAttribute(fname, "", "/Comprobante/notthere"));
// ##No coinciden##

Sat.SignXml Method

Sign an XML file

Syntax

[C#]
public static int SignXml(
	string newFile,
	string baseFile,
	string keyFile,
	string password,
	string certFile,
	SignOptions signOpts
)
[VB.NET]
Public Shared Function SignXml ( _
	newFile As String, _
	baseFile As String, _
	keyFile As String, _
	password As String, _
	certFile As String, _
	signOpts As SignOptions _
) As Integer

Parameters

newFile
Name of new file to be created
baseFile
Name of base XML file to be signed (or a string containing XML data)
keyFile
Name of private key file
password
Password
certFile
Name of X.509 certificate file to be included in output XML (optional)
signOpts
Type: SignOptions
Options for output format (optional)

Return Value

0 if successful or non-zero error code if failed

Remarks

This will create an output XML document copied from the input with the Sello node overwritten by a new signature value. Any existing file called newFile will be overwritten without warning; however, the input and output files can be the same.

If a certificate file szCertFile is specified then the Certificado and NoCertificado nodes will be overwritten in the output file with the values in the certificate file. If a certificate file is not specified then the Certificado value in the XML will be used.

A version 4 CFDi document to be signed must use the "cfdi:" namespace prefix. For CFD v4 the NoCertificado attribute in the input must be set to the correct certificate serial number before signing. In a Retenciones document you must set the CertNum attribute before signing. In a ControlesVolumetricos document you must set both the noCertificado and certificado attributes before signing.

Example

[C#]
int n = Sat.SignXml("cfdv40-signed_new.xml", "cfdv40-ejemplo.xml", "emisor.key", "12345678a", "emisor.cer");

Sat.SignXmlEx Method

Sign an XML file with extended options [deprecated].

Syntax

[C#]
[ObsoleteAttribute("Use Sat.SignXml with optional SignOptions parameter")]
public static int SignXmlEx(
	string newFile,
	string xmlFile,
	string keyFile,
	string password,
	string certFile,
	SignOptions signOpts
)
[VB.NET]
<ObsoleteAttribute("Use Sat.SignXml with optional SignOptions parameter")> _
Public Shared Function SignXmlEx ( _
	newFile As String, _
	xmlFile As String, _
	keyFile As String, _
	password As String, _
	certFile As String, _
	signOpts As SignOptions _
) As Integer

Parameters

newFile
Name of new file to be created
xmlFile
Name of base XML file to be signed
keyFile
Name of private key file
password
Password for private key file
certFile
(optional) name of X.509 certificate file to be included in output XML
signOpts
Type: SignOptions
Options for output format

Return Value

0 if successful or non-zero error code if failed

Remarks

See the remarks in SignXml(String, String, String, String, String, SignOptions)

Example

[C#]
int n = Sat.SignXmlEx(newname, fname, keyfile, password, certfile, SignOptions.BigFile);

Sat.SignXmlToBytes Method (Byte[], String, String, String, SignOptions)

Sign XML data writing output to a byte array.

Syntax

[C#]
public static byte[] SignXmlToBytes(
	byte[] xmlData,
	string keyFile,
	string password,
	string certFile,
	SignOptions signOpts
)
[VB.NET]
Public Shared Function SignXmlToBytes ( _
	xmlData As Byte(), _
	keyFile As String, _
	password As String, _
	certFile As String, _
	signOpts As SignOptions _
) As Byte()

Parameters

xmlData
Byte array containing XML data
keyFile
Name of private key file (or string containing key data in PEM format)
password
Password for key file
certFile
(optional) name of X.509 certificate file to be included in output XML (or string containing certificate data in base64 or PEM format)
signOpts
Type: SignOptions
Options for output format

Return Value

Signed XML data in a byte array

Remarks

Output XML is always UTF-8 encoded

Example

[C#]
string password = "12345678a";
string keyStr = Sat.GetKeyAsString("emisor.key", password, KeyOption.EncryptedPEM);
string cerStr = Sat.GetCertAsString("emisor.cer");
byte[] xmlArr = File.ReadAllBytes("cfdv40-ejemplo.xml");
byte[] xmlArrSigned = Sat.SignXmlToBytes(xmlArr, keyStr, password, cerStr, 0);
Console.WriteLine(System.Text.Encoding.UTF8.GetString(xmlArrSigned));
// <?xml version="1.0" encoding="UTF-8"?>
// <cfdi:Comprobante xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cfdi="http://www.sat.gob.mx/cfd/3" ...

Sat.SignXmlToBytes Method (String, String, String, String, SignOptions)

Sign XML file writing output to a byte array.

Syntax

[C#]
public static byte[] SignXmlToBytes(
	string xmlFile,
	string keyFile,
	string password,
	string certFile,
	SignOptions signOpts
)
[VB.NET]
Public Shared Function SignXmlToBytes ( _
	xmlFile As String, _
	keyFile As String, _
	password As String, _
	certFile As String, _
	signOpts As SignOptions _
) As Byte()

Parameters

xmlFile
Name of base XML file to be signed
keyFile
Name of private key file (or string containing key data in PEM format)
password
Password for key file
certFile
(optional) name of X.509 certificate file to be included in output XML (or string containing certificate data in base64 or PEM format)
signOpts
Type: SignOptions
Options for output format

Return Value

Signed XML data in a byte array

Remarks

Output XML is always UTF-8 encoded

Example

[C#]
byte[] b = Sat.SignXmlToBytes("cfdv40-ejemplo.xml", "emisor.key", "12345678a", "emisor.cer", SignOptions.Default);
Console.WriteLine(System.Text.Encoding.UTF8.GetString(b));
// <?xml version="1.0" encoding="UTF-8"?>
// <cfdi:Comprobante xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cfdi="http://www.sat.gob.mx/cfd/3" ...

Sat.Uuid Method

Generate a Universally Unique IDentifier (UUID) compliant with RFC 4122.

Syntax

[C#]
public static string Uuid()
[VB.NET]
Public Shared Function Uuid As String

Return Value

UUID string of exactly 36 characters

Remarks

The output value will be different each time.

Example

[C#]
Console.WriteLine(Sat.Uuid());
// 343c6b13-4f69-4d2a-97e6-64cb770c7677

Sat.ValidateXml Method

Validate an XML file against SAT specifications.

Syntax

[C#]
public static int ValidateXml(
	string xmlFile,
	XmlOption xmlOpt
)
[VB.NET]
Public Shared Function ValidateXml ( _
	xmlFile As String, _
	xmlOpt As XmlOption _
) As Integer

Parameters

xmlFile
Name of input XML file to be processed (or a string containing XML data)
xmlOpt
Type: XmlOption
Option for strict or loose XML restrictions (optional, default=Strict)

Return Value

0 if successful or non-zero error code

Remarks

This just validates the XML structure, not the signature.

Example

[C#]
int n = Sat.ValidateXml("cfdv40-ejemplo.xml");
Console.WriteLine("Sat.ValidateXml returns {0}", n);
// Sat.ValidateXml returns 0

int n = Sat.ValidateXml("cfdv40-iedu-badcurp.xml");
Console.WriteLine("Sat.ValidateXml returns {0}", n);
// Sat.ValidateXml returns -28
Console.WriteLine(General.ErrorLookup(n));
// XML restriction is violated/XML restriccion es violada (XML_FACET_ERROR)
Console.WriteLine(General.LastError());
// Bad attribute/atributo mal [iedu:instEducativas/@CURP] (line 30): 
// 'JUAN01010101GTOHMD0' is too long/es demasiado largo, maximum length/longitud maxima=18
// Input has valid XML form but an invalid facet error against SAT specifications
// Using the "Loose" option validates that the XML form is still correct.
int n = Sat.ValidateXml("cfdv40-iedu-badcurp.xml", XmlOption.Loose);
Console.WriteLine("Sat.ValidateXml(Loose) returns {0}", n);
// Sat.ValidateXml(Loose) returns 0

Sat.VerifySignature Method

Verify the signature (sello) in an XML file.

Syntax

[C#]
public static int VerifySignature(
	string xmlFile,
	string certFile
)
[VB.NET]
Public Shared Function VerifySignature ( _
	xmlFile As String, _
	certFile As String _
) As Integer

Parameters

xmlFile
Name of input XML file to be processed (or a string containing XML data)
certFile
X.509 certificate file (optional)

Return Value

Zero if signature is verified or nonzero error code if failed

Remarks

If no certFile is specified, the public key is obtained from the certificado node in the XML file.

Example

[C#]
Console.WriteLine(Sat.VerifySignature("cfdv40-ejemplo-signed.xml"));
// 0
Console.WriteLine(Sat.VerifySignature("cfdv40-badsig.xml"));
// -15
Console.WriteLine(General.ErrorLookup(-15));
// Decryption error/De error de descifrado (DECRYPT_ERROR)

Sat.WritePfxFile Method

Create PFX (PKCS-12) file in PEM format suitable for a Cancelacin.

Syntax

[C#]
public static int WritePfxFile(
	string pfxFile,
	string pfxPassword,
	string keyFile,
	string keyPassword,
	string certFile,
	PfxFormat pfxFormat
)
[VB.NET]
Public Shared Function WritePfxFile ( _
	pfxFile As String, _
	pfxPassword As String, _
	keyFile As String, _
	keyPassword As String, _
	certFile As String, _
	pfxFormat As PfxFormat _
) As Integer

Parameters

pfxFile
Name of output PFX file to be created
pfxPassword
Password to open new PFX file
keyFile
Name of encrypted key file
keyPassword
Password for encrypted key file
certFile
Name of X.509 certificate file
pfxFormat
Type: PfxFormat
Output format for PFX file (optional, default=plain base64)

Return Value

Zero (0) if output file is successfully created, or a negative error code.

Example

[C#]
string password = "12345678a";
string newpassword = "clavedesalida";
int n = Sat.WritePfxFile("archivo_new-pfx.txt", newpassword, "emisor.key", password, "emisor.cer");
Debug.Assert(n == 0, "Sat.WritePfxFile failed");
Console.WriteLine(File.ReadAllText("archivo_new-pfx.txt"));
// MIIMOQIBAzCCC/8GCSqGSIb3DQEHAaCCC/AEggvsMIIL6DCCBp8GCSqGSIb3DQEH ...

Sat.XmlNoMatch Method

Error message returned when GetXmlAttribute(String, String, String) fails to find a match

Syntax

[C#]
public static string XmlNoMatch()
[VB.NET]
Public Shared Function XmlNoMatch As String

Return Value

Error message (default = "!NO MATCH!")

Remarks

Use to test for existence of an element. The message can be changed using SetXmlNoMatch(String).

Example

[C#]
Console.WriteLine(Sat.XmlNoMatch());
// !NO MATCH!

Sat.XmlReceiptVersion Method

Find version number of Comprobante element or ID number for other document types.

Syntax

[C#]
public static int XmlReceiptVersion(
	string xmlFile
)
[VB.NET]
Public Shared Function XmlReceiptVersion ( _
	xmlFile As String _
) As Integer

Parameters

xmlFile
Name of XML file

Return Value

Version number or ID number, or a negative error code.

Example

[C#]
Console.WriteLine(Sat.XmlReceiptVersion("cfdv40-ejemplo.xml"));  // 40

Tfd.AddSignedTfd Method

Add a signed Timbre Fiscal Digital (TFD) element to a CFDI document.

Syntax

[C#]
public static int AddSignedTfd(
	string newFile,
	string inputFile,
	string keyFile,
	string password,
	string certFile
)
[VB.NET]
Public Shared Function AddSignedTfd ( _
	newFile As String, _
	inputFile As String, _
	keyFile As String, _
	password As String, _
	certFile As String _
) As Integer

Parameters

newFile
Name of new file to be created
inputFile
Name of existing CFDI file
keyFile
Name of PAC's private key file
password
Password for private key
certFile
Name of PAC's X.509 certificate that matches the keyFile

Return Value

Zero (0) if successful or non-zero error code if failed

Remarks

The inputFile must be a version 4.0/3.3 CFDi document already signed with a sello field and no existing TFD element. The TFD will be timestamped using the system clock and a fresh UUID will be generated. No other XML processing is carried out except inserting the TFD element.

Example

[C#]
int n = Tfd.AddSignedTfd(newname, fname, keyfile, password, certfile);
Console.WriteLine("Tfd.AddSignedTfd returns {0}", n);  // 0
string s = Sat.GetXmlAttribute("cfdv40-ejemplo_signed.xml", "SelloSAT", "TimbreFiscalDigital");
// SelloSat=Qncw19SZ0w/uxkwCYkf/7V3DF3j28Jp1XyNVyqiyOreq0S ...

Tfd.ExtractDigestFromSignature Method

Extract message digest from the selloSAT node in Timbre Fiscal Digital of CFDI document.

Syntax

[C#]
public static string ExtractDigestFromSignature(
	string xmlFile,
	string certFile
)
[VB.NET]
Public Shared Function ExtractDigestFromSignature ( _
	xmlFile As String, _
	certFile As String _
) As String

Parameters

xmlFile
Name of input XML file to be processed (or a string containing XML data)
certFile
X.509 certificate file of PAC who signed the TFD (required)

Return Value

Message digest in hex format or empty string on error

Tfd.MakeDigestFromXml Method

Form message digest of cadena original del Timbre Fiscal Digital del SAT (TFD piped string) from CFDI XML file.

Syntax

[C#]
public static string MakeDigestFromXml(
	string xmlFile
)
[VB.NET]
Public Shared Function MakeDigestFromXml ( _
	xmlFile As String _
) As String

Parameters

xmlFile
Name of input XML file to be processed (or a string containing XML data)

Return Value

Message digest in hex format or empty string on error

Tfd.MakePipeStringFromXml Method

Create the cadena original del Timbre Fiscal Digital del SAT (TFD piped string) from CFDI XML file.

Syntax

[C#]
public static string MakePipeStringFromXml(
	string xmlFile
)
[VB.NET]
Public Shared Function MakePipeStringFromXml ( _
	xmlFile As String _
) As String

Parameters

xmlFile
Name of input XML file to be processed (or a string containing XML data)

Return Value

Piped string in UTF-8 encoding

Tfd.MakeSignatureFromXml Method

Create the selloSAT signature as a base64 string from TFD data in CFDI XML document.

Syntax

[C#]
public static string MakeSignatureFromXml(
	string xmlFile,
	string keyFile,
	string password
)
[VB.NET]
Public Shared Function MakeSignatureFromXml ( _
	xmlFile As String, _
	keyFile As String, _
	password As String _
) As String

Parameters

xmlFile
Name of input XML file to be processed (or a string containing XML data)
keyFile
Name of private key file
password
Password

Return Value

Signature in base64 format or empty string on error

Remarks

Assumes you are a PAC with a valid SAT signing key.

Tfd.VerifySignature Method

Verify the selloSAT signature in CFDI XML document.

Syntax

[C#]
public static int VerifySignature(
	string xmlFile,
	string certFile
)
[VB.NET]
Public Shared Function VerifySignature ( _
	xmlFile As String, _
	certFile As String _
) As Integer

Parameters

xmlFile
Name of input XML file to be processed (or a string containing XML data)
certFile
X.509 certificate file of PAC who signed the TFD (required)

Return Value

0 if signature is verified or non-zero error code if failed

Enumerations

KeyFormat Enumeration

Format for saved key files.

Syntax

[C#]
public enum KeyFormat
[VB.NET]
Public Enumeration KeyFormat

Members

Member nameDescription
Default
Default = Binary
Binary
Binary DER-encoded
PEM
PEM Format

KeyOption Enumeration

Options for key output in Sat.GetKeyAsString().

Syntax

[C#]
public enum KeyOption
[VB.NET]
Public Enumeration KeyOption

Members

Member nameDescription
Default
Default (unencrypted base64 string).
UnencryptedBase64
Key as unencrypted base64 string suitable for Cancelacion element.
EncryptedPEM
Key as encrypted private key in PEM format suitable for input as a keyFile parameter.

PfxFormat Enumeration

Options for PKCS12 (PFX) output in Sat.WritePfxFile().

Syntax

[C#]
public enum PfxFormat
[VB.NET]
Public Enumeration PfxFormat

Members

Member nameDescription
Default
Default (plain base64 suitable for Cancelacion element).
Base64
PFX data as plain base64.
PEM
PKCS12 PEM textual form = same as Base64 but with PEM encapsulation
-----BEGIN PKCS12-----
...
-----END PKCS12-----
Binary
Binary DER form.

Query Enumeration

Options for certificate query.

Syntax

[C#]
public enum Query
[VB.NET]
Public Enumeration Query

Members

Member nameDescription
notAfter
Get certificate expiry date.
notBefore
Get certificate start date.
organizationName
Get organization name of issuer. Expecting "Servicio de Administración Tributaria" if issued by SAT
companyName
Get organization name of subject. This should be your company name.
rfc
Get RFC of subject. Expecting 12 or 13 characters if issued by SAT.
serialNumber
Get decoded serial number. Expecting 20 decimal digits.
sigAlg
Get algorithm used to sign certificate (e.g. "sha256WithRSAEncryption").
keySize
Get size in bits of certificate's public key (e.g. "2048").

SignOptions Enumeration

Options for signing XML.

Syntax

[C#]
[FlagsAttribute]
public enum SignOptions
[VB.NET]
<FlagsAttribute> _
Public Enumeration SignOptions

Members

Member nameDescription
Default
Default (add BOM, empty elements in form <foo></foo>).
NoBOM
Do not add byte-order mark (BOM) to file.
UseEmptyElements
Output empty elements in empty-element tag form <foo /> (default is start-end tag pair form <foo></foo>).
BigFile
Speed up the processing of large files.
OverrideReqd
Override strict checks for required nodes (advanced users).

XmlOption Enumeration

Options for XML validation.

Syntax

[C#]
public enum XmlOption
[VB.NET]
Public Enumeration XmlOption

Members

Member nameDescription
Default
Default value (strict)
Strict
Enforce stricter XML restrictions (default in v5.0 and above).
Loose
Use looser restrictions on data types (default before v5.0).

Index

Classes
Enumerations
FirmaSAT Namespace
General Class
Methods
Sat Class
Tfd Class