> ## Documentation Index
> Fetch the complete documentation index at: https://docs.juicyway.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Encryption Keys

> Secure your card data with strong encryption

# Payment Data Encryption

<Warning>
  Never send raw card data directly to your backend or our API. All sensitive payment information must be encrypted client-side before transmission.
</Warning>

Protecting customer payment information is critical. Our API uses strong encryption to safeguard sensitive data. This guide explains how to securely handle encryption for card data in your integration.

## Fetching Encryption Keys

To encrypt sensitive card information, you first need to retrieve your unique encryption keys. Make a GET request to:

```bash theme={null}
GET /keys/encryption-key
```

**Parameters**

<ParamField path="mode" type="string" required>
  Environment Mode. Available Values: `live`, `test`
</ParamField>

**Successful Response (200 OK):**

```json theme={null}
{
  "data": {
    "encryption_key": "67634cc972d2433b8725c8f6fbfdf792"
  }
}
```

**Error Response (400 Bad Request):**
Indicates an issue with the request, such as an invalid `mode`.

### Encryption Process

When handling sensitive card data, follow these steps:

1. Fetch the encryption key for your environment (test/live)

2. Format the card data as a JSON string

3. Generate a random initialization vector (IV)

4. Encrypt the data using AES-256-GCM with your encryption key and IV

5. Concatenate the hex-encoded IV, ciphertext, and authentication tag

6. Send the encrypted data to our API

<Warning>
  Never send raw card data directly to your backend or our API. Always encrypt it first on the client-side.
</Warning>

### Code Examples

<Tabs>
  <Tab title="PHP">
    ```php theme={null}
    function card_encrypt($payload, $key) {
        $iv = openssl_random_pseudo_bytes(16);
        $cipher_text = openssl_encrypt(
            $payload, 
            "aes-256-gcm", 
            $key, 
            OPENSSL_RAW_DATA, 
            $iv, 
            $tag
        );
        return implode(':', [
            bin2hex($iv),
            bin2hex($cipher_text),
            bin2hex($tag)
        ]);
    }

    // Example usage
    $card_data = json_encode([
        'card_number' => '4111111111111111',
        'expiry_month' => '12',
        'expiry_year' => '2025',
        'cvv' => '123'
    ]);
    $encrypted = card_encrypt($card_data, $encryption_key);
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    const cardEncrypt = async (payload, encKey) => {
      const _iv = crypto.getRandomValues(new Uint8Array(12));
      const encodedPlaintext = new TextEncoder().encode(payload);
      
      const secretKey = await crypto.subtle.importKey(
        "raw",
        Buffer.from(encKey, "utf8"),
        {
          name: "AES-GCM",
          length: 256,
        },
        true,
        ["encrypt", "decrypt"],
      );

      const cipherText = await crypto.subtle.encrypt(
        {
          name: "AES-GCM",
          iv: _iv,
        },
        secretKey,
        encodedPlaintext,
      );

      const [value, auth_tag] = [
        cipherText.slice(0, cipherText.byteLength - 16),
        cipherText.slice(cipherText.byteLength - 16),
      ];

      const cipher = Buffer.from(value).toString("hex");
      const iv = Buffer.from(_iv).toString("hex");
      const tag = Buffer.from(auth_tag).toString("hex");
      
      return [iv, cipher, tag].join(":");
    };

    // Example usage
    const cardData = JSON.stringify({
      card_number: '4111111111111111',
      expiry_month: '12',
      expiry_year: '2025',
      cvv: '123'
    });
    const encrypted = await cardEncrypt(cardData, encryptionKey);
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    from cryptography.hazmat.primitives.ciphers.aead import AESGCM
    import os
    import json
    import binascii

    def card_encrypt(payload, key):
        # Convert hex key to bytes
        key_bytes = bytes.fromhex(key)
        
        # Generate random IV
        iv = os.urandom(12)
        
        # Create AESGCM instance
        aesgcm = AESGCM(key_bytes)
        
        # Encrypt the payload
        payload_bytes = payload.encode()
        cipher_text = aesgcm.encrypt(iv, payload_bytes, None)
        
        # Split cipher text and auth tag
        auth_tag = cipher_text[-16:]
        encrypted_data = cipher_text[:-16]
        
        # Format result
        return ':'.join([
            binascii.hexlify(iv).decode(),
            binascii.hexlify(encrypted_data).decode(),
            binascii.hexlify(auth_tag).decode()
        ])

    # Example usage
    card_data = json.dumps({
        'card_number': '4111111111111111',
        'expiry_month': '12',
        'expiry_year': '2025',
        'cvv': '123'
    })
    encrypted = card_encrypt(card_data, encryption_key)
    ```
  </Tab>

  <Tab title="Ruby">
    ```ruby theme={null}
    require 'openssl'
    require 'json'

    def card_encrypt(payload, key)
      # Convert hex key to binary
      key_bin = [key].pack('H*')
      
      # Generate random IV
      iv = OpenSSL::Random.random_bytes(12)
      
      # Create cipher
      cipher = OpenSSL::Cipher.new('aes-256-gcm')
      cipher.encrypt
      cipher.key = key_bin
      cipher.iv = iv
      
      # Encrypt
      cipher.auth_data = ""
      encrypted = cipher.update(payload) + cipher.final
      tag = cipher.auth_tag
      
      # Format result
      [
        iv.unpack('H*')[0],
        encrypted.unpack('H*')[0],
        tag.unpack('H*')[0]
      ].join(':')
    end

    # Example usage
    card_data = JSON.generate({
      card_number: '4111111111111111',
      expiry_month: '12',
      expiry_year: '2025',
      cvv: '123'
    })
    encrypted = card_encrypt(card_data, encryption_key)
    ```
  </Tab>
</Tabs>

### Security Best Practices

<AccordionGroup>
  <Accordion title="Key Management">
    * Store encryption keys securely in environment variables or a key management service

    * Never commit encryption keys to source control

    * Rotate encryption keys periodically (we'll notify you before key expiration)

    * Use different keys for test and production environments
  </Accordion>

  <Accordion title="Data Handling">
    * Encrypt sensitive data as soon as it's collected

    * Clear sensitive data from memory after use

    * Never log or store raw card data

    * Use HTTPS for all API communications
  </Accordion>

  <Accordion title="Client-side Security">
    * Implement Content Security Policy (CSP) headers

    * Use Subresource Integrity for external scripts

    * Minimize the time sensitive data remains in memory

    * Clear form fields after encryption
  </Accordion>
</AccordionGroup>

### Troubleshooting Guide

<AccordionGroup>
  <Accordion title="Invalid Encryption Format">
    If you receive an "Invalid encryption format" error:

    * Verify the encryption key is correct and valid

    * Ensure IV, ciphertext, and tag are properly concatenated with colons

    * Check that all components are properly hex-encoded
  </Accordion>

  <Accordion title="Authentication Failed">
    If you receive an "Authentication failed" error:

    * Verify you're using the correct encryption key for your environment

    * Check that the authentication tag is being properly generated and included

    * Ensure the payload hasn't been modified after encryption
  </Accordion>

  <Accordion title="Common Implementation Issues">
    * **Random IV Generation**: Ensure a new random IV is generated for each encryption

    * **Memory Management**: Clear sensitive data from variables after use

    * **Encoding Issues**: Verify proper encoding/decoding of binary data to hex

    * **Library Version Compatibility**: Check cryptographic library versions match requirements
  </Accordion>
</AccordionGroup>
