# PDF にパスワードを追加する

暗号化アルゴリズムを選択して、開く際にパスワードが必要になるよう PDF を暗号化します。

PDF ドキュメントを開くためのパスワードで暗号化し、パスワードなしでは開けないようにします。これは、ファイルを開くためだけに必要なパスワードを設定するもので、印刷やコピーなどの操作に関する権限フラグを設定する[制限の追加](/docs/api/add-restrictions-to-pdf)とは異なります。コンプライアンス要件に合わせて暗号化アルゴリズムを選択できます。API はステートレスです。ドキュメントはリージョン内で処理され、保存されることはありません。

## エンドポイント

<Endpoint method="POST" path="/v1/add_password" />

すべてのリージョンで利用できます。ルーティングとデータレジデンシーについては、[リージョンとデータレジデンシー](/docs/api/regions-and-data-residency)を参照してください。

| リージョン       | URL                                            |
| -------------- | ---------------------------------------------- |
| グローバル       | `https://api.pdfblocks.com/v1/add_password`    |
| 日本            | `https://jp.api.pdfblocks.com/v1/add_password` |
| 米国            | `https://us.api.pdfblocks.com/v1/add_password` |
| HIPAA 米国      | `https://hipaa.api.pdfblocks.com/v1/add_password` |
| 欧州連合         | `https://eu.api.pdfblocks.com/v1/add_password` |
| 英国            | `https://uk.api.pdfblocks.com/v1/add_password` |
| カナダ           | `https://ca.api.pdfblocks.com/v1/add_password` |
| オーストラリア    | `https://au.api.pdfblocks.com/v1/add_password` |
| インド           | `https://in.api.pdfblocks.com/v1/add_password` |
| ブラジル         | `https://br.api.pdfblocks.com/v1/add_password` |

## 認証

すべてのリクエストは、HTTPS 経由で `X-API-Key` ヘッダーにシークレット API キーを設定して認証してください。キーの作成と管理は[ダッシュボード](https://dashboard.pdfblocks.com)から行います。詳細は[認証](/docs/api/authentication)を参照してください。

## リクエスト

このエンドポイントは `multipart/form-data` 形式のリクエストボディを受け付けます。

<ParamField name="file" type="file" required>
  入力する PDF ドキュメント。
</ParamField>

<ParamField name="password" type="string" required>
  ドキュメントを開くために必要なパスワード。4〜32文字の印字可能な ASCII 文字（`^[\x20-\x7e]{4,32}$`）。
</ParamField>

<ParamField name="encryption_algorithm" type="string" default="AES-128">
  暗号化アルゴリズム。`AES-128` または `AES-256` のいずれか。
</ParamField>

<Note>
  これは開くためのパスワードを設定するもので、ドキュメントを暗号化し、そのパスワードなしでは開けないようにします。開くためのパスワードを要求せずに、読者ができること（印刷、コピー、編集）を制限したい場合は、代わりに[制限の追加](/docs/api/add-restrictions-to-pdf)を使用してください。ライフサイクル全体については、[ドキュメントの保護](/docs/api/protecting-documents)を参照してください。
</Note>

## 例

AES-256 で PDF を暗号化し、パスワードなしでは開けないようにする例：

<CodeGroup>

```bash title="cURL"
curl https://api.pdfblocks.com/v1/add_password \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F password='0pen-Sesame' \
  -F encryption_algorithm=AES-256 \
  -o encrypted.pdf
```

```python title="Python"
# pip install requests
import requests

with open('input.pdf', 'rb') as file:
    response = requests.post(
        'https://api.pdfblocks.com/v1/add_password',
        headers={'X-API-Key': 'your_api_key'},
        files={'file': file},
        data={
            'password': '0pen-Sesame',
            'encryption_algorithm': 'AES-256',
        },
    )

response.raise_for_status()
with open('encrypted.pdf', 'wb') as output:
    output.write(response.content)
```

```javascript title="Node.js"
// Node.js 18+
import { readFile, writeFile } from 'node:fs/promises';

const body = new FormData();
body.set('file', new Blob([await readFile('input.pdf')]), 'input.pdf');
body.set('password', '0pen-Sesame');
body.set('encryption_algorithm', 'AES-256');

const response = await fetch('https://api.pdfblocks.com/v1/add_password', {
  method: 'POST',
  headers: { 'X-API-Key': 'your_api_key' },
  body,
});

if (!response.ok) throw new Error(`Request failed: ${response.status}`);
await writeFile('encrypted.pdf', Buffer.from(await response.arrayBuffer()));
```

```php title="PHP"
<?php
$ch = curl_init('https://api.pdfblocks.com/v1/add_password');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['X-API-Key: your_api_key'],
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => [
        'file' => new CURLFile('input.pdf', 'application/pdf'),
        'password' => '0pen-Sesame',
        'encryption_algorithm' => 'AES-256',
    ],
]);

$pdf = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) {
    file_put_contents('encrypted.pdf', $pdf);
}
```

```ruby title="Ruby"
# gem install http
require 'http'

response = HTTP
  .headers('X-API-Key' => 'your_api_key')
  .post('https://api.pdfblocks.com/v1/add_password', form: {
    file: HTTP::FormData::File.new('input.pdf'),
    password: '0pen-Sesame',
    encryption_algorithm: 'AES-256',
  })

File.write('encrypted.pdf', response.body) if response.status.success?
```

```go title="Go"
package main

import (
	"bytes"
	"io"
	"mime/multipart"
	"net/http"
	"os"
)

func main() {
	var buf bytes.Buffer
	form := multipart.NewWriter(&buf)

	file, _ := os.Open("input.pdf")
	defer file.Close()
	part, _ := form.CreateFormFile("file", "input.pdf")
	io.Copy(part, file)

	form.WriteField("password", "0pen-Sesame")
	form.WriteField("encryption_algorithm", "AES-256")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/add_password", &buf)
	req.Header.Set("Content-Type", form.FormDataContentType())
	req.Header.Set("X-API-Key", "your_api_key")

	res, _ := http.DefaultClient.Do(req)
	defer res.Body.Close()

	out, _ := os.Create("encrypted.pdf")
	defer out.Close()
	io.Copy(out, res.Body)
}
```

```csharp title="C#"
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", "your_api_key");

using var form = new MultipartFormDataContent
{
    { new ByteArrayContent(File.ReadAllBytes("input.pdf")), "file", "input.pdf" },
    { new StringContent("0pen-Sesame"), "password" },
    { new StringContent("AES-256"), "encryption_algorithm" },
};

var response = await client.PostAsync(
    "https://api.pdfblocks.com/v1/add_password", form);
response.EnsureSuccessStatusCode();
await File.WriteAllBytesAsync(
    "encrypted.pdf", await response.Content.ReadAsByteArrayAsync());
```

</CodeGroup>

## レスポンス

成功すると、暗号化された PDF を本文とする `200 OK` が返されます：

```http
HTTP/1.1 200 OK
Content-Type: application/pdf
Content-Length: 48213
```

出力は暗号化された同じドキュメントです。ページと内容は変更されません。上記の例のように、レスポンスの本文はそのままファイルにストリーミングしてください。サーバー側には何も保存されません。

## エラー

リクエストが失敗した場合は、`application/problem+json` 形式のボディが返されます。このエンドポイントで最も多いのは `400` で、パラメーターが無効な場合（たとえば `password` が 4〜32文字の印字可能な ASCII 文字でない場合）に返され、`errors` オブジェクトに該当するフィールド名が示されます：

```json
{
  "type": "https://www.pdfblocks.com/docs/api/v1/error/400",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "errors": {
    "password": ["The field password must match the regular expression '^[\\x20-\\x7e]{4,32}$'."]
  }
}
```

`X-API-Key` が指定されていないか無効な場合は `401` が返されます。すべてのステータスコードとレスポンスの完全な形式については、[エラー](/docs/api/errors)を参照してください。

## レシピ

よく使われるバリエーションです。展開すると、各言語のコード例を確認できます。

<AccordionGroup>

<Accordion title="デフォルトの AES-128 で暗号化">

<CodeGroup>

```bash title="cURL"
curl https://api.pdfblocks.com/v1/add_password \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F password='Tr0ub4dor' \
  -o encrypted.pdf
```

```python title="Python"
import requests

with open('input.pdf', 'rb') as file:
    response = requests.post(
        'https://api.pdfblocks.com/v1/add_password',
        headers={'X-API-Key': 'your_api_key'},
        files={'file': file},
        data={'password': 'Tr0ub4dor'},
    )

response.raise_for_status()
with open('encrypted.pdf', 'wb') as output:
    output.write(response.content)
```

```javascript title="Node.js"
import { readFile, writeFile } from 'node:fs/promises';

const body = new FormData();
body.set('file', new Blob([await readFile('input.pdf')]), 'input.pdf');
body.set('password', 'Tr0ub4dor');

const response = await fetch('https://api.pdfblocks.com/v1/add_password', {
  method: 'POST',
  headers: { 'X-API-Key': 'your_api_key' },
  body,
});

if (!response.ok) throw new Error(`Request failed: ${response.status}`);
await writeFile('encrypted.pdf', Buffer.from(await response.arrayBuffer()));
```

```php title="PHP"
<?php
$ch = curl_init('https://api.pdfblocks.com/v1/add_password');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['X-API-Key: your_api_key'],
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => [
        'file' => new CURLFile('input.pdf', 'application/pdf'),
        'password' => 'Tr0ub4dor',
    ],
]);

$pdf = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) {
    file_put_contents('encrypted.pdf', $pdf);
}
```

```ruby title="Ruby"
require 'http'

response = HTTP
  .headers('X-API-Key' => 'your_api_key')
  .post('https://api.pdfblocks.com/v1/add_password', form: {
    file: HTTP::FormData::File.new('input.pdf'),
    password: 'Tr0ub4dor',
  })

File.write('encrypted.pdf', response.body) if response.status.success?
```

```go title="Go"
package main

import (
	"bytes"
	"io"
	"mime/multipart"
	"net/http"
	"os"
)

func main() {
	var buf bytes.Buffer
	form := multipart.NewWriter(&buf)

	file, _ := os.Open("input.pdf")
	defer file.Close()
	part, _ := form.CreateFormFile("file", "input.pdf")
	io.Copy(part, file)

	form.WriteField("password", "Tr0ub4dor")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/add_password", &buf)
	req.Header.Set("Content-Type", form.FormDataContentType())
	req.Header.Set("X-API-Key", "your_api_key")

	res, _ := http.DefaultClient.Do(req)
	defer res.Body.Close()

	out, _ := os.Create("encrypted.pdf")
	defer out.Close()
	io.Copy(out, res.Body)
}
```

```csharp title="C#"
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", "your_api_key");

using var form = new MultipartFormDataContent
{
    { new ByteArrayContent(File.ReadAllBytes("input.pdf")), "file", "input.pdf" },
    { new StringContent("Tr0ub4dor"), "password" },
};

var response = await client.PostAsync(
    "https://api.pdfblocks.com/v1/add_password", form);
response.EnsureSuccessStatusCode();
await File.WriteAllBytesAsync(
    "encrypted.pdf", await response.Content.ReadAsByteArrayAsync());
```

</CodeGroup>

</Accordion>

</AccordionGroup>

## 関連アクション

<CardGroup cols={2}>

<Card title="パスワードを削除" href="/docs/api/remove-password-from-pdf">
  パスワード保護された PDF を復号します。
</Card>

<Card title="制限を追加" href="/docs/api/add-restrictions-to-pdf">
  開くためのパスワードの代わりに権限フラグを設定します。
</Card>

<Card title="制限を削除" href="/docs/api/remove-restrictions-from-pdf">
  権限フラグをリセットします。
</Card>

<Card title="テキスト透かしの追加" href="/docs/api/add-text-watermark-to-pdf">
  暗号化する前にドキュメントに透かしを付与します。
</Card>

</CardGroup>
