> For the complete documentation index, see [llms.txt](https://docs.payments.thalescloud.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.payments.thalescloud.io/classic-tokenization/es/comenzar/conceptos-basicos-de-la-api/cifrado-y-seguridad-de-datos.md).

# Cifrado y seguridad de datos

### Cifrado a nivel de aplicación de datos sensibles <a href="#application-level-encryption-of-sensitive-data" id="application-level-encryption-of-sensitive-data"></a>

Los campos sensibles según PCI en los mensajes API entrantes y salientes se cifran usando el formato PKCS#7 enveloped-data. Esto es además de la conexión mutual TLS (mTLS).

<figure><img src="/files/abcf4fbc9f56e3e2ca3aea1396040eab03c7206c" alt=""><figcaption><p>Cifrado PKCS#7 a nivel de aplicación sobre mutual TLS (mTLS).</p></figcaption></figure>

### Claves y certificados <a href="#keys-and-certificates" id="keys-and-certificates"></a>

Use el portal TSH durante la incorporación a TSH para gestionar certificados PKCS#7:

* Cargue su certificado del Emisor (`ISSUER_PKCS7_CERT`). Thales TSH lo usa para cifrar los campos sensibles PCI enviados al backend del emisor. Thales TSH también envía el identificador del certificado para que pueda seleccionar la clave privada adecuada (por ejemplo, en `RequestCardDigitalization`).
* Descargue el certificado de Thales. Úselo para cifrar los campos sensibles PCI enviados desde el backend del emisor a Thales TSH. Incluya el identificador del certificado en su solicitud para que Thales TSH pueda seleccionar la clave privada correcta (por ejemplo, en `UpdateCard`).

### Parámetros de cifrado <a href="#encryption-parameters" id="encryption-parameters"></a>

PKCS#7 y CMS están definidos en RFC 2315 y RFC 5652. La mayoría de las bibliotecas criptográficas soportan las operaciones requeridas.

Parámetros de cifrado:

* Algoritmo de cifrado del contenido: `AES-256-CBC` con `PKCS7Padding`.
* Algoritmo de cifrado de clave: `RSA/None/OAEPWithSHA256AndMGF1Padding` (MGF1 usa SHA-256), con una clave pública RSA de 2048 o 4096 bits.
* Codificación de salida: representación de cadena hexadecimal.

#### Ejemplos de cifrado PKCS#7 <a href="#pkcs7-encryption-examples" id="pkcs7-encryption-examples"></a>

Estos ejemplos de código muestran cómo generar y procesar PKCS#7 enveloped-data. En la API de TSH, los bytes cifrados se codifican como una cadena hexadecimal.

{% tabs %}
{% tab title="Java" %}

```java
package com.gemalto.test.pkcs7;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.MGF1ParameterSpec;
import java.util.Collection;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.PSource;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;

import org.bouncycastle.cms.CMSAlgorithm;
import org.bouncycastle.cms.CMSEnvelopedData;
import org.bouncycastle.cms.CMSEnvelopedDataGenerator;
import org.bouncycastle.cms.CMSProcessableByteArray;
import org.bouncycastle.cms.KeyTransRecipientInformation;
import org.bouncycastle.cms.RecipientInformation;
import org.bouncycastle.cms.bc.BcCMSContentEncryptorBuilder;
import org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient;
import org.bouncycastle.cms.jcajce.JceKeyTransRecipientInfoGenerator;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.jcajce.JcaAlgorithmParametersConverter;
import org.bouncycastle.util.encoders.Hex;

public class TpcEncryptPkcs7 {

    private static final String DATA_TO_ENCRYPT = "{\"fpan\":\"987654321123456789\",\"issuerCardRefId\":\"abc1245784219\",\"exp\":\"1223\",\"cardholderName\":\"John\""
            + ",\"postalAddress\":{\"line1\":\"address1\",\"line2\":\"address2\",\"city\":\"City1\",\"postalCode\":\"12345\",\"state\":\"state1\",\"country\":\"Country1\"}}";

    private static final String KEY_IDENTIFIER = "a_key_id";

    private static final BouncyCastleProvider bcProvider;
    private static PrivateKey privKey;
    private static PublicKey pubKey;

    static {
        bcProvider = new BouncyCastleProvider();
        Security.addProvider(bcProvider);
    }

    public static void main(String[] args) throws Exception {

        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(2048);
        KeyPair kp = kpg.generateKeyPair();
        privKey = kp.getPrivate();
        pubKey = kp.getPublic();

        // Encrypt
        byte[] encData = encryptPKCS7(DATA_TO_ENCRYPT.getBytes("UTF-8"), pubKey);
        System.out.println("Encrypted data = " + Hex.toHexString(encData));

        // Decrypt
        byte[] result = decryptPKCS7(encData, privKey);
        System.out.println("Decrypted data = " + new String(result));

    }

    private static byte[] encryptPKCS7(byte[] plainData, PublicKey pubKey) throws Exception {

        CMSEnvelopedDataGenerator gen = new CMSEnvelopedDataGenerator();

        JcaAlgorithmParametersConverter paramsConverter = new JcaAlgorithmParametersConverter();
        OAEPParameterSpec oaepParamSpec = new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT);
        AlgorithmIdentifier algoId = paramsConverter.getAlgorithmIdentifier(PKCSObjectIdentifiers.id_RSAES_OAEP, oaepParamSpec);

        JceKeyTransRecipientInfoGenerator recipInfo = new JceKeyTransRecipientInfoGenerator(KEY_IDENTIFIER.getBytes(), algoId, pubKey)
                .setProvider(bcProvider);

        gen.addRecipientInfoGenerator(recipInfo);

        CMSProcessableByteArray data = new CMSProcessableByteArray(plainData);
        BcCMSContentEncryptorBuilder builder = new BcCMSContentEncryptorBuilder(CMSAlgorithm.AES256_CBC);

        CMSEnvelopedData enveloped = gen.generate(data, builder.build());

        return enveloped.getEncoded();
    }

    private static byte[] decryptPKCS7(byte[] encryptedData, PrivateKey privKey) throws Exception {
        CMSEnvelopedData enveloped = new CMSEnvelopedData(encryptedData);
        Collection<RecipientInformation> recip = enveloped.getRecipientInfos().getRecipients();
        KeyTransRecipientInformation rinfo = (KeyTransRecipientInformation) recip.iterator().next();
        return rinfo.getContent(new JceKeyTransEnvelopedRecipient(privKey).setProvider(bcProvider));
    }

}
```

{% endtab %}

{% tab title="C#" %}

```csharp
AsymmetricCipherKeyPair keyPair;

using (var txtreader = new StringReader(privateKey))
{
    keyPair = (AsymmetricCipherKeyPair)new PemReader(txtreader).ReadObject();
}

var bytesToDecrypt = Convert.FromBase64String(base64Input);

CmsEnvelopedData env = new CmsEnvelopedData(bytesToDecrypt);

KeyTransRecipientInformation recip = (KeyTransRecipientInformation)new System.Collections.ArrayList(env.GetRecipientInfos().GetRecipients())[0];

var message = recip.GetContent(keyPair.Private);

return System.Text.Encoding.GetEncoding("ISO-8859-1").GetString(message);
```

{% endtab %}
{% endtabs %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.payments.thalescloud.io/classic-tokenization/es/comenzar/conceptos-basicos-de-la-api/cifrado-y-seguridad-de-datos.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
