---
# System prepended metadata

title: MTLS API implementation methods
tags: [mtls]

---

# MTLS API implementation methods
## Overview

This document has been prepared to explain how to implement MTLS API and how to operate the MTLS process.

## Table of Contents
1. [Introduction](#Introduction)
2. [Creating Certificate](#Creation-Certificate)
3. [Transaction](#Transaction)
5. [Changelog](#Changelog)
6. [Links](#Links)

## Introduction
MTLS implementation has two independent processes. The first is certificate creation. SubFlow is used to create certificates.
The second one is used to sign your transactions that have financial consequences with your certificate.

## Creation Certificate

Below you can see the certificate creation request and process flow on subflow.

![image](https://hackmd.io/_uploads/HJL9gt8QC.png)

**Workflow Steps**
	**1.	Certificate Management Start**
	•	The workflow begins with either a trigger or an event to manage certificates (represented by two different start points).
	**2.	Set URLs**
	•	Initial task to set URLs with default values, preparing the necessary endpoints for subsequent operations.
	**3.	Amorphie HTTP Worker (Get By DeviceId)**
	•	This task involves fetching details by DeviceId using the amorphie HTTP worker, ensuring the device is recognized and its details are retrieved.
	**4.	Decision Point: Device Found**
	•	A decision point checks if the device details were found:
	•	If found, proceed to the end of the workflow.
	•	If not found, proceed to create a new certificate.
	**5.	Amorphie HTTP Worker (Create)**
	•	If the device is not found, this task creates a new certificate using the amorphie HTTP worker. This step ensures that a new, valid certificate is generated for the device.
	**6.	Decision Point: Certificate Created**
	•	Another decision point checks if the certificate was successfully created:
	•	If successful, proceed to the end of the workflow.
	•	If not, handle the error by transitioning to the error management state.

**Error Handling**
	•	Amorphie HTTP Worker (Error)
	•	If any errors occur at different stages, an amorphie HTTP worker manages the error.
	•	Error End
	•	The error handling process concludes with an error end state, allowing for logging, notifications, or corrective actions.

## Transaction
You can find below how to use MTSL API to sign user's financial transactions. [Click](https://hackmd.io/nTIZw0UeStuoO-M-lVXfXQ?view#6-Sequence-Diagram) to see the process flow.

**Process steps**
- The data to be signed is transmitted to the MTLS Service.
- MTLS Service adds nonce information to the data and returns the data by encrypting it with publicKey.
- Client decrypts the encrypted data with its privateKey.
- User approval process is implemented.
- A request is made to the MTLS Service by signing the data with pivateKey.
- MTLS Service verifies the signed data with publicKey and returns the result.

> RSA was preferred as the encryption algorithm. The key length is; It is 4096. [Click](https://hackmd.io/X6LqhqvlScmc-dWZZ8BhaQ) for more details.

**Data Decrypt**
You can find sample code on how to decrypt data with Private Key.
```csharp
public string Decrypt(string privatePhase, string payloadData)
{
    using (RSA rsa = RSA.Create(4096))
    {
        byte[] dataBytes = Convert.FromBase64String(payloadData);
        rsa.ImportParameters(ConvertPemToRsaParameters(privatePhase));

        return Convert.ToBase64String(rsa.Decrypt(dataBytes, RSAEncryptionPadding.Pkcs1));
    }
}
    
// PEM formatındaki özel anahtarı RSAParameters formatına çevirme
static RSAParameters ConvertPemToRsaParameters(string privateKeyString)
{
    // PEM formatını temizle
    string header = "-----BEGIN RSA PRIVATE KEY-----";
    string footer = "-----END RSA PRIVATE KEY-----";
    string base64 = privateKeyString.Replace(header, "").Replace(footer, "").Replace("\n", "").Replace("\r", "");

    // Base64 string'i byte dizisine çevir
    byte[] keyBytes = Convert.FromBase64String(base64);

    using (var rsa = RSA.Create(4096))
    {
        rsa.ImportRSAPrivateKey(keyBytes, out _);
        return rsa.ExportParameters(true);
    }
} 
```

**Data Sign**
You can find sample code on how to sign data with Private Key.
```csharp
public string Signed(string privatePhase, string payloadData)
{
    using (RSA rsa = RSA.Create(4096))
    {
        byte[] dataBytes = Convert.FromBase64String(payloadData);
        rsa.ImportParameters(ConvertPemToRsaParameters(privatePhase));
        return Convert.ToBase64String(rsa.SignData(dataBytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1));
    }
}

// PEM formatındaki özel anahtarı RSAParameters formatına çevirme
static RSAParameters ConvertPemToRsaParameters(string privateKeyString)
{
    // PEM formatını temizle
    string header = "-----BEGIN RSA PRIVATE KEY-----";
    string footer = "-----END RSA PRIVATE KEY-----";
    string base64 = privateKeyString.Replace(header, "").Replace(footer, "").Replace("\n", "").Replace("\r", "");

    // Base64 string'i byte dizisine çevir
    byte[] keyBytes = Convert.FromBase64String(base64);

    using (var rsa = RSA.Create(4096))
    {
        rsa.ImportRSAPrivateKey(keyBytes, out _);
        return rsa.ExportParameters(true);
    }
}   
```

### Sub Transaction Flow
![image](https://hackmd.io/_uploads/r1Q4V8PVR.png)

**Workflow Steps**
	**1.	Transaction Management Start**
	•	The workflow is initiated by either a trigger or an event (represented by two different start points).
	**2.	Set URLs**
	•	The initial task is setting the URLs with default values. This step prepares the necessary endpoints for subsequent operations.
	**3.	Amorphie HTTP Worker (Check Certificate)**
	•	This task involves checking the certificate using the amorphie HTTP worker. It ensures that the certificate is valid and trusted.
	**4.	Decision Point: Certificate Check**
	•	A decision point follows the certificate check. If the certificate is valid (success), the workflow proceeds to encryption. If not, it loops back for error handling.
	**5.	Amorphie HTTP Worker (Encrypt)**
	•	Upon successful certificate validation, the next task is to encrypt the data. This ensures that the data is secure before further processing.
	**6.	Amorphie Workflow Set State (Return Encrypt)**
	•	The encrypted data is returned, and the workflow state is updated accordingly.
	**7.	Transaction Management Send Sign**
	•	The encrypted data is sent for signing. This step is crucial for validating the transaction data’s integrity and authenticity.
	**8.	Amorphie HTTP Worker (Verify)**
	•	The verification of the signed data is performed by the amorphie HTTP worker. It ensures that the data has not been tampered with and is authentic.
	**9.	Decision Point: Verification**
	•	Another decision point evaluates the verification results. If the data is verified, the workflow ends successfully. If not, it transitions to error handling.

**Error Handling**
	•	Amorphie Workflow Set State
	•	If any errors occur at different stages, the workflow state is set to indicate an error.
	•	Error State
	•	The workflow enters an error state to manage and handle the issues encountered.
	•	Error End Sub
	•	The error handling process concludes, allowing for logging, notifications, or corrective actions.

## Changelog
**v1.0.0 - 05/2024 - (DRAFT)**
* First release

## Links
* [MTLS Api Guide](https://hackmd.io/c_WrUdbSRKSEZSe6LJsYKA)
* [Client Certificate Creation for Signing and mTLS](https://hackmd.io/X6LqhqvlScmc-dWZZ8BhaQ)
* [Methods to implement MTLS](https://hackmd.io/YXHUE59ISCqpHRvW8VdN1A)
* [Secure Transaction Signing with Mobile App and Secure Element](https://hackmd.io/nTIZw0UeStuoO-M-lVXfXQ)