Skip to content

vishakhajain102133/client-encryption-csharp

 
 

Repository files navigation

client-encryption-csharp

Table of Contents

Overview

Library for Mastercard API compliant payload encryption/decryption.

Compatibility

.NET

This library requires a .NET Framework implementing .NET Standard 1.3.

Strong Naming

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

References

Encryption of sensitive data

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
Install-Package Mastercard.Developer.ClientEncryption.RestSharp

.NET CLI

dotnet add package Mastercard.Developer.ClientEncryption.Core
dotnet add package Mastercard.Developer.ClientEncryption.RestSharp

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 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:
var encryptedRequestPayload = FieldLevelEncryption.EncryptPayload(requestPayload, config);
  • DecryptPayload usage:
var responsePayload = FieldLevelEncryption.DecryptPayload(encryptedResponsePayload, config);

Configuring the Field Level 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 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 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 (targetFramework v5.0)

OpenAPI Generator

Client libraries can be generated using the following command:

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

config.json:

{ "targetFramework": "v5.0" }

See also:

Usage of the RestSharpFieldLevelEncryptionInterceptor

RestSharpFieldLevelEncryptionInterceptor is located in the Mastercard.Developer.ClientEncryption.RestSharp package.

Usage:

  1. Create a new file (for instance, ApiClientWithEncryption.cs) extending the definition of the generated ApiClient class:
partial class ApiClient
{
    public RestSharpFieldLevelEncryptionInterceptor EncryptionInterceptor { private get; set; }
    partial void InterceptRequest(IRestRequest request) => EncryptionInterceptor.InterceptRequest(request);
    partial void InterceptResponse(IRestRequest request, IRestResponse 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 fieldLevelEncryptionConfig = FieldLevelEncryptionConfigBuilder
    .AFieldLevelEncryptionConfig()
    // ...
    .Build();
config.ApiClient.EncryptionInterceptor = new RestSharpFieldLevelEncryptionInterceptor(fieldLevelEncryptionConfig);
var serviceApi = new ServiceApi(config);
// ...