Skip to content

Mastercard/client-encryption-csharp

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

client-encryption-csharp

Table of Contents

Overview

Compatibility

.NET

  • ClientEncryption.Core targets .NET Standard 2.1
  • ClientEncryption.RestSharpV2 targets .NET Standard 2.1
  • ClientEncryption.RestSharp targets .NET Standard 2.1

.NET Standard versions supported by .NET implementations can be found in the following articles: .NET Standard, .NET Standard versions.

Strong Naming

Assemblies are strong-named as per Strong naming and .NET libraries. The SN key is available here: Identity.snk.

References

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 Libraries to Your Project

Package Manager

Install-Package Mastercard.Developer.ClientEncryption.{Core|RestSharp|RestSharpV2}

.NET CLI

dotnet add package Mastercard.Developer.ClientEncryption.{Core|RestSharp|RestSharpV2}

Loading the Encryption Certificate

A System.Security.Cryptography.X509Certificates.X509Certificate object can be created from a file by calling EncryptionUtils.LoadEncryptionCertificate:

var encryptionCertificate = EncryptionUtils.LoadEncryptionCertificate("<insert certificate file path>");

Supported certificate formats: PEM, DER.

Loading the Decryption Key

From a PKCS#12 Key Store

A System.Security.Cryptography.RSA object can be created from a PKCS#12 key store by calling EncryptionUtils.LoadDecryptionKey the following way:

var decryptionKey = EncryptionUtils.LoadDecryptionKey(
                                    "<insert PKCS#12 key file path>", 
                                    "<insert key alias>", 
                                    "<insert key password>");

From an Unencrypted Key File

A System.Security.Cryptography.RSA object can be created from an unencrypted key file by calling EncryptionUtils.LoadDecryptionKey the following way:

var 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 Payload Encryption and Decryption

Introduction

This library supports two types of encryption/decryption, both of which support field level and entire payload encryption: JWE encryption and what the library refers to as Field Level Encryption (Mastercard encryption), a scheme used by many services hosted on Mastercard Developers before the library added support for JWE.

JWE Encryption and Decryption

• Introduction

This library uses JWE compact serialization for the encryption of sensitive data. The core methods responsible for payload encryption and decryption are EncryptPayload and DecryptPayload in the JweEncryption class.

  • EncryptPayload usage:
var encryptedRequestPayload = JweEncryption.EncryptPayload(requestPayload, config);
  • DecryptPayload usage:
var responsePayload = JweEncryption.DecryptPayload(encryptedResponsePayload, config);
• Configuring the JWE Encryption

Use the JweConfigBuilder to create JweConfig instances. Example:

var config = JweConfigBuilder.AJweEncryptionConfig()
    .WithEncryptionCertificate(encryptionCertificate)
    .WithDecryptionKey(decryptionKey)
    .WithEncryptionPath("$.path.to.foo", "$.path.to.encryptedFoo")
    .WithDecryptionPath("$.path.to.encryptedFoo", "$.path.to.foo")
    .WithEncryptedValueFieldName("encryptedValue")
    .Build();
• Performing JWE Encryption

Call JweEncryption.EncryptPayload with a JSON request payload and a JweConfig instance.

Example using the configuration above:

const string payload = "{" +
    "    \"path\": {" +
    "        \"to\": {" +
    "            \"foo\": {" +
    "                \"sensitiveField1\": \"sensitiveValue1\"," +
    "                \"sensitiveField2\": \"sensitiveValue2\"" +
    "            }" +
    "        }" +
    "    }" +
    "}";
var encryptedPayload = JweEncryption.EncryptPayload(payload, config);
Console.WriteLine(JObject.Parse(encryptedPayload));

Output:

{
    "path": {
        "to": {
            "encryptedFoo": {
                "encryptedValue": "eyJraWQiOiI3NjFiMDAzYzFlYWRlM….Y+oPYKZEMTKyYcSIVEgtQw"
            }
        }
    }
}
• Performing JWE Decryption

Call JweEncryption.DecryptPayload with a JSON response payload and a JweConfig instance.

Example using the configuration above:

const string encryptedPayload = "{" +
    "    \"path\": {" +
    "        \"to\": {" +
    "            \"encryptedFoo\": {" +
    "                \"encryptedValue\": \"eyJraWQiOiI3NjFiMDAzYzFlYWRlM….Y+oPYKZEMTKyYcSIVEgtQw\"" +
    "            }" +
    "        }" +
    "    }" +
    "}";
var payload = JweEncryption.DecryptPayload(encryptedPayload, config);
Console.WriteLine(JObject.Parse(payload));

Output:

{
    "path": {
        "to": {
            "foo": {
                "sensitiveField1": "sensitiveValue1",
                "sensitiveField2": "sensitiveValue2"
            }
        }
    }
}
• Encrypting Entire Payloads

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

var config = JweConfigBuilder.AJweEncryptionConfig()
    .WithEncryptionCertificate(encryptionCertificate)
    .WithEncryptionPath("$", "$")
    // …
    .Build();

Example:

const string payload = "{" +
    "    \"sensitiveField1\": \"sensitiveValue1\"," +
    "    \"sensitiveField2\": \"sensitiveValue2\"" +
    "}";
var encryptedPayload = JweEncryption.EncryptPayload(payload, config);
Console.WriteLine(JObject.Parse(encryptedPayload));

Output:

{
    "encryptedValue": "eyJraWQiOiI3NjFiMDAzYzFlYWRlM….Y+oPYKZEMTKyYcSIVEgtQw"
}
• Decrypting Entire Payloads

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

var config = JweConfigBuilder.AJweEncryptionConfig()
    .WithDecryptionKey(decryptionKey)
    .WithDecryptionPath("$", "$")
    // …
    .Build();

Example:

const string encryptedPayload = "{" +
    "  \"encryptedValue\": \"eyJraWQiOiI3NjFiMDAzYzFlYWRlM….Y+oPYKZEMTKyYcSIVEgtQw\"" +
    "}";
var payload = JweEncryption.DecryptPayload(encryptedPayload, config);
Console.WriteLine(JObject.Parse(payload));

Output:

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

Mastercard Encryption and Decryption

• Introduction

The core methods responsible for payload encryption and decryption are EncryptPayload and DecryptPayload in the FieldLevelEncryption class.

  • EncryptPayload usage:
var encryptedRequestPayload = FieldLevelEncryption.EncryptPayload(requestPayload, config);
  • DecryptPayload usage:
var responsePayload = FieldLevelEncryption.DecryptPayload(encryptedResponsePayload, config);
• Configuring the Mastercard Encryption

Use the FieldLevelEncryptionConfigBuilder to create FieldLevelEncryptionConfig instances. Example:

var 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")
    .WithValueEncoding(FieldValueEncoding.Hex)
    .Build();

See also:

• Performing Mastercard Encryption

Call FieldLevelEncryption.EncryptPayload with a JSON request payload and a FieldLevelEncryptionConfig instance.

Example using the configuration above:

const string payload = "{" +
    "    \"path\": {" +
    "        \"to\": {" +
    "            \"foo\": {" +
    "                \"sensitiveField1\": \"sensitiveValue1\"," +
    "                \"sensitiveField2\": \"sensitiveValue2\"" +
    "            }" +
    "        }" +
    "    }" +
    "}";
var encryptedPayload = FieldLevelEncryption.EncryptPayload(payload, config);
Console.WriteLine(JObject.Parse(encryptedPayload));

Output:

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

Call FieldLevelEncryption.DecryptPayload with a JSON response payload and a FieldLevelEncryptionConfig instance.

Example using the configuration above:

const string encryptedPayload = "{" +
    "    \"path\": {" +
    "        \"to\": {" +
    "            \"encryptedFoo\": {" +
    "                \"iv\": \"e5d313c056c411170bf07ac82ede78c9\"," +
    "                \"encryptedKey\": \"e3a56746c0f9109d18b3a2652b76…f16d8afeff36b2479652f5c24ae7bd\"," +
    "                \"encryptedValue\": \"809a09d78257af5379df0c454dcdf…353ed59fe72fd4a7735c69da4080e74f\"" +
    "            }" +
    "        }" +
    "    }" +
    "}";
var payload = FieldLevelEncryption.DecryptPayload(encryptedPayload, config);
Console.WriteLine(JObject.Parse(payload));

Output:

{
    "path": {
        "to": {
            "foo": {
                "sensitiveField1": "sensitiveValue1",
                "sensitiveField2": "sensitiveValue2"
            }
        }
    }
}
• Encrypting Entire Payloads

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

var config = FieldLevelEncryptionConfigBuilder.AFieldLevelEncryptionConfig()
    .WithEncryptionCertificate(encryptionCertificate)
    .WithEncryptionPath("$", "$")
    // …
    .Build();

Example:

const string payload = "{" +
    "    \"sensitiveField1\": \"sensitiveValue1\"," +
    "    \"sensitiveField2\": \"sensitiveValue2\"" +
    "}";
var encryptedPayload = FieldLevelEncryption.EncryptPayload(payload, config);
Console.WriteLine(JObject.Parse(encryptedPayload));

Output:

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

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

var config = FieldLevelEncryptionConfigBuilder.AFieldLevelEncryptionConfig()
    .WithDecryptionKey(decryptionKey)
    .WithDecryptionPath("$", "$")
    // …
    .Build();

Example:

const string encryptedPayload = "{" +
    "  \"iv\": \"1b9396c98ab2bfd195de661d70905a45\"," +
    "  \"encryptedKey\": \"7d5112fa08e554e3dbc455d0628…52e826dd10311cf0d63bbfb231a1a63ecc13\"," +
    "  \"encryptedValue\": \"e5e9340f4d2618d27f8955828c86…379b13901a3b1e2efed616b6750a90fd379515\"" +
    "}";
var payload = FieldLevelEncryption.DecryptPayload(encryptedPayload, config);
Console.WriteLine(JObject.Parse(payload));

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:

var config = FieldLevelEncryptionConfigBuilder.AFieldLevelEncryptionConfig()
    .WithEncryptionCertificate(encryptionCertificate)
    .WithDecryptionKey(decryptionKey)
    .WithEncryptionPath("$", "$")
    .WithDecryptionPath("$", "$")
    .WithOaepPaddingDigestAlgorithm("SHA-256")
    .WithEncryptedValueFieldName("data")
    .WithIvHeaderName("x-iv")
    .WithEncryptedKeyHeaderName("x-encrypted-key")
    // …
    .WithValueEncoding(FieldValueEncoding.Hex)
    .Build();

See also:

Encrypting Using HTTP Headers

Encryption can be performed using the following steps:

  1. Generate parameters by calling FieldLevelEncryptionParams.Generate:
var parameters = FieldLevelEncryptionParams.Generate(config);
  1. Update the request headers:
request.SetHeader(config.IvHeaderName, parameters.IvValue);
request.SetHeader(config.EncryptedKeyHeaderName, parameters.EncryptedKeyValue);
// …
  1. Call EncryptPayload with params:
FieldLevelEncryption.EncryptPayload(payload, config, parameters);

Example using the configuration above:

const string payload = "{" +
    "    \"sensitiveField1\": \"sensitiveValue1\"," +
    "    \"sensitiveField2\": \"sensitiveValue2\"" +
    "}";
var encryptedPayload = FieldLevelEncryption.EncryptPayload(payload, config, parameters);
Console.WriteLine(JObject.Parse(encryptedPayload));

Output:

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

Decryption can be performed using the following steps:

  1. Read the response headers:
var ivValue = response.GetHeader(config.IvHeaderName);
var encryptedKeyValue = response.GetHeader(config.EncryptedKeyHeaderName);
// …
  1. Create a FieldLevelEncryptionParams instance:
var parameters = new FieldLevelEncryptionParams(config, ivValue, encryptedKeyValue,);
  1. Call DecryptPayload with params:
FieldLevelEncryption.DecryptPayload(encryptedPayload, config, parameters);

Example using the configuration above:

const string encryptedPayload = "{" +
    "  \"data\": \"53b5f07ee46403af2e92abab900853…d560a0a08a1ed142099e3f4c84fe5e5\"" +
    "}";
var payload = FieldLevelEncryption.DecryptPayload(encryptedPayload, config, parameters);
Console.WriteLine(JObject.Parse(payload));

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:

csharp-netcore

OpenAPI Generator

Client libraries can be generated using the following command:

openapi-generator-cli generate -i openapi-spec.yaml -g csharp-netcore -c config.json -o out

config.json:

{ "targetFramework": "netstandard2.1" }

See also:

Usage of the RestSharpEncryptionInterceptor

RestSharpEncryptionInterceptor is located in the ClientEncryption.RestSharpV2 package.

Usage
  1. Create a new file (for instance, MastercardApiClient.cs) extending the definition of the generated ApiClient class:
partial class ApiClient
{
    private readonly Uri _basePath;
    private readonly RestSharpSigner _signer;
    private readonly RestSharpEncryptionInterceptor _encryptionInterceptor;

    /// <summary>
    /// Construct an ApiClient which will automatically:
    /// - Sign requests
    /// - Encrypt/decrypt requests and responses
    /// </summary>
    public ApiClient(RSA signingKey, string basePath, string consumerKey, EncryptionConfig config)
    {
        _baseUrl = basePath;
        _basePath = new Uri(basePath);
        _signer = new RestSharpSigner(consumerKey, signingKey);
        _encryptionInterceptor = RestSharpEncryptionInterceptor.From(config);
    }

    partial void InterceptRequest(RestRequest request)
    {
        _encryptionInterceptor.InterceptRequest(request);
        _signer.Sign(_basePath, request);
    }
}
  1. Configure your ApiClient instance the following way:
var client = new ApiClient(SigningKey, BasePath, ConsumerKey, config);
var serviceApi = new ServiceApi() { Client = client };
// …

csharp (deprecated)

OpenAPI Generator

Client libraries can be generated using the following command:

openapi-generator-cli generate -i openapi-spec.yaml -g csharp -c config.json -o out

config.json:

{ "targetFramework": "netstandard2.1" }

⚠️ v5.0 was used for targetFramework in OpenAPI Generator versions prior 5.0.0.

See also:

Usage of the RestSharpFieldLevelEncryptionInterceptor

RestSharpFieldLevelEncryptionInterceptor is located in the ClientEncryption.RestSharp package.

Usage:
  1. Create a new file (for instance, MastercardApiClient.cs) extending the definition of the generated ApiClient class:
partial class ApiClient
{
    public RestSharpFieldLevelEncryptionInterceptor EncryptionInterceptor { private get; set; }
    partial void InterceptRequest(RestRequest request) => EncryptionInterceptor.InterceptRequest(request);
    partial void InterceptResponse(RestRequest request, RestResponse response) => EncryptionInterceptor.InterceptResponse(response);
}
  1. Configure your ApiClient instance the following way:
var config = Configuration.Default;
config.BasePath = "https://sandbox.api.mastercard.com";
config.ApiClient.RestClient.Authenticator = new RestSharpOAuth1Authenticator(ConsumerKey, signingKey, new Uri(config.BasePath));
var encryptionConfig = FieldLevelEncryptionConfigBuilder
    .AFieldLevelEncryptionConfig()
    // …
    .Build();
config.ApiClient.EncryptionInterceptor = new RestSharpFieldLevelEncryptionInterceptor(encryptionConfig);
var serviceApi = new ServiceApi(config);
// …