Saltar al contenido principal

Cifrado de datos

Requisitos

⚠️ Para utilizar esta funcionalidad debes solicitar la activación con el equipo de soporte.

Cifrando las credenciales del usuario

Para esto debes obtener un token de sesión previamente, una vez obtenido el token puedes cifrar los datos utilizando el algoritmo AES-256-CBC como se puede ver en el siguiente ejemplo:

Iniciar proceso de extracción con credenciales cifradas

Endpoint: POST /api/v1/tasks

Request

curl --request POST \
'https://${URL}/api/v1/tasks' \
-H 'Authorization: Bearer ${TOKEN}' \
-H 'Content-Type: application/json' \
-data-raw '{
"action": "banco-santander:tef",
"encryptArgs": "czuqliRO1DKMj4bbPIzMEIYyj4+GqFLBXXc/TM7d3x1dgIDXZeMlyW7vO5vrBpGHyyz+6RtW9jOeqlTDpTH+Nw==-Qlih4F8+I6kZv8xCuSAc2A=="
}'

Response

{
"taskId": "5cbae0b5e1b5d035d99469f42c653ff4bb8aecdf9dbdb8e10f45a31677683369"
}

Implementaciones

El algoritmo de cifrado AES-256-CBC utiliza un vector de inicialización (IV) de 16 bytes, el cual es generado aleatoriamente por el cliente y enviado junto con el texto cifrado, para que el servidor pueda descifrarlo. El formato de la cadena de texto cifrado es el siguiente:

${CIPHER_TEXT}-${IV}

NodeJS

const crypto = require('crypto');

function encrypt(token, data) {
const hash = crypto.createHash('sha256').update(token).digest('hex');
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv(
'aes-256-cbc',
Buffer.from(hash, 'hex'),
iv
);
const plaintextBytes = Buffer.from(data, 'utf8');
const cipherTextBytes = Buffer.concat([
cipher.update(plaintextBytes),
cipher.final()
]);
const encryptedArgs =
cipherTextBytes.toString('base64') + '-' + iv.toString('base64');
return encryptedArgs;
}

const token = 'TOKEN';
const data = {
username: '11.111.111-1',
password: 'AAAAA11111'
};

const dataToJson = JSON.stringify(data);

const encryptedText = encrypt(token, dataToJson);
console.log(encryptedText);

// Results
// 2iHTdihWU9zAcb+ixoavm6xcmk3xq8+3NMIBd5gpleTHnWT41EoPltpcllnRdiJb7V6EK/2mz3ccxozaZ79Wcw==-0s8j3MAEU7bBEYHjVIK6aQ==

Python

Requisitos

  • pycryptodome
import json
import hashlib
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from base64 import b64decode, b64encode


def encrypt(token, plaintext):
utf8_key = token.encode('utf-8')
hashed_key = hashlib.sha256(utf8_key).digest()

cipher = AES.new(hashed_key, AES.MODE_CBC)
ct_bytes = cipher.encrypt(pad(plaintext.encode("UTF-8"), AES.block_size))
iv = b64encode(cipher.iv).decode("utf-8")
cipherText = b64encode(ct_bytes).decode("utf-8")
return f"{cipherText}-{iv}"


if __name__ == "__main__":
token = "TOKEN"
data = {
"username": '11.111.111-1',
"password": 'AAAAA11111',
}

dataToJson = json.dumps(data)
encryptedText = encrypt(token, dataToJson)
print(encryptedText)

# Results
# 2iHTdihWU9zAcb+ixoavm6xcmk3xq8+3NMIBd5gpleTHnWT41EoPltpcllnRdiJb7V6EK/2mz3ccxozaZ79Wcw==-0s8j3MAEU7bBEYHjVIK6aQ==

Java

Version: openjdk 11.0.16 2022-07-19

⚠️ Este es un ejemplo de implementación, no es recomendable utilizar este código en producción.

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.math.BigInteger;

public class Main {

public static void main(String[] args) throws Exception {
String token = "TOKEN";
String jsonString = "{\"username\":\"11.111.111-1\",\"password\":\"AAAAA11111\"}";

String encrypted = encrypt(token, jsonString);
String hash = toHexString(getSHA(token));

System.out.println("Hash: " + hash);
System.out.println("Encrypted: " + encrypted);

}

public static byte[] getSHA(String input) throws NoSuchAlgorithmException
{
MessageDigest md = MessageDigest.getInstance("SHA-256");
return md.digest(input.getBytes(StandardCharsets.UTF_8));
}

public static String toHexString(byte[] hash)
{
BigInteger number = new BigInteger(1, hash);
StringBuilder hexString = new StringBuilder(number.toString(16));

// Pad with leading zeros
while (hexString.length() < 64)
{
hexString.insert(0, '0');
}

return hexString.toString();
}

public static String encrypt(String token, String data) throws Exception {
SecureRandom random = new SecureRandom();
byte[] ivBytes = new byte[16];
random.nextBytes(ivBytes);

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(getSHA(token), "AES");
IvParameterSpec iv = new IvParameterSpec(ivBytes);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);

byte[] plaintextBytes = data.getBytes(StandardCharsets.UTF_8);
byte[] cipherTextBytes = cipher.doFinal(plaintextBytes);

String cipherTextBase64 = Base64.getEncoder().encodeToString(cipherTextBytes);
String ivBase64 = Base64.getEncoder().encodeToString(ivBytes);
return cipherTextBase64 + "-" + ivBase64;
}
}