Coder Social home page Coder Social logo

diffblue-benchmarks / client-encryption-java Goto Github PK

View Code? Open in Web Editor NEW

This project forked from mastercard/client-encryption-java

1.0 3.0 0.0 212 KB

Library for Mastercard API compliant payload encryption/decryption.

License: MIT License

Java 100.00%

client-encryption-java's Introduction

client-encryption-java

Table of Contents

Overview

Library for Mastercard API compliant payload encryption/decryption.

Compatibility

Java 7+

References

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

Maven

<dependency>
    <groupId>com.mastercard.developer</groupId>
    <artifactId>client-encryption</artifactId>
    <version>${client-encryption-version}</version>
</dependency>

Gradle

dependencies {
    implementation "com.mastercard.developer:client-encryption:$clientEncryptionVersion"
}	

Other Dependency Managers

See: https://search.maven.org/artifact/com.mastercard.developer/client-encryption

Selecting a JSON Engine

This library requires one of the following dependencies to be added to your classpath:

You can either let the library choose for you, or force the one to be used by calling withJsonEngine on the FieldLevelEncryption class. Example:

FieldLevelEncryption.withJsonEngine(new JettisonJsonEngine());

Available engine classes:

  • GsonJsonEngine
  • JacksonJsonEngine
  • JettisonJsonEngine
  • JsonOrgJsonEngine
  • JsonSmartJsonEngine

Loading the Encryption Certificate

A Certificate object can be created from a file by calling the EncryptionUtils.loadEncryptionCertificate method:

Certificate encryptionCertificate = EncryptionUtils.loadEncryptionCertificate("<insert certificate file path>");

Supported certificate formats: PEM, DER.

Loading the Decryption Key

From a PKCS#12 File

A PrivateKey object can be created from a PKCS#12 file by calling the EncryptionUtils.loadDecryptionKey method:

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

From an Unencrypted Key File

A PrivateKey object can be created from an unencrypted key file by calling the EncryptionUtils.loadDecryptionKey method:

PrivateKey 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 methods that do all the heavy lifting are encryptPayload and decryptPayload in the FieldLevelEncryption class.

  • encryptPayload usage:
String encryptedRequestPayload = FieldLevelEncryption.encryptPayload(requestPayload, config);
  • decryptPayload usage:
String responsePayload = FieldLevelEncryption.decryptPayload(encryptedResponsePayload, config);

Configuring the Field Level Encryption

Use the FieldLevelEncryptionConfigBuilder to create FieldLevelEncryptionConfig instances. Example:

FieldLevelEncryptionConfig 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:

String payload = "{" +
        "    \"path\": {" +
        "        \"to\": {" +
        "            \"foo\": {" +
        "                \"sensitiveField1\": \"sensitiveValue1\"," +
        "                \"sensitiveField2\": \"sensitiveValue2\"" +
        "            }" +
        "        }" +
        "    }" +
        "}";
String encryptedPayload = FieldLevelEncryption.encryptPayload(payload, config);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(new JsonParser().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:

String encryptedPayload = "{" +
        "    \"path\": {" +
        "        \"to\": {" +
        "            \"encryptedFoo\": {" +
        "                \"iv\": \"e5d313c056c411170bf07ac82ede78c9\"," +
        "                \"encryptedKey\": \"e3a56746c0f9109d18b3a2652b76(...)f16d8afeff36b2479652f5c24ae7bd\"," +
        "                \"encryptedValue\": \"809a09d78257af5379df0c454dcdf(...)353ed59fe72fd4a7735c69da4080e74f\"" +
        "            }" +
        "        }" +
        "    }" +
        "}";
String payload = FieldLevelEncryption.decryptPayload(encryptedPayload, config);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(new JsonParser().parse(payload)));

Output:

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

Encrypting Entire Payloads

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

FieldLevelEncryptionConfig config = FieldLevelEncryptionConfigBuilder.aFieldLevelEncryptionConfig()
        .withEncryptionCertificate(encryptionCertificate)
        .withEncryptionPath("$", "$")
        // ...
        .build();

Example:

String payload = "{" +
        "    \"sensitiveField1\": \"sensitiveValue1\"," +
        "    \"sensitiveField2\": \"sensitiveValue2\"" +
        "}";
String encryptedPayload = FieldLevelEncryption.encryptPayload(payload, config);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(new JsonParser().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:

FieldLevelEncryptionConfig config = FieldLevelEncryptionConfigBuilder.aFieldLevelEncryptionConfig()
        .withDecryptionKey(decryptionKey)
        .withDecryptionPath("$", "$")
        // ...
        .build();

Example:

String encryptedPayload = "{" +
        "  \"iv\": \"1b9396c98ab2bfd195de661d70905a45\"," +
        "  \"encryptedKey\": \"7d5112fa08e554e3dbc455d0628(...)52e826dd10311cf0d63bbfb231a1a63ecc13\"," +
        "  \"encryptedValue\": \"e5e9340f4d2618d27f8955828c86(...)379b13901a3b1e2efed616b6750a90fd379515\"" +
        "}";
String payload = FieldLevelEncryption.decryptPayload(encryptedPayload, config);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(new JsonParser().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:

FieldLevelEncryptionConfig 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:
FieldLevelEncryptionParams 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:

String payload = "{" +
        "    \"sensitiveField1\": \"sensitiveValue1\"," +
        "    \"sensitiveField2\": \"sensitiveValue2\"" +
        "}";
String encryptedPayload = FieldLevelEncryption.encryptPayload(payload, config, params);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(new JsonParser().parse(encryptedPayload)));

Output:

{
    "data": "53b5f07ee46403af2e92abab900853(...)d560a0a08a1ed142099e3f4c84fe5e5"
}
Decrypting Using HTTP Headers

Decryption can be performed using the following steps:

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

Example using the configuration above:

String encryptedPayload = "{" +
        "  \"data\": \"53b5f07ee46403af2e92abab900853(...)d560a0a08a1ed142099e3f4c84fe5e5\"" +
        "}";
String payload = FieldLevelEncryption.decryptPayload(encryptedPayload, config, params);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(new JsonParser().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.

The com.mastercard.developer.interceptors package will provide 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.

Library options currently supported for the java generator:

See also:

okhttp-gson

OpenAPI Generator Plugin Configuration
<configuration>
    <inputSpec>${project.basedir}/src/main/resources/openapi-spec.yaml</inputSpec>
    <generatorName>java</generatorName>
    <library>okhttp-gson</library>
    <!-- ... -->
</configuration>
Usage of the OkHttp2FieldLevelEncryptionInterceptor
ApiClient client = new ApiClient();
client.setBasePath("https://sandbox.api.mastercard.com");
List<Interceptor> interceptors = client.getHttpClient().interceptors();
interceptors.add(new OkHttp2FieldLevelEncryptionInterceptor(config));
interceptors.add(new OkHttp2OAuth1Interceptor(consumerKey, signingKey));
ServiceApi serviceApi = new ServiceApi(client);
// ...

feign

OpenAPI Generator Plugin Configuration
<configuration>
    <inputSpec>${project.basedir}/src/main/resources/openapi-spec.yaml</inputSpec>
    <generatorName>java</generatorName>
    <library>feign</library>
    <!-- ... -->
</configuration>
Usage of OpenFeignFieldLevelEncryptionEncoder and OpenFeignFieldLevelEncryptionDecoder
ApiClient client = new ApiClient();
ObjectMapper objectMapper = client.getObjectMapper();
client.setBasePath("https://sandbox.api.mastercard.com");
Feign.Builder feignBuilder = client.getFeignBuilder();
ArrayList<RequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new OpenFeignOAuth1Interceptor(consumerKey, signingKey, client.getBasePath()));
feignBuilder.requestInterceptors(interceptors);
feignBuilder.encoder(new OpenFeignFieldLevelEncryptionEncoder(config, new FormEncoder(new JacksonEncoder(objectMapper))));
feignBuilder.decoder(new OpenFeignFieldLevelEncryptionDecoder(config, new JacksonDecoder(objectMapper)));
ServiceApi serviceApi = client.buildClient(ServiceApi.class);
// ...

retrofit

OpenAPI Generator Plugin Configuration
<configuration>
    <inputSpec>${project.basedir}/src/main/resources/openapi-spec.yaml</inputSpec>
    <generatorName>java</generatorName>
    <library>retrofit</library>
    <!-- ... -->
</configuration>
Usage of the OkHttp2FieldLevelEncryptionInterceptor
ApiClient client = new ApiClient();
RestAdapter.Builder adapterBuilder = client.getAdapterBuilder();
adapterBuilder.setEndpoint("https://sandbox.api.mastercard.com"); 
List<Interceptor> interceptors = client.getOkClient().interceptors();
interceptors.add(new OkHttp2FieldLevelEncryptionInterceptor(config));
interceptors.add(new OkHttp2OAuth1Interceptor(consumerKey, signingKey));
ServiceApi serviceApi = client.createService(ServiceApi.class);
// ...

retrofit2

OpenAPI Generator Plugin Configuration
<configuration>
    <inputSpec>${project.basedir}/src/main/resources/openapi-spec.yaml</inputSpec>
    <generatorName>java</generatorName>
    <library>retrofit2</library>
    <!-- ... -->
</configuration>
Usage of the OkHttpFieldLevelEncryptionInterceptor
ApiClient client = new ApiClient();
Retrofit.Builder adapterBuilder = client.getAdapterBuilder();
adapterBuilder.baseUrl("https://sandbox.api.mastercard.com"); 
OkHttpClient.Builder okBuilder = client.getOkBuilder();
okBuilder.addInterceptor(new OkHttpFieldLevelEncryptionInterceptor(config));
okBuilder.addInterceptor(new OkHttpOAuth1Interceptor(consumerKey, signingKey));
ServiceApi serviceApi = client.createService(ServiceApi.class);
// ...

google-api-client

OpenAPI Generator Plugin Configuration
<configuration>
    <inputSpec>${project.basedir}/src/main/resources/openapi-spec.yaml</inputSpec>
    <generatorName>java</generatorName>
    <library>google-api-client</library>
    <!-- ... -->
</configuration>
Usage of HttpExecuteFieldLevelEncryptionInterceptor and HttpExecuteInterceptorChain
HttpRequestInitializer initializer = new HttpRequestInitializer() {
    @Override
    public void initialize(HttpRequest request) {
        HttpExecuteOAuth1Interceptor authenticationInterceptor = new HttpExecuteOAuth1Interceptor(consumerKey, signingKey);
        HttpExecuteFieldLevelEncryptionInterceptor encryptionInterceptor = new HttpExecuteFieldLevelEncryptionInterceptor(config);
        request.setInterceptor(new HttpExecuteInterceptorChain(Arrays.asList(encryptionInterceptor, authenticationInterceptor)));
        request.setResponseInterceptor(encryptionInterceptor);
    }
};
ApiClient client = new ApiClient("https://sandbox.api.mastercard.com", null, initializer, null);
ServiceApi serviceApi = client.serviceApi();
// ...

client-encryption-java's People

Contributors

jaaufauvre avatar

Stargazers

 avatar

Watchers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.