# Encryptor

## Create a channel for a secret and upload an encryption <a href="#op-upload-encryption" id="op-upload-encryption"></a>

`POST /encryptions`

### Description

Secrets are secured within a channel of a PAD instance. To create an encryption `Channel`, you must upload an `Encryption` object to the server. At any time, the decryptor can retrieve the `Encryption` object using the hash of the token value, which acts as an identifier of the channel. The decryptor may choose to retrieve the `Encryption` object immediately in order to independently store the encrypted values, or may only do so when a decryption is requested. In any case, no decryption can occur unless the decryptor has posted a data request and sufficient trustees and validators have responded. Read [the code samples section](https://github.com/sw7group/PAD-Dev-Docs/blob/main/code_samples_enc_dec.md#encrypting) for details and information about how to construct `Encryption` objects.

To facilitate updating the `Encryption` object securely in some use cases (Find-me, for example), you can send a channel key along with this request. This ensures only you who has the private key counterpart of the channel key can change the `Encryption` object in this channel.

### Parameters

| Name         | In   | Type                             | Required | Description                                             |
| ------------ | ---- | -------------------------------- | -------- | ------------------------------------------------------- |
| `encryption` | body | [Encryption](#schema-encryption) | true     | none                                                    |
| `channelKey` | body | string                           | true     | A PEM-encoded (public) verification key for the channel |

**Example**

```json
{
  "encryption": {
    "description": "string",
    "tokenHash": "d033713dd14552c060c55746afdb989cfee8e624ae94a932d79fd25630f728a4",
    "ciphertext": {
      "encryptedMessage": {
        "ciphertext": "base64_encoded_data",
        "iv": "base64_encoded_data"
      },
      "encryptedEphemeralKey": "base64_encoded_data"
    },
    "trusteeShares": {
      "trustee1": {
        "encrypted": "base64_encoded_data",
        "hashed": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
      }
    },
    "validatorShares": {
      "validator1": {
        "encrypted": {
          "encryptedMessage": {
            "ciphertext": "base64_encoded_data",
            "iv": "base64_encoded_data"
          },
          "encryptedEphemeralKey": "base64_encoded_data"
        }
      }
    },
  },
  "channelKey": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE5fYv3lbLtDjR5IxAurWF6TMfhNZB\nPUn2DLapmjLWvZXYjqSrflJx4TemksjRyMDi+CwWP0PkunBB6wUdCDmdWA==\n-----END PUBLIC KEY-----"
}
```

### Responses

| Status | Meaning                                                         | Description                   | Schema                              |
| ------ | --------------------------------------------------------------- | ----------------------------- | ----------------------------------- |
| 200    | [OK](https://tools.ietf.org/html/rfc7231#section-6.3.1)         | Succeeded                     | [ApiResponse](#schema-api-response) |
| 401    | [Unauthorized](https://tools.ietf.org/html/rfc7235#section-3.1) | API key is missing or invalid | [ApiResponse](#schema-api-response) |
| 409    | [Conflict](https://tools.ietf.org/html/rfc7231#section-6.5.8)   | Conflict                      | [ApiResponse](#schema-api-response) |

#### 200 OK

The encryption has been successfully uploaded onto the server.

**Example**

```json
{
  "ok": true,
  "message": "Successfully uploaded encryption",
}
```

#### 401 Unauthorized

API key is missing or incorrect.

**Example**

```json
{
  "ok": false,
  "message": "Unauthorized",
}
```

#### 409 Conflict

A channel with the same token already exists. The client should use another token or [update the encryption](#op-update-encryption) on the channel.

**Example**

```json
{
  "ok": false,
  "message": "The encryption with token hash ${tokenHash} already exists. Update it with PUT request or renew the token.",
}
```

## Get encryption status <a href="#op-get-encryption-status" id="op-get-encryption-status"></a>

`GET /encryptions/{token-hash}/status`

### Description

This retrieves the status of an `encryption`, namely whether or not the data has been requested by the decryptor. If a request has been made, then this status also gives which trustees and validators have responded to the data request. This information is retrieved and provided by the PAD server. To eliminate the need to trust the PAD service, this data should be checked for consistency with trustee attestations of the ledger state.

### Parameters

| Name         | In   | Type                     | Required | Description                            |
| ------------ | ---- | ------------------------ | -------- | -------------------------------------- |
| `token-hash` | path | [Sha256](#schema-sha256) | true     | Hash value of the token in hexadecimal |

#### Example

`GET /encryptions/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855/status`

### Responses

| Status | Meaning                                                         | Description                                                   | Schema                              |
| ------ | --------------------------------------------------------------- | ------------------------------------------------------------- | ----------------------------------- |
| 200    | [OK](https://tools.ietf.org/html/rfc7231#section-6.3.1)         | Succeeded                                                     | Inline                              |
| 401    | [Unauthorized](https://tools.ietf.org/html/rfc7235#section-3.1) | API key is missing or invalid; Or the client lacks permission | [ApiResponse](#schema-api-response) |

#### 200 OK

Successfully retrieved the status of an `Encryption`.

**Schema**

| Name                    | Type                                       | Required | Restrictions | Description |
| ----------------------- | ------------------------------------------ | -------- | ------------ | ----------- |
| `ok`                    | boolean                                    | true     | none         | none        |
| `encryptionStatus`      | object                                     | true     | none         | none        |
| » `tokenHash`           | [Sha256](#schema-sha256)                   | true     | none         | none        |
| » `requested`           | boolean                                    | true     | none         | none        |
| » `token`               | [Token](#schematoken)                      | false    | none         | none        |
| » `requestTime`         | [DateTime](#schemadatetime)                | false    | none         | none        |
| » `respondedTrustees`   | array<[TrusteeId](#schema-trustee-id)>     | false    | none         | none        |
| » `respondedValidators` | array<[ValidatorId](#schema-validator-id)> | false    | none         | none        |

**Example**

```json
{
  "ok": true,
  "encryptionStatus": {
    "tokenHash": "d033713dd14552c060c55746afdb989cfee8e624ae94a932d79fd25630f728a4",
    "requested": true,
    "token": "0fe5ff17c6ee6efa8ca385587b1e1ac2",
    "requestTime": "2021-05-05T13:53:19.275Z",
    "respondedTrustees": [
      "trustee1"
    ],
    "respondedValidators": [
      "validator1"
    ]
  }
}
```

#### 401 Unauthorized

API key is missing or incorrect.

**Example**

```json
{
  "ok": false,
  "message": "Unauthorized",
}
```

## Update encryption <a href="#op-update-encryption" id="op-update-encryption"></a>

`PUT /encryptions/{token-hash}`

### Description

In some use cases (e.g. Find-me), secrets may be generated as a stream of data and the decryptor can make a request for only the most recent secret. This endpoint allows the encryptor to update the `Encryption` after [establishing an encryption channel](#op-upload-encryption).

To ensure only you can use this endpoint, you must sign the `Encryption` object with the channel private key.

### Parameters

| Name                | In   | Type                                     | Required | Description                                                            |
| ------------------- | ---- | ---------------------------------------- | -------- | ---------------------------------------------------------------------- |
| `token-hash`        | path | [Sha256](#schema-sha256)                 | true     | Hash value of the token                                                |
| `encryptionPayload` | body | string<[Encryption](#schema-encryption)> | true     | The new, stringified encryption object                                 |
| `signature`         | body | [Base64](#schema-base64)                 | true     | The signature with the channel private key against `encryptionPayload` |

#### Example

`PUT /encryptions/d033713dd14552c060c55746afdb989cfee8e624ae94a932d79fd25630f728a4`

```json
{
  "encryptionPayload": "{\"description\":\"string\",\"tokenHash\":\"d033713dd14552c060c55746afdb989cfee8e624ae94a932d79fd25630f728a4\",\"ciphertext\":{\"encryptedMessage\":{\"ciphertext\":\"base64_encoded_data\",\"iv\":\"base64_encoded_data\"},\"encryptedEphemeralKey\":\"base64_encoded_data\"},\"trusteeShares\":{\"trustee1\":{\"encrypted\":\"base64_encoded_data\",\"hashed\":\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\"}},\"validatorShares\":{\"validator1\":{\"encrypted\":{\"encryptedMessage\":{\"ciphertext\":\"base64_encoded_data\",\"iv\":\"base64_encoded_data\"},\"encryptedEphemeralKey\":\"base64_encoded_data\"}}}}",
  "signature": "MEQCIGuYVL9wh/4TawM1bFSB5MmF4FkqJPcppj66xc2+MRdHAiBNEF8w77J6SLq3UtxgIRw5Hl8C2JKVUwaKHLflkoaI0w=="
}
```

### Responses

| Status | Meaning                                                         | Description                                                   | Schema                              |
| ------ | --------------------------------------------------------------- | ------------------------------------------------------------- | ----------------------------------- |
| 200    | [OK](https://tools.ietf.org/html/rfc7231#section-6.3.1)         | Succeeded                                                     | [ApiResponse](#schema-api-response) |
| 400    | Bad Request                                                     | Tokens in path and body are inconsistent                      | [ApiResponse](#schema-api-response) |
| 401    | [Unauthorized](https://tools.ietf.org/html/rfc7235#section-3.1) | API key is missing or invalid; Or the client lacks permission | [ApiResponse](#schema-api-response) |

#### 200 OK

The `Encryption` is successfully updated.

**Example**

```json
{
  "ok": true,
  "message": "Successfully updated encryption"
}
```

#### 400 Bad Request

The request failed because tokens in path and body are inconsistent.

**Example**

```json
{
  "ok": false,
  "message": "Token hashes in path and body must be consistent",
}
```

#### 401 Unauthorized

Api key is missing or incorrect.

**Example**

```json
{
  "ok": false,
  "message": "Unauthorized",
}
```

## Schemas

### TrusteeId <a href="#schema-trustee-id" id="schema-trustee-id"></a>

ID of a trustee. It contains only alphanumerical characters, underscores (\_) and dashes (-). It has length inclusively between 3 and 30.

**Example**

```
my_trustee-1
```

#### Schema

| Type   | Restrictions          |
| ------ | --------------------- |
| string | `[a-zA-Z0-9-_]{3,30}` |

### ValidatorId <a href="#schema-validator-id" id="schema-validator-id"></a>

ID of a validator. It contains only alphanumerical characters, underscores (\_) and dashes (-). It has length inclusively between 3 and 30.

#### Example

```
my_validator-2
```

#### Schema

| Type   | Restrictions          |
| ------ | --------------------- |
| string | `[a-zA-Z0-9-_]{3,30}` |

### Encryption <a href="#schema-encryption" id="schema-encryption"></a>

An `Encryption` is identified by `tokenHash` and the instance in which it lives. It contains the ciphertext encrypted by both the decryptor's key and a fresh symmetric key `k`. It also contains the encrypted shares of `k` for the trustees and validators. For more details, read the [code samples page](https://docs.padprotocol.org/code_samples_enc_dec).

**Example**

```json
{
  "description": "string",
  "tokenHash": "hex_encoded_string",
  "ciphertext": {
    "encryptedMessage": {
      "ciphertext": "base64_encoded_string",
      "iv": "base64_encoded_string",
    },
    "encryptedEphemeralKey": "base64_encoded_string",
  },
  "trusteeShares": {
    "trustee1": {
      "encrypted": "base64_encoded_string",
      "hashed": "hex_encoded_string",
    },
  },
  "validatorShares": {
    "validator1": {
      "encrypted": {
        "encryptedMessage": {
          "ciphertext": "base64_encoded_string",
          "iv": "base64_encoded_string",
        },
        "encryptedEphemeralKey": "base64_encoded_string",
      },
    },
  },
}
```

#### Schema

| Name                   | Type                                              | Required | Description |
| ---------------------- | ------------------------------------------------- | -------- | ----------- |
| `description`          | string                                            | true     | none        |
| `tokenHash`            | [Sha256](#schema-sha256)                          | true     | none        |
| `trusteeShares`        | dict<[TrusteeId](#schema-trustee-id), object>     | true     | none        |
| » **\[`trusteeId`]**   | object                                            | true     | none        |
| »» `encrypted`         | string                                            | true     | none        |
| »» `hashed`            | [Sha256](#schema-sha256)                          | true     | none        |
| `validatorShares`      | dict<[ValidatorId](#schema-validator-id), object> | true     | none        |
| » **\[`validatorId`]** | object                                            | true     | none        |
| »» `encrypted`         | [Ciphertext](#schema-ciphertext)                  | true     | none        |
| `ciphertext`           | [Ciphertext](#schema-ciphertext)                  | true     | none        |

### Sha256 <a href="#schema-sha256" id="schema-sha256"></a>

A Sha256 hash value as a hexidecimal string.

**Example**

```json
"d033713dd14552c060c55746afdb989cfee8e624ae94a932d79fd25630f728a4"
```

#### Schema

| Type   | Restrictions        |
| ------ | ------------------- |
| string | `/[0-9a-fA-F]{64}/` |

### DateTime <a href="#schema-date-time" id="schema-date-time"></a>

A timestamp in ISO 8601 format.

**Example**

```json
"2021-05-05T13:53:19.275Z"
```

#### Schema

| Type   | Restrictions |
| ------ | ------------ |
| string | -            |

### Trustee <a href="#schema-trustee" id="schema-trustee"></a>

An object listing details of a trustee, including its ID, human-readable description/name, its role (`Trustee`) and its public keys.

**Example**

```json
{
  "id": "trustee1",
  "fullName": "Trustee-1",
  "role": "Trustee",
  "encryptionKey": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvAnBzaNLM8/iIxP0Rz88\nQk7mj+TW1U1C2BQAaOAQfRTRrEsNDVPpAZB8LTfs8wZEhok5VzSMA4dPTkQE8Su8\np/eQJthOTCmBq2t8dgx0+uX3IhdwXgmWCh0OQ8NJ94rXA+/rWqjeNXZ4ShFlNDeu\nkv9OGLh4bvSTUHWzDi6M4qxlq8fJ/O+lTvJzf6cb6n7pKpT7/ppdGik/Hi8EcQiY\nSL9lbAkKJpgrfqWNDo7HX/2GffZdd316123stOqrBTZS81Ow/Z/rqiPvzBV1HxEv\nabfIFd1LefWgBfECoXOpvYaBuL4N6fchX9gAis7J66WFDQVZsnJ/J3Bzl0ECRgVp\n8QIDAQAB\n-----END PUBLIC KEY-----\n",
  "verificationKey": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAELZyXL9AOgZrIsWrDkY0ohQuvMsVa\n+3eJSfsV+a1HW0M34lZInCVPgule/a9HqnqpDtXEBclgeeKS1YT7jVjpTg==\n-----END PUBLIC KEY-----",
}
```

#### Schema

| Name              | Type                            | Required | Restrictions              | Description                                                                               |
| ----------------- | ------------------------------- | -------- | ------------------------- | ----------------------------------------------------------------------------------------- |
| `id`              | [TrusteeId](#schema-trustee-id) | true     | `/[0-9a-zA-Z-_]{3,30}/`   | none                                                                                      |
| `fullName`        | string                          | true     | `/Trustee-[0-9a-zA-Z_]+/` | none                                                                                      |
| `role`            | enum                            | true     | none                      | none                                                                                      |
| `encryptionKey`   | string                          | true     | none                      | PEM-encoded (public) encryption key of the trustee. Used by encryptors at encryption time |
| `verificationKey` | string                          | true     | none                      | PEM-encoded (public) verification key of trustee                                          |

#### Enumerated Values

| Property | Value     |
| -------- | --------- |
| role     | `Trustee` |

### Validator <a href="#schema-validator" id="schema-validator"></a>

An object listing details of a validator, including its ID, human-readable description/name, its role (`Validator`) and its public keys.

**Example**

```json
{
  "id": "validator1",
  "fullName": "Validator1",
  "role": "Validator",
  "encryptionKey": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvAnBzaNLM8/iIxP0Rz88\nQk7mj+TW1U1C2BQAaOAQfRTRrEsNDVPpAZB8LTfs8wZEhok5VzSMA4dPTkQE8Su8\np/eQJthOTCmBq2t8dgx0+uX3IhdwXgmWCh0OQ8NJ94rXA+/rWqjeNXZ4ShFlNDeu\nkv9OGLh4bvSTUHWzDi6M4qxlq8fJ/O+lTvJzf6cb6n7pKpT7/ppdGik/Hi8EcQiY\nSL9lbAkKJpgrfqWNDo7HX/2GffZdd316123stOqrBTZS81Ow/Z/rqiPvzBV1HxEv\nabfIFd1LefWgBfECoXOpvYaBuL4N6fchX9gAis7J66WFDQVZsnJ/J3Bzl0ECRgVp\n8QIDAQAB\n-----END PUBLIC KEY-----\n",
  "verificationKey": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAELZyXL9AOgZrIsWrDkY0ohQuvMsVa\n+3eJSfsV+a1HW0M34lZInCVPgule/a9HqnqpDtXEBclgeeKS1YT7jVjpTg==\n-----END PUBLIC KEY-----",
}
```

#### Schema

| Name              | Type                                | Required | Restrictions                | Description                                                                                 |
| ----------------- | ----------------------------------- | -------- | --------------------------- | ------------------------------------------------------------------------------------------- |
| `id`              | [ValidatorId](#schema-validator-id) | true     | -                           | none                                                                                        |
| `fullName`        | string                              | true     | `/Validator-[0-9a-zA-Z_]+/` | none                                                                                        |
| \`role            | enum\`                              | true     | none                        | none                                                                                        |
| `encryptionKey`   | string                              | true     | none                        | PEM-encoded (public) encryption key of the validator. Used by encryptors at encryption time |
| `verificationKey` | string                              | true     | none                        | PEM-encoded (public) verification key of validator                                          |

#### Enumerated Values

| Property | Value       |
| -------- | ----------- |
| role     | `Validator` |

### Base64 <a href="#schema-base64" id="schema-base64"></a>

A base64-encoded binary data.

**Example**

```json
"aGVsbG8gd29ybGQ="
```

#### Schema

| Type   | Restrictions |
| ------ | ------------ |
| string | none         |

### Ciphertext <a href="#schema-ciphertext" id="schema-ciphertext"></a>

A piece of asymmetrically encrypted ciphertext. It is created by first generating a symmetric ephemeral key, encrypt symmetrically the message using the ephemeral key, then encrypt asymmetrically the ephemeral key by an encryption key. All binary data are encoded in base64. For details, read [the code samples](https://docs.padprotocol.org/code_samples_enc_dec).

**Example**

```json
{
  "encryptedMessage": {
    "ciphertext": "base64_encoded_data=",
    "iv": "base64_encoded_data=",
  },
  "encryptedEphemeralKey": "base64_encoded_data=",
}
```

#### Schema

| Name                    | Type                     | Required | Restrictions | Description                                                 |
| ----------------------- | ------------------------ | -------- | ------------ | ----------------------------------------------------------- |
| `encryptedMessage`      | object                   | true     | none         | Cipher of a message encrypted with an ephemeral key         |
| » `ciphertext`          | [Base64](#schema-base64) | true     | none         | none                                                        |
| » `iv`                  | [Base64](#schema-base64) | true     | none         | none                                                        |
| `encryptedEphemeralKey` | [Base64](#schema-base64) | true     | none         | The ephemeral key encrypted by an asymmetric encryption key |

### PadInstanceMetadata <a href="#schema-pad-instance-metadata" id="schema-pad-instance-metadata"></a>

Information about a PAD instance. That includes the instance name, its list of trustees, the trustee threshold, the list of validators and the validator threshold.

**Example**

```json
{
  "padName": "my-pad-1.0",
  "trusteeIds": [
    "trustee1",
    "trustee2",
  ],
  "t": 1,
  "validatorIds": [
    "validator1",
    "validator2",
  ],
  "tPrime": 1,
}
```

#### Schema

| Name           | Type                                       | Required | Restrictions | Description |
| -------------- | ------------------------------------------ | -------- | ------------ | ----------- |
| `padName`      | [PadName](#schema-pad-name)                | true     | none         | none        |
| `trusteeIds`   | array<[TrusteeId](#schema-trustee-id)>     | true     | none         | none        |
| `t`            | integer                                    | true     | none         | none        |
| `validatorIds` | array<[ValidatorId](#schema-validator-id)> | true     | none         | none        |
| `tPrime`       | integer                                    | true     | none         | none        |

### ApiResponse <a href="#schema-api-response" id="schema-api-response"></a>

**Example**

```json
{
  "ok": true,
  "message": "string",
}
```

#### Schema

| Name      | Type    | Required | Description                      |
| --------- | ------- | -------- | -------------------------------- |
| `ok`      | boolean | true     | The request is successful or not |
| `message` | string  | true     | none                             |

### Token <a href="#schema-token" id="schema-token"></a>

A 128-bit random string kept secret between the encryptor and decryptor after encryption stage and before data request stage. It identifies a data request. Its hash value identifies an `encryption`. The decryptor posts it on the ledger at data request stage.

**Example**

```
"0fe5ff17c6ee6efa8ca385587b1e1ac2"
```

#### Schema

| Type   | Restrictions        |
| ------ | ------------------- |
| string | `/[0-9a-fA-Z]{32}/` |

### PadName <a href="#schema-pad-name" id="schema-pad-name"></a>

ID of a PAD instance. Its length must be inclusively between 4 and 30. It should contains only lowercase letters, digits, periods (`.`) or dashes (`-`). It must start with a lowercase letter.

It is seldom used as a request parameter because the API key in the request already identifies a PAD instance.

**Example**

```json
"my-pad-1.0"
```

#### Schema

| Type   | Restrictions              |
| ------ | ------------------------- |
| string | `/[a-z][a-z0-9.-]{3,29}/` |
