Xmldsig cryptopro

Xmldsig cryptopro ГИС ЖКХ

Table of contents

Cryptography tasks are not the most common in 1C. Nevertheless, such things as an electronic signature are becoming more and more dense in our lives and periodically 1C developers have to deal with some issues from this area.

We hope that this material will give an overview of what a 1C specialist in the field of cryptography may encounter, what concepts it contains, what tools we have for work.

Cryptography around us

The applications of cryptography are varied.
This is a clear application of it «as intended»:

Application as one of the auxiliary elements and components of more complex systems, protocols, processes:

A lot of things around us also contain cryptography:

Many mechanisms and technologies use cryptography implicitly, deep in libraries, and we do not think that this is the case, even using these technologies.

For example, an HTTPS connection and the corresponding 1C HTTPConnection object. This object uses encryption, but it happens by itself, without our participation. And it does not require intervention and even understanding how it works.

Sometimes there are tasks that require a deeper immersion in the topic.

Cryptography itself (as the name implies) is the science of encryption. Simply put, encryption is about turning understandable data into incomprehensible, sometimes reversible and sometimes not.

A bit of history

The first encryption methods were based on purely physical objects.

It is a rod on which a long, narrow (letter-wide) parchment is wound. Text is written along the rod axis (in several rows). After unwinding, the message turns into a set of letters. For decoding, a rod of the same diameter is required.

Letters are marked on the ruler near the serifs and there is a “zero” hole. The letter is encoded by the distance between the «zero» hole and the corresponding slot. That is, the thread is pulled between these holes and a knot is tied, then it is threaded back into the «zero» hole and into the slot of the next letter. Sequentially, knots are tied on the thread for the entire text. The distances between the knots are the codes of the letters. Reverse decoding requires the same ruler, with the same letters.

The disc has holes, each coded with a letter. The thread is simply threaded sequentially through the letters-holes corresponding to the text of the message. Pulling the thread back, we restore the text. Secrecy consists in the fact that the disk can be broken or the thread can be quickly pulled out and that’s it — the message cannot be read.

Xmldsig cryptopro

The message is hidden inside an outwardly harmless text, for decoding it is required to impose a template (grid) with holes on the text and read the received.

In such encryption methods, it is assumed that both the sender and the recipient of messages have the same type of devices, in fact, this is an ancient example of symmetric encryption. Well, in this case, the key of a symmetric cipher is, in fact, a set of physical characteristics of an object, that is, geometric dimensions, the location of holes, serifs, etc. And in order to maintain secrecy, the object itself must be kept secret — the encryption tool.

Everyone knows Enigma

Xmldsig cryptopro

The basis of this machine is substitution ciphers, when another set of characters is compared to the alphabet of the source text and a replacement is made (like, for example, the Caesar Cipher).

For each letter of the message, Enigma performed several such substitutions in succession, while on each letter the substitution cipher itself, that is, the correspondence of characters, changed.

Encryption methods without devices

Other encryption methods already consisted of some algorithm for rearranging or replacing letters, and there was no device here, but it was necessary to know the key. For example, the Caesar Cipher — it needs to know how many characters we have shifted the alphabet to the right or left.

Alphabet characters with number N are replaced by characters with number N + k.

Letters are replaced by letters that are symmetrical to them from the end of the alphabet.

Xmldsig cryptopro

It is impossible not to remember the cipher from Conan Doyle’s The Dancing Men. This is the simplest substitution cipher (letters for pictograms)

Xmldsig cryptopro

Modern methods of encryption

Modern cryptography does not rely on any mechanical and physical devices, but uses exclusively mathematical apparatus to transform data.

Physical devices are used only as computers or secure storage for secret keys.

At the same time, the encryption methods themselves are not kept secret, such as, for example, the physical mechanisms that were once used. The algorithms are freely distributed and quite reproducible.

But algorithms require input parameters called keys, and all the secrecy is precisely contained in the keys, since the output result of this or that calculation depends on the use of the correct key.

Symmetric and asymmetric encryption

Encryption algorithms are divided into two classes: with a private key (symmetric encryption) and with a public key (asymmetric).

With symmetric encryption, there is only one key, it is used both for the encryption operation and for decryption.

Asymmetric encryption uses different keys for these two operations. Such systems are considered more reliable, since there is no need to transfer the secret key to the interlocutor and thereby expose the key to the danger of disclosure. In addition, the public key system, in fact, gives us another opportunity — to create an electronic signature. On the other hand, asymmetric encryption requires much more computing resources.

Several known encryption algorithms

The reliability of asymmetric ciphers is based on the complexity of some mathematical problems.

In the RSA algorithm, and similar ones, these are factorization problems, that is, factoring large numbers into prime factors.

Multiplying two numbers is quite easy, while the inverse problem is computationally difficult. With the increase in the numbers themselves, it becomes almost impossible to complete it in a reasonable time.

One of the most famous applications of RSA is in the cryptographic protocols used on the Internet — SSL and TLS.

SSL (Secure Sockets Layer) is a cryptographic protocol that implies a more secure connection. It uses asymmetric cryptography to authenticate exchange keys, symmetric encryption to preserve confidentiality, message authentication codes for message integrity.

The protocol was widely used for instant messaging and voice over IP (Voice over IP — VoIP) in applications such as email, Internet fax, etc. In 2014, the US government reported a vulnerability in the current version protocol. S SL should be deprecated in favor of TLS (see C VE-2014-3566).

SSL was originally developed by Netscape Communications to add HTTPS to its Netscape Navigator web browser. Subsequently, based on the SSL 3.0 protocol, the RFC standard was developed and adopted, which received the name TLS.

In the ElGamal scheme, the difficulty lies in obtaining the value of the discrete logarithm in a finite field. According to this scheme, DSA algorithms are built, encryption according to the GOST R 34.10-94 standard.

Algorithms based on the complexity of calculating the discrete logarithm in a group of points of an elliptic curve are considered even more resistant to hacking (mathematical operations are performed not on integers, but on points on the curve). Such a scheme is used in the ECDSA algorithm (in fact, it is a modification of DSA for elliptic curves). In addition, algorithms from the latest GOST standards are built on this scheme (GOST 2001, 2012, 2018).

An example of the RSA cipher algorithm

Keys are calculated (created) first:

Suppose we need to encrypt the number M (M must be less than n).

For this, the value C = Me mod n is calculated. The value c is the ciphertext, the encrypted message.

For decryption, you need to calculate the value M’ = Cd mod n . The resulting value M’ will be equal to the original number M. Why this happens is a complex question and requires a deeper immersion in mathematical theory, which is beyond the scope of this article.

M = 26³ mod 33 = 20

In reality, of course, the work is with large numbers, 1024 bits and higher. And the calculations are more complicated, and it is almost impossible to pick up the key.

It should be noted that asymmetric algorithms are slower than symmetric encryption algorithms, since they require much more (and more complex) calculations.

Cryptanalysis

Simultaneously with cryptography, cryptanalysis appeared — the science of how to decrypt encrypted information, and in general, about finding vulnerabilities in cryptographic protection.

For example, the simplest attacks and ways to break substitution ciphers are to statistically analyze the ciphertext and compare the results with patterns in the language in which the original text is written. You can read about this popularly in the already mentioned «Dancing Men» (Arthur Conan Doyle).

Complex ciphers currently in use are not so easily broken, cryptographic tools have become much less vulnerable to attacks of various kinds. However, there are various methods of cryptanalysis, and sometimes vulnerabilities are found in certain ciphers.

Also, with the development of computer technology and the advent of distributed computing, the protection of encryption methods from attacks such as Brute Force, by simple enumeration of values, periodically becomes relevant. That is why the length of the encryption key plays an important role — the longer the key, the more options you need to sort through.

Про ГИС ЖКХ:  Раскрываем секреты проведения успешных мероприятий: определены ключевые инициаторы

In addition, there are also social engineering attacks. The weakest link in defense is often a person. This also has to be taken into account when developing cryptographic methods.

Thus, each algorithm has its own level of resistance to hacking, reliability, and security.

Cryptographic primitives

Everything we talked about above concerns, basically, encryption.

In modern cryptography, encryption is not only the end in itself of the whole process, but also a tool that is also used to perform other operations (primitives).

Each of these primitives also deals with the transformation of understandable data into incomprehensible, but with different goals and different results. There are usually three such primitive operations.

Hashing

A hash function is a function that allows you to get a pseudo-unique value of a certain fixed length from data of arbitrary size. This, one might say, is also a kind of encryption procedure (we get incomprehensible data from understandable data), but it is irreversible, that is, data cannot be returned from the hash sum.

Xmldsig cryptopro

There are hashing algorithms, so to speak, everyday, familiar to everyone:

More exotic hashing algorithms are also used, for example, in Russian standards:

The second cryptographic function is encryption itself. The reverse to it is data decryption.

This operation already involves such a concept as a key — public and private. A public key is a value that is freely distributed and open to everyone.

A private key is a secret value that the owner keeps secret.

Encryption occurs using the public key. At the output, we get a ciphertext.

Xmldsig cryptopro

Decryption is performed using the private key.

There is a common misconception that it is just the opposite, and a private secret key is used for encryption. This is true for symmetric ciphers. In them, the public and private keys are the same, only one key is used, which is known to both the recipient and the sender, and they, of course, keep it secret.

With asymmetric encryption, the scheme works like this:

We have said before that asymmetric encryption is a slow operation. Therefore, in practice, encryption, especially large or streaming data, often happens like this:

Alternatively, when transmitting a data packet, it is immediately placed in it:

Xmldsig cryptopro

The encryption result obtained using the 1C platform is arranged in this way.

This scheme allows «expensive» asymmetric encryption to be performed on a small value of the session key. And a large amount of transmitted data should be encrypted with a fast symmetric cipher.

Electronic signature

An electronic signature is created using a private key. The private key is known only to the owner of the signature, respectively, only he can create this signature. To do this, the initial data and the private key are passed to the signature calculation function, at the output we get some new value, which is called the «signature» or «signature value».

This is a small value, such as 512 bits. Sometimes it is called the «raw» value of an electronic signature — that is, not wrapped in any wrappers or formats, just the result of calculating a mathematical cryptographic function.

An electronic signature is also a kind of encryption. From understandable input data, we get an incomprehensible signature value.

Xmldsig cryptopro

The inverse task is to make sure that the input data matches the value of the signature. These two values ​​are passed to a cryptographic function, and using the public key, it is checked whether these data correspond to this signature.

The public key must be obtained somewhere in advance, often it is included in the same package as the rest of the values.

Let us note such a point that the electronic signature in no way encrypts information. And it is not intended to hide or encrypt information. The signature value does not contain the original data at all — it is some kind of additional value.

In order to transfer the signed data to the recipient, we put the original data itself and the signature value in one package. The source data is not encrypted.

If you want to classify information, you must additionally use encryption, and this will be a more complicated operation.

Often, when installing an electronic signature for data, additional information is also added to one package for greater security. For example, the date of signing, the name of the subject who signed, and other information.

All this is combined into one common information structure, and then a signature is already established for the full amount of data. Thus, for example, if someone inserts the original true data, but changes the signature date, this can be established.

As with encryption, in the case of a large amount of data, setting a signature is a rather expensive computational operation. Therefore, a technique is often also applied to reduce these computational costs.

A hash is calculated (relatively) quickly, and it is much less expensive to calculate a signature from a few bytes of a hash value than from a large block of source data, theoretically unlimited.

Xmldsig cryptopro

An electronic signature gives us several useful features:

Types of electronic signature in Russia

There are, in accordance with Russian law, three types of electronic signature:

A simple signature is, for example, an SMS code. Cryptography is not used.

Enhanced Unqualified (UNEP) — created using cryptographic means. Such a signature is generated and acts within some system. For example, it can be an internal document flow of a company. Also, this type of signature is issued for interested individuals in the personal account of the taxpayer. Theoretically, any software can be used.

Enhanced qualified (UKEP) — also created using cryptographic tools, but the tools and algorithms used must be certified by the FSB.

Thus, in theory, in some cases, UNEP can be used. In practice, almost all systems of interaction and integration, especially state ones, require the use of ECES. In fact, this narrows the choice from the whole variety of algorithms to algorithms defined by GOST standards (now GOST 2012), and software to those that have the appropriate registration and certification.

Crypto providers

As we found out, to work with cryptographic tools, you need to have a mathematical apparatus (algorithms), a set of cryptographic functions for data transformation. We have already listed some of them above. There are many algorithms, they differ in purpose, complexity, resistance to various attacks.

Cryptography does not stand still. Some algorithms are considered obsolete or unsafe and are no longer used.

Sometimes there are new modifications of algorithms. For example, the algorithms enshrined in GOST changed several times: GOST R34.10-94 was replaced by the GOST 2001 version, and several years ago there was a massive transition of systems to GOST 2012. At the same time, not just the names, but the essential characteristics of the algorithms changed.

In order to practically perform some kind of encryption, it is not required to re-implement the algorithm in any programming language. For this, ready-made software products are intended — CIPF (means of cryptographic information protection), or cryptographic providers.

There are many cryptographic providers, here are a few of them:

Different crypto providers can execute different sets of cryptography algorithms. Some simple algorithms are built into the operating system, for example, Windows has the Microsoft Base Cryptographic Provider. It is used for various internal cryptographic needs of the system, such as encryption and hashing of passwords, support for SSL and TLS protocols.

But those algorithms that we are usually interested in, for example, the same GOST, are not in the operating system and additional programs need to be used for them.

In our practice, the two most common crypto providers are CryptoPro and VipNet.

Crypto providers are capricious programs, sometimes there are difficulties with them. Crypto providers installed on the same operating system often conflict with each other. There are also cases of conflicts with antiviruses. There were cases when there were problems connecting to the network on the computer.

Also, in the 1C documentation (its.1c.ru/db/v83doc#bookmark:dev:TI000000835) it is directly written that CryptoPro cryptographic information protection system works in Linux with 1C. In fact, we are limited to one software product. Other programs are not mentioned and, therefore, are not supported.

Initialization of cryptography in 1C

Before citing various code fragments, let’s make a reservation.

First of all, they are, of course, simple enough for real use and are educational.

Secondly, many operations are well automated in the Library of Standard Subsystems, and, accordingly, in many typical configurations. Moreover, the Library also has ready-made blocks of data structure and interfaces for interacting with the user. All of these elements can be used in your solution, and the functions are easy to call in your code.

But in order to understand how the ready-made functional blocks presented in the BSP library work, to embed them correctly, to be able to debug and refine them, you need to understand what elementary operations and objects are for interacting with cryptography in the 1C platform. If you want to develop something of your own, all the more you need to have an idea about it.

To use cryptography in 1C, we do not have many tools — there are only two of them. It is a cryptography manager and an external XMLDSig component.

The cryptography manager is an object of the built-in 1C language.

It does not perform cryptographic operations itself, but calls the functions of the cryptoprovider libraries installed in the system through the CryptoAPI interface.

The XMLDSig external component is the second tool, it is an external component for the 1C platform, it is included in the BSP delivery. The new version of the BSP has a new version of this component with several additional features, it is called ExtraCryptoAPI.

Про ГИС ЖКХ:  Получите образец сертификата оказанных услуг: загрузка Word

Xmldsig cryptopro

This library slightly extends the capabilities of the cryptography manager.

In the BSP, in the modules of the digital signature subsystem, the main necessary wrapper functions for working with this component are implemented.

In order to start working with the Cryptography Manager object, it must be initialized. Here is a sample code.

Xmldsig cryptopro

In this fragment, you can notice some constants, which are denoted here as ModuleName, ModuleType, Signature Algorithm, etc.

These are quite important values. ModuleName + ModuleType give us a cryptographic provider that we want to call through the API of the Windows operating system.

But the Module Path is designed to initialize cryptography in the Linux system, where access to the crypto provider occurs not through a system call of a special API, but through loading libraries, the paths to which must be specified in this variable.

Hash Algorithm and Signature Algorithm — set the selected algorithms for subsequent execution.

The values ​​of all these constants are not just arbitrary, but fixed for each crypto provider. Note also that the same algorithm may have different names in different CIPFs.

Possible values ​​can be viewed:

Xmldsig cryptopro

Xmldsig cryptopro

After initialization, we have the Cryptography Manager — this is the object through which we will interact with the crypto provider and perform functions such as:

Also, for signing and encrypting / decrypting, we need to use keys — public and private.

Installation, storage and communication of keys, certificates, containers

As mentioned earlier, the public key is distributed among those with whom we want to interact. The public key itself is a large number, most often represented as a HEX string. But keys are distributed not as a string, but as certificates.

A certificate is a file that contains, in addition to the public key itself, various information about the electronic signature. A certificate is essentially a kind of electronic signature passport. It, in turn, is also signed with an electronic signature — of the issuing certification center. The certificate also confirms that this public key belongs to us, that is, to a specific organization or individual.

Files containing certificates often have a .cer or .pfx extension. If you click on such a file in Windows Explorer, it will open and look like in the picture.

Xmldsig cryptopro

In this window, you can view various properties of the electronic signature. Here you can also see the «Install Certificate» button. It allows you to place a certificate in a special certificate store and it will be «known» to the system.

Of course, the certificate can simply be located in a file, and with various interactive and programmatic manipulations, we can select it or specify the path to it, as to a physical file.

But the operating system provides a centralized store of certificates. Interactively, using console utilities or programmatically, we can install the certificate in the store.

Xmldsig cryptopro

For Windows, we choose where to place the certificate: in the computer’s storage, that is, available to many users, or in the storage of a specific current user.

Certificates are divided into categories: Personal, CA Root Certificates and several other categories.

The system and the crypto provider build chains from these certificates (when the user’s certificate, for example, is confirmed by a certification authority certificate), checks their integrity, validity period, etc.

Private key

Xmldsig cryptopro

Private keys are stored in «containers». The container can be located: in the file system (on a flash drive, on a floppy disk), on a smart card, on a hardware token carrier, in the Windows registry, and even in the cloud.

Some hardware media do not just store private keys, but are more complex devices and can perform some cryptographic operations themselves.

The private key container can sometimes be moved between different repositories. For example, a key from a hardware media can be copied to the Windows registry so that you do not need to insert the media into a USB port each time. This, of course, is convenient, but there is a separate question regarding the security of such a solution.

Variants of containers, their location, the ability to move, export, import private keys is already determined by a specific crypto provider. Additionally, the private key container is usually protected by a password.

Connection of keys and crypto provider

If we want to use an electronic signature and sign documents, we need to have three elements in the system: two keys and a crypto provider, and establish a connection between them.

The system needs to know that a given public key is associated with a given private key container and with a given cryptographic provider.

Xmldsig cryptopro

At the same time, if you use the «Install certificate» button to install the certificate, then such a connection is not established and the electronic signature will not work. To correctly install the certificate and establish a connection between the public key certificate and the private key container, they are usually installed simultaneously into the system using the cryptographic provider function.

Also, the crypto provider can have the function of adding a link for already installed keys.

Xmldsig cryptopro

Xmldsig cryptopro

Incorrect installation of the signature (keys) in the system is one of the common mistakes when setting up cryptography, and a wide variety of errors can occur, here are just a few of them:

Xmldsig cryptopro

Certificates in 1С code

In order to use the private key and sign or decrypt the data, the private key container is not directly specified. The public key certificate associated with the container is used.

In order to somehow interact with the public key, a public key certificate is also used.

Thus, in order to perform some kind of cryptographic operation related to keys, we need to specify a certificate.

There can be several certificates in the system, so to select a specific certificate, you need to somehow identify it. A certificate has many parameters, for example: issuer, subject (that is, owner), expiration date. But all these parameters are not suitable as an identifier. Typically, the Thumbprint field is used to identify a certificate. In general, a thumbprint is just a hash sum of a certificate file, but it is often used as its identifier.

In the 1C code, you can most often see just such an option.

Xmldsig cryptopro

To obtain a certificate, you need to use the cryptography manager, indicating from which storage (common for a computer or personal) we want to receive it.

Xmldsig cryptopro

Since the private key is protected by a password, it must also be specified in order to perform cryptographic operations.

In the above example, the password is explicitly specified for demonstration purposes only.

Also, with the help of the cryptography manager, you can perform other operations with certificates — sort, save to a file, delete from storage, etc.

Xmldsig cryptopro

Standards, formats

When a specialist plunges into the world of cryptography, he immediately encounters a huge number of different abbreviations and designations, in addition to the names of encryption algorithms:

  • ASN.1,
  • X.509.

It’s easy to get lost here at first. Let’s try, just for clarity, to make out what relates to what.

PKCS#NN are Public Key Cryptography Standards developed by RSA Security. Standards describe a wide variety of things, from encryption algorithms to secure exchange protocols and mechanisms for storing and transmitting cryptographic information. In particular, PKCS#7 (Cryptographic Message Syntax Standard) is a standard for storing cryptographic data (certificates, signatures, encrypted data).

CMS, XMLDsig, CAdES, JAdES, PAdES, XAdES are various storage formats for signatures and other cryptographic information such as certificates. They describe a fairly high-level structure of how and what data should be represented inside a file or stream data with a signature or other information.

ASN.1 is a binary, low-level format for storing cryptographic data. Describes the byte structure of the file.

CER/DER/BER are formats for storing certificates of electronic signature and encryption keys. They are approximately the same, differing in minor features, such as the way internal values ​​are encoded, and content restrictions.

X.509 is commonly understood as a certificate structure standard.

Some signature formats can be created from the built-in 1C language.

CMS/CAdES format

One of the most common formats is the CMS format. C MS is the base format. Based on it, a whole bunch of CAdES formats have been compiled.

CMS is a specific structure that contains inside the value of an electronic signature and many additional attributes of this electronic signature. Different CAdES formats are different CMS variants that differ in the set of these attributes.

Xmldsig cryptopro

Files having the logical structure of CMS are physically saved in a binary format based on the ASN.1 format. Here is an example of such a file in a HEX editor and the structure it contains:

Xmldsig cryptopro

There are many signature attributes here, such as:

The signature itself occupies a very small part of the file:

Xmldsig cryptopro

CMS in 1С code

To create a signature in 1C program code, you can use the Cryptography Manager object. First, we initialize the crypto provider, find the certificate (code fragments are given earlier). Then we read the data from the file we want to sign and pass it to the Sign() Cryptography Manager method. In addition to the data for signing, we transfer the signing certificate that we want to use. If all parameters are correct, we will get a signature at the output and write it to a file.

Xmldsig cryptopro

Xmldsig cryptopro

Signature verification is also performed using the cryptography manager. In case of an invalid signature, an exception is thrown.

Xmldsig cryptopro

Signature PDF

The 1C platform allows you to sign PDF files with an electronic signature.

This is an embedded signature, it is contained within the signed document itself, and not in a separate file, as in the previous case.

To create a PDF, the platform has an object called Write PDF. In the 16th version of the platform, the WriteSignature() function appeared in it, which allows you to place an electronic signature in a file, the parameters of which are prepared in advance.

Xmldsig cryptopro

The above code will call the cryptographic provider, calculate the signature of the PDF document using the specified certificate, and place it inside the same document in accordance with the PDF format. Additionally, you can place a picture-stamp of the signature.

Про ГИС ЖКХ:  Реестр гис спб

Xmldsig cryptopro

XMLDSig/XAdES format

XMLDSig and XadES are also a whole family of formats. The logic here is approximately the same as with the CMS and CAdES formats — different XAdES formats contain a different number of attributes, and the basic format is XMLDSig.

For a 1C developer, this is a more complex format than previously discussed. It causes much more trouble, because, unlike the previously described formats, it cannot be obtained just like that in one or two lines of code. Getting this signature is a whole process.

Xmldsig cryptopro

First of all, XMLDSig is a standard for signing XML documents, such as web service messages transmitted over the SOAP protocol. The signature can be embedded or separated, that is, located inside, next to or separate from the data being signed.

Xmldsig cryptopro

Most often, this is an embedded signature, that is, it is contained in the same XML document as the data being signed.

Electronic signature information can be located in different parts of the XML document. If this is a SOAP message, the Header block is often used for this.

Xmldsig cryptopro

But they can also be located in the Body block.

Xmldsig cryptopro

One XML document can contain several electronic signatures, respectively, several XMLDsig blocks.

Specific clarifications of these requirements are usually specified in the documentation for a specific information exchange system.

The standard describes the electronic signature storage block and the tag fields that should be located in it.

Xmldsig cryptopro

The main, root block must be named Signature and belong to the «http://www.w3.org/2000/09/xmldsig#» namespace.

Each Reference element (often one) is a reference to a signed XML fragment. To specify this link, the Id attribute is set in the source data, and the URI attribute is specified in the Reference tag. In the example, we want to sign a part of the document — the Row block. To do this, he was given the attribute Id = «ID1» and referred to this Id in the Reference block.

Xmldsig cryptopro

There are also three subsections in the Reference block:

Xmldsig cryptopro

Thus, in order to sign an XML document with an XMLDSig signature, it is necessary to supplement the document with the formed Signature block and fill in several field tags in it.

Xmldsig cryptopro

Usually these three marked items are:

In this case, the signature field must contain the value of the «raw» signature, that is, free from different formats and wrappers. Only those bytes returned by the cryptographic algorithm. Therefore, it is impossible to use here, for example, a signature in the CMS format, which we already know how to easily receive.

And here comes the problem. The fact is that the 1C platform, represented by the cryptography manager, cannot calculate the «raw» signature. It also does not know how to calculate the necessary hash functions.

Indeed, the platform has a DataHashing object, but it can be used to calculate the hash sums of only the most common algorithms:

Xmldsig cryptopro

But specific ones, for example, the GOST R 34.11-2012 hash required for signing according to GOST, cannot be calculated. On the other hand, such a hash can be calculated by a crypto provider — this is one of its functions.

And here the external component XMLDSig (ExtraCryptoAPI) comes to the rescue. It just has the missing functions:

What is XML Canonicalization?

XML documents have the following feature: the same, logically identical, data in XML can be represented in different ways by writing the physical structure in different ways. And this manifests itself in the following way.

Suppose the sender decides to create an XML document, sign it with an electronic signature and send it somewhere. He got document number 1:

Xmldsig cryptopro

When transferred to the recipient, this document will go through some parsers, libraries, possibly placed inside the SOAP package.

It may happen that for the recipient it will already look like fragment number 2. Perhaps some parser will decide to refine the document a little.

Xmldsig cryptopro

This is not a mistake, because the logical data is the same, contains the same information, just formatted differently.

However, when using cryptography, this is a problem.

The byte representation of these documents is different. And, accordingly, there will be a different hash value and a discrepancy in the electronic signature.

To solve this problem, there is a «canonicalization» mechanism (Canonicalization, canonization, C14N). This is a certain set of rules, described by the W3C standard, which is applied to a document in order to bring it into a single canonical form.

Xmldsig cryptopro

It is assumed that if we have two XML documents that are logically the same, but differ in the form of representation, their canonical form will be the same and match up to a byte.

How will the data transfer process change when using canonicalization:

Xmldsig cryptopro

The sender, having prepared the document

, first passes it through the canonicalization procedure, receives the canonical form Xmldsig cryptopro and already performs cryptographic procedures on it, for example, receives a hash.

Then sends the canonical or original form of the document through communication channels.

The recipient, in turn, having loaded the document (which, for some reason, was converted to the form
during the transmission), will also calculate the canonical form and again receive the same document Xmldsig cryptopro. You can now perform calculations on this document. The result of cryptographic procedures, for example, the calculation of a hash, will now converge with the result of the sender.

Just the canonicalization algorithm used, we must specify in the CanonicalizationMethod section of the Signature block, as well as in the SignedInfo/Reference/Transforms/Transform section.

Usually Algorithm=»http://www.w3.org/2001/10/xml-exc-c14n#» is specified both there and there.

Additional XML transformations

In addition, the XMLDsig standard allows you to perform not only canonicalization using a typical algorithm, but also introduce your own so-called transformations.

In practice, we have encountered such a feature in the SMEV system.

SMEV is a system of interdepartmental electronic interaction, a state system for exchanging data between institutions.

In this system, the document, in addition to XML canonicalization, must be transformed by a special «SMEV transformation» algorithm. Thus, the original XML document goes through one more stage before it gets the canonical form (according to the SMEV system version):

Xmldsig cryptopro

Recently, interaction with this system has become more and more in demand, and in the XMLDSig component, as well as in the BSP, a procedure for this transformation has appeared.

Xmldsig cryptopro

In the case of using an additional transformation, we must also indicate this in the SignedInfo/Reference/Transforms/Transform block, in one more line:

Xmldsig cryptopro

Creating an XMLDsig Signature

Let’s walk through how to create an XMLDSig signature step by step. Let’s leave the code related to XML transformations behind the scenes.

Suppose we have a source XML document, such as a SOAP package, and we want to sign part of it — the «Row» block.

Xmldsig cryptopro

We start by preparing a structure of a certain format for storing signatures.

Xmldsig cryptopro

There are three fragments here that need to be filled in. We have already considered what is placed in them. All values ​​are written as Base64 strings.

From the source text, you need to select this Row block separately and get its canonical form. To do this, we use the method of the XMLDSig component called C14N(). To specify which particular block needs to be selected and converted to the canonical form, we use the XPath expression.

Xmldsig cryptopro

Xmldsig cryptopro

Here you can pay attention to the tabs — all the tabs have been preserved. That is, despite the fact that we pulled the block out of the XML context, its canonical form still contains all whitespace characters, indents between tags. Now we will perform cryptographic operations on this canonical form — calculate the hash.

Compute the hash of this string. This is also done using a component. What specific algorithm we calculate the hash is indicated with the help of the so-called OID — this is a special identifier assigned to a particular algorithm. For example, here it is GOST R 2012.

Xmldsig cryptopro

We get the following value:

Xmldsig cryptopro

Convert the certificate previously received from the store to Base64.

Xmldsig cryptopro

And we place these obtained values ​​in the previously prepared structure in the places intended for them (1, 3).

Xmldsig cryptopro

In DIgestValue

we put a hash, in X509Certificate

— a certificate.

We received an already partially completed construction.

Xmldsig cryptopro

The next step is actually calculating the signature. But we will sign not the Row block (from which it all started), but the SignedInfo block, in which we previously placed the hash (this is how this signature format works).

This block is highlighted in the text. Here, too, the canonicalization procedure must be applied.

Xmldsig cryptopro

An electronic signature must be obtained exactly “raw” — directly the value that the cryptographic function gives at the output. To obtain a signature, we use the Sign() function of the XMLDSig component. Just like we did with the Row block, we call the C14N() canonicalization function, and then we call the Sign() function and get the raw signature value in base64 format.

Xmldsig cryptopro

The resulting value is placed in the appropriate place in the structure, marked here with the number

— «SignatureValue»

Xmldsig cryptopro

Now the document is signed. It can be sent to another participant in the interaction or exchange.

To be continued

This is the first article in a cycle about cryptography and encryption for 1C. In it, we gave the history of the development of the issue, the initial theoretical information about the mathematical apparatus of encryption, talked about the terminological field, which is very rich. They gave practical examples from the life of 1C specialists, where it was necessary to understand the formats, and also understood what the platform has in this part, and what is still missing.

In the next part, we will analyze the practical issues of obtaining keys, legislation and settings in 1C programs.

Оцените статью
ГИС ЖКХ