Skip to content
This repository has been archived by the owner on Feb 28, 2024. It is now read-only.

Mastercard/client-encryption-php

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

91 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

client-encryption-php

maintenance-status

Table of Contents

Overview

Library for Mastercard API compliant payload encryption/decryption.

Compatibility

PHP 7.0+

References

Encryption of sensitive data

Versioning and Deprecation Policy

Usage

Prerequisites

Before using this library, you will need to set up a project in the Mastercard Developers Portal.

As part of this set up, you'll receive:

  • A public request encryption certificate (aka Client Encryption Keys)
  • A private response decryption key (aka Mastercard Encryption Keys)

Adding the Library to Your Project

composer require mastercard/client-encryption

Loading the Encryption Certificate

A certificate resource can be created from a file by calling EncryptionUtils::loadEncryptionCertificate:

use Mastercard\Developer\Utils\EncryptionUtils;
// …
$encryptionCertificate = EncryptionUtils::loadEncryptionCertificate('<insert certificate file path>');

Supported certificate formats: PEM, DER.

Loading the Decryption Key

From a PKCS#12 Key Store

A private key resource can be created from a PKCS#12 key store by calling EncryptionUtils::loadDecryptionKey the following way:

use Mastercard\Developer\Utils\EncryptionUtils;
// …
$decryptionKey = EncryptionUtils::loadDecryptionKey(
                                    '<insert PKCS#12 key file path>', 
                                    '<insert key alias>', 
                                    '<insert key password>');

From an Unencrypted Key File

A private key resource can be created from an unencrypted key file by calling EncryptionUtils::loadDecryptionKey the following way:

use Mastercard\Developer\Utils\EncryptionUtils;
// …
$decryptionKey = EncryptionUtils::loadDecryptionKey('<insert key file path>');

Supported RSA key formats:

  • PKCS#1 PEM (starts with '-----BEGIN RSA PRIVATE KEY-----')
  • PKCS#8 PEM (starts with '-----BEGIN PRIVATE KEY-----')
  • Binary DER-encoded PKCS#8

Performing Field Level Encryption and Decryption

Introduction

The core methods responsible for payload encryption and decryption are encryptPayload and decryptPayload in the FieldLevelEncryption class.

  • encryptPayload usage:
use Mastercard\Developer\Encryption;
// …
$encryptedRequestPayload = FieldLevelEncryption::encryptPayload($requestPayload, $config);
  • decryptPayload usage:
use Mastercard\Developer\Encryption;
// …
$responsePayload = FieldLevelEncryption::decryptPayload($encryptedResponsePayload, $config);

Configuring the Field Level Encryption

Use the FieldLevelEncryptionConfigBuilder to create FieldLevelEncryptionConfig instances. Example:

use Mastercard\Developer\Encryption;
// …
$config = FieldLevelEncryptionConfigBuilder::aFieldLevelEncryptionConfig()
    ->withEncryptionCertificate($encryptionCertificate)
    ->withDecryptionKey($decryptionKey)
    ->withEncryptionPath('$.path.to.foo', '$.path.to.encryptedFoo')
    ->withDecryptionPath('$.path.to.encryptedFoo', '$.path.to.foo')
    ->withOaepPaddingDigestAlgorithm('SHA-256')
    ->withEncryptedValueFieldName('encryptedValue')
    ->withEncryptedKeyFieldName('encryptedKey')
    ->withIvFieldName('iv')
    ->withFieldValueEncoding(FieldValueEncoding::HEX)
    ->build();

See also:

Performing Encryption

Call FieldLevelEncryption::encryptPayload with a JSON request payload and a FieldLevelEncryptionConfig instance.

Example using the configuration above:

use Mastercard\Developer\Encryption;
// …
$payload = '{
    "path": {
        "to": {
            "foo": {
                "sensitiveField1": "sensitiveValue1",
                "sensitiveField2": "sensitiveValue2"
            }
        }
    }
}';
$encryptedPayload = FieldLevelEncryption::encryptPayload($payload, $config);
echo (json_encode(json_decode($encryptedPayload), JSON_PRETTY_PRINT));

Output:

{
    "path": {
        "to": {
            "encryptedFoo": {
                "iv": "7f1105fb0c684864a189fb3709ce3d28",
                "encryptedKey": "67f467d1b653d98411a0c6d3c…ffd4c09dd42f713a51bff2b48f937c8",
                "encryptedValue": "b73aabd267517fc09ed72455c2…dffb5fa04bf6e6ce9ade1ff514ed6141"
            }
        }
    }
}

Performing Decryption

Call FieldLevelEncryption::decryptPayload with a JSON response payload and a FieldLevelEncryptionConfig instance.

Example using the configuration above:

use Mastercard\Developer\Encryption;
// …
$encryptedPayload = '{
    "path": {
        "to": {
            "encryptedFoo": {
                "iv": "e5d313c056c411170bf07ac82ede78c9",
                "encryptedKey": "e3a56746c0f9109d18b3a2652b76…f16d8afeff36b2479652f5c24ae7bd",
                "encryptedValue": "809a09d78257af5379df0c454dcdf…353ed59fe72fd4a7735c69da4080e74f"
            }
        }
    }
}';
$payload = FieldLevelEncryption::decryptPayload($encryptedPayload, $config);
echo (json_encode(json_decode($payload), JSON_PRETTY_PRINT));

Output:

{
    "path": {
        "to": {
            "foo": {
                "sensitiveField1": "sensitiveValue1",
                "sensitiveField2": "sensitiveValue2"
            }
        }
    }
}

Encrypting Entire Payloads

Entire payloads can be encrypted using the '$' operator as encryption path:

use Mastercard\Developer\Encryption;
// …
$config = FieldLevelEncryptionConfigBuilder::aFieldLevelEncryptionConfig()
    ->withEncryptionCertificate(encryptionCertificate)
    ->withEncryptionPath('$', '$')
    // …
    ->build();

Example:

use Mastercard\Developer\Encryption;
// …
$payload = '{
    "sensitiveField1": "sensitiveValue1",
    "sensitiveField2": "sensitiveValue2"
}';
$encryptedPayload = FieldLevelEncryption::encryptPayload($payload, $config);
echo (json_encode(json_decode($encryptedPayload), JSON_PRETTY_PRINT));

Output:

{
    "iv": "1b9396c98ab2bfd195de661d70905a45",
    "encryptedKey": "7d5112fa08e554e3dbc455d0628…52e826dd10311cf0d63bbfb231a1a63ecc13",
    "encryptedValue": "e5e9340f4d2618d27f8955828c86…379b13901a3b1e2efed616b6750a90fd379515"
}

Decrypting Entire Payloads

Entire payloads can be decrypted using the '$' operator as decryption path:

use Mastercard\Developer\Encryption;
// …
$config = FieldLevelEncryptionConfigBuilder::aFieldLevelEncryptionConfig()
    ->withDecryptionKey(decryptionKey)
    ->withDecryptionPath('$', '$')
    // …
    ->build();

Example:

use Mastercard\Developer\Encryption;
// …
$encryptedPayload = '{
    "iv": "1b9396c98ab2bfd195de661d70905a45",
    "encryptedKey": "7d5112fa08e554e3dbc455d0628…52e826dd10311cf0d63bbfb231a1a63ecc13",
    "encryptedValue": "e5e9340f4d2618d27f8955828c86…379b13901a3b1e2efed616b6750a90fd379515"
}';
$payload = FieldLevelEncryption::decryptPayload($encryptedPayload, $config);
echo (json_encode(json_decode($payload), JSON_PRETTY_PRINT));

Output:

{
    "sensitiveField1": "sensitiveValue1",
    "sensitiveField2": "sensitiveValue2"
}

Using HTTP Headers for Encryption Params

In the sections above, encryption parameters (initialization vector, encrypted symmetric key, etc.) are part of the HTTP payloads.

Here is how to configure the library for using HTTP headers instead.

Configuration for Using HTTP Headers

Call with{Param}HeaderName instead of with{Param}FieldName when building a FieldLevelEncryptionConfig instance. Example:

use Mastercard\Developer\Encryption;
// …
$config = FieldLevelEncryptionConfigBuilder::aFieldLevelEncryptionConfig()
    ->withEncryptionCertificate(encryptionCertificate)
    ->withDecryptionKey(decryptionKey)
    ->withEncryptionPath('$', '$')
    ->withDecryptionPath('$', '$')
    ->withOaepPaddingDigestAlgorithm('SHA-256')
    ->withEncryptedValueFieldName('data')
    ->withIvHeaderName('x-iv')
    ->withEncryptedKeyHeaderName('x-encrypted-key')
    // …
    ->withFieldValueEncoding(FieldValueEncoding::HEX)
    ->build();

See also:

Encrypting Using HTTP Headers

Encryption can be performed using the following steps:

  1. Generate parameters by calling FieldLevelEncryptionParams::generate:
$params = FieldLevelEncryptionParams::generate($config);
  1. Update the request headers:
$request->setHeader($config->getIvHeaderName(), $params->getIvValue());
$request->setHeader($config->getEncryptedKeyHeaderName(), $params->getEncryptedKeyValue());
// …
  1. Call encryptPayload with params:
FieldLevelEncryption::encryptPayload($payload, $config, $params);

Example using the configuration above:

$payload = '{
    "sensitiveField1": "sensitiveValue1",
    "sensitiveField2": "sensitiveValue2"
}';
$encryptedPayload = FieldLevelEncryption::encryptPayload($payload, $config, $params);
echo (json_encode(json_decode($encryptedPayload), JSON_PRETTY_PRINT));

Output:

{
    "data": "53b5f07ee46403af2e92abab900853…d560a0a08a1ed142099e3f4c84fe5e5"
}
Decrypting Using HTTP Headers

Decryption can be performed using the following steps:

  1. Read the response headers:
$ivValue = $response->getHeader($config->getIvHeaderName());
$encryptedKeyValue = $response->getHeader($config->getEncryptedKeyHeaderName());
// …
  1. Create a FieldLevelEncryptionParams instance:
$params = new FieldLevelEncryptionParams($config, $ivValue, $encryptedKeyValue, …, );
  1. Call decryptPayload with params:
FieldLevelEncryption::decryptPayload($encryptedPayload, $config, $params);

Example using the configuration above:

$encryptedPayload = '{
    "data": "53b5f07ee46403af2e92abab900853…d560a0a08a1ed142099e3f4c84fe5e5"
}';
$payload = FieldLevelEncryption::decryptPayload($encryptedPayload, $config, $params);
echo (json_encode(json_decode($payload), JSON_PRETTY_PRINT));

Output:

{
    "sensitiveField1": "sensitiveValue1",
    "sensitiveField2": "sensitiveValue2"
}

Performing JWE Encryption and Decryption

Introduction

The core methods responsible for payload encryption and decryption are encryptPayload and decryptPayload in the JweEncryption class.

  • encryptPayload usage:
use Mastercard\Developer\Encryption;
// …
$encryptedRequestPayload = JweEncryption::encryptPayload($requestPayload, $config);
  • decryptPayload usage:
use Mastercard\Developer\Encryption;
// …
$responsePayload = JweEncryption::decryptPayload($encryptedResponsePayload, $config);

Configuring the JWE Encryption

Use the JweEncryptionConfigBuilder to create JweEncryptionConfig instances. Example:

use Mastercard\Developer\Encryption;
// …
$config = JweEncryptionConfigBuilder::aJweEncryptionConfig()
    ->withEncryptionCertificate($encryptionCertificate)
    ->withDecryptionKey($decryptionKey)
    ->withEncryptionPath('$.path.to.foo', '$.path.to.encryptedFoo')
    ->withDecryptionPath('$.path.to.encryptedFoo', '$.path.to.foo')
    ->withEncryptedValueFieldName('encryptedValue')
    ->build();

Note: If withEncryptedValueFieldName is left blank, the value will default to encryptedData

See also:

Performing Encryption

Call JweEncryption::encryptPayload with a JSON request payload and a JweEncryptionConfig instance.

Example using the configuration above:

use Mastercard\Developer\Encryption;
// …
$payload = '{
    "path": {
        "to": {
            "foo": {
                "sensitiveField1": "sensitiveValue1",
                "sensitiveField2": "sensitiveValue2"
            }
        }
    }
}';
$encryptedPayload = JweEncryption::encryptPayload($payload, $config);
echo (json_encode(json_decode($encryptedPayload), JSON_PRETTY_PRINT));

Output:

{
  "path": {
    "to": {
      "encryptedFoo": "809a09d78257af5379df0c454dcdf…353ed59fe72fd4a7735c69da4080e74f"
    }
  }
}

Performing Decryption

Call JweEncryption::decryptPayload with a JSON response payload and a JweEncryptionConfig instance.

Example using the configuration above:

use Mastercard\Developer\Encryption;
// …
$encryptedPayload = '{
    "path": {
        "to": {
            "encryptedFoo": {
                "encryptedValue": "809a09d78257af5379df0c454dcdf…353ed59fe72fd4a7735c69da4080e74f"
            }
        }
    }
}';
$payload = JweEncryption::decryptPayload($encryptedPayload, $config);
echo (json_encode(json_decode($payload), JSON_PRETTY_PRINT));

Output:

{
    "path": {
        "to": {
            "foo": {
                "sensitiveField1": "sensitiveValue1",
                "sensitiveField2": "sensitiveValue2"
            }
        }
    }
}

Encrypting Entire Payloads

Entire payloads can be encrypted using the '$' operator as encryption path:

use Mastercard\Developer\Encryption;
// …
$config = JweConfigBuilder::aJweEncryptionConfig()
    ->withEncryptionCertificate(encryptionCertificate)
    ->withEncryptionPath('$', '$')
    ->withEncryptedValueFieldName("encryptedValue")
    // …
    ->build();

Example:

use Mastercard\Developer\Encryption;
// …
$payload = '{
    "sensitiveField1": "sensitiveValue1",
    "sensitiveField2": "sensitiveValue2"
}';
$encryptedPayload = JweEncryption::encryptPayload($payload, $config);
echo (json_encode(json_decode($encryptedPayload), JSON_PRETTY_PRINT));

Output:

{
    "encryptedValue": "e5e9340f4d2618d27f8955828c86…379b13901a3b1e2efed616b6750a90fd379515"
}

Decrypting Entire Payloads

Entire payloads can be decrypted using the '$' operator as decryption path:

use Mastercard\Developer\Encryption;
// …
$config = JweEncryptionConfigBuilder::aJweEncryptionConfig()
    ->withDecryptionKey(decryptionKey)
    ->withDecryptionPath('$', '$')
    ->withEncryptedValueFieldName("encryptedValue")
    // …
    ->build();

Example:

use Mastercard\Developer\Encryption;
// …
$encryptedPayload = '{
    "encryptedValue": "e5e9340f4d2618d27f8955828c86…379b13901a3b1e2efed616b6750a90fd379515"
}';
$payload = FieldLevelEncryption::decryptPayload($encryptedPayload, $config);
echo (json_encode(json_decode($payload), JSON_PRETTY_PRINT));

Output:

{
    "sensitiveField1": "sensitiveValue1",
    "sensitiveField2": "sensitiveValue2"
}

Integrating with OpenAPI Generator API Client Libraries

OpenAPI Generator generates API client libraries from OpenAPI Specs. It provides generators and library templates for supporting multiple languages and frameworks.

This project provides you with some interceptor classes you can use when configuring your API client. These classes will take care of encrypting request and decrypting response payloads, but also of updating HTTP headers when needed.

Generators currently supported:

php

OpenAPI Generator

Client libraries can be generated using the following command:

openapi-generator-cli generate -i openapi-spec.yaml -g php -o out

See also:

Usage of the PsrHttpMessageEncryptionInterceptor for Field Level Encryption
use GuzzleHttp;
use OpenAPI\Client\Api\ServiceApi;
use OpenAPI\Client\Configuration
use Mastercard\Developer\Signers\PsrHttpMessageSigner;
use Mastercard\Developer\Interceptors\PsrHttpMessageEncryptionInterceptor;
// …

$stack = new GuzzleHttp\HandlerStack();
$stack->setHandler(new GuzzleHttp\Handler\CurlHandler());
$fieldLevelEncryptionConfig = FieldLevelEncryptionConfigBuilder::aFieldLevelEncryptionConfig()
    // …
    ->build();
$fieldLevelEncryptionInterceptor = new PsrHttpMessageEncryptionInterceptor($fieldLevelEncryptionConfig);
$stack->push(GuzzleHttp\Middleware::mapRequest([$fieldLevelEncryptionInterceptor, 'interceptRequest']));
$stack->push(GuzzleHttp\Middleware::mapResponse([$fieldLevelEncryptionInterceptor, 'interceptResponse']));
$stack->push(GuzzleHttp\Middleware::mapRequest([new PsrHttpMessageSigner($consumerKey, $signingKey), 'sign']));
$options = ['handler' => $stack];
$client = new GuzzleHttp\Client($options);
$config = new Configuration();
$config->setHost('https://sandbox.api.mastercard.com');
$serviceApi = new ServiceApi($client, $config);
// …
Usage of the PsrHttpMessageEncryptionInterceptor for JWE Encryption
use GuzzleHttp;
use OpenAPI\Client\Api\ServiceApi;
use OpenAPI\Client\Configuration
use Mastercard\Developer\Signers\PsrHttpMessageSigner;
use Mastercard\Developer\Interceptors\PsrHttpMessageEncryptionInterceptor;
// …

$stack = new GuzzleHttp\HandlerStack();
$stack->setHandler(new GuzzleHttp\Handler\CurlHandler());
$JweEncryptionConfig = JweEncryptionConfigBuilder::aJweEncryptionConfig()
    // …
    ->build();
$JweEncryptionInterceptor = new PsrHttpMessageEncryptionInterceptor($JweEncryptionConfig);
$stack->push(GuzzleHttp\Middleware::mapRequest([$JweEncryptionInterceptor, 'interceptRequest']));
$stack->push(GuzzleHttp\Middleware::mapResponse([$JweEncryptionInterceptor, 'interceptResponse']));
$stack->push(GuzzleHttp\Middleware::mapRequest([new PsrHttpMessageSigner($consumerKey, $signingKey), 'sign']));
$options = ['handler' => $stack];
$client = new GuzzleHttp\Client($options);
$config = new Configuration();
$config->setHost('https://sandbox.api.mastercard.com');
$serviceApi = new ServiceApi($client, $config);
// …