Gmail API を使用して S/MIME 証明書を管理する

このドキュメントでは、Gmail API で S/MIME メール証明書を使用する方法について説明します。

Gmail API を使用すると、プログラムで Google Workspace ドメインのユーザーの S/MIME メール証明書を管理できます。

証明書を使用するには、管理者がドメインでホスト型 S/MIME を有効にする必要があります。

S/MIME 標準は、公開鍵暗号化と MIME データの署名の 仕様を提供します。S/MIME 証明書がユーザー アカウントで構成されている場合、Gmail は次の方法で使用します。

  • ユーザー証明書と秘密鍵を使用して送信メールに署名する。

  • ユーザーの秘密鍵を使用して受信メールを復号する。

  • 受信者の証明書と公開鍵を使用して送信メールを暗号化する。

  • 送信者の証明書と公開鍵を使用して受信メールを検証する。

個々の S/MIME 証明書を生成して、Gmail API を使用してアップロードできます。各 S/MIME 証明書は、ユーザーのメール アカウントの特定のエイリアス用です。エイリアスには、メインのメールアドレスとカスタムの [名前を付けて送信] アドレスが含まれます。API は、各エイリアスのデフォルトとして 1 つの S/MIME 証明書をマークします。

エイリアスの詳細については、Gmail API でエイリアスと署名を管理する をご覧ください。

API アクセスを承認する

Gmail API へのアクセスを承認するには、次のいずれかの方法を使用します。

  1. ドメイン全体の権限委任が設定された サービス アカウントを使用する。これらの用語の説明については、認証と 認可についてをご覧ください。このオプションを有効にするには、アクセス認証情報を作成するをご覧ください。

  2. エンドユーザーの同意を得て OAuth 2.0 アクセス トークンを取得する標準の OAuth 2.0 フローを使用する。詳細については、認証と認可について をご覧ください

    このオプションを使用するには、ドメイン管理者が Google 管理コンソールで [メールの送受信で S/MIME 暗号化を有効にする] チェックボックスをオンにする必要があります。詳細については、ホスト型 S/MIME を有効にする Google 管理コンソールをご覧ください。

ACL スコープ

Gmail API は、同じ ACL スコープを、Gmail sendAs メソッドと同じように使用します。

  • gmail.settings.basic: メインの SendAs S/MIME を更新するには、このスコープが必要です。

  • gmail.settings.sharing: カスタムの from S/MIME を更新するには、このスコープが必要です。

S/MIME 鍵を構成する

settings.sendAs.smimeInfo リソースには、S/MIME 証明書を管理するためのメソッドがいくつか用意されています。各証明書は、ユーザーの 1 つの [名前を付けて送信] エイリアスに関連付けられています。

ユーザーの [名前を付けて送信] エイリアスを特定するには、 settings.sendAs.list リソースで settings.sendAs メソッドを使用します。

S/MIME 鍵をアップロードする

settings.sendAs.smimeInfo リソースで settings.sendAs.smimeInfo.insert メソッドを使用して、ユーザーに属するエイリアスの新しい S/MIME 鍵 をアップロードします。次のパスパラメータを使用して、ターゲット エイリアスを特定します。

  • userId: ユーザーのメールアドレス。特別な値 me を使用して、認証済みユーザーを示します。

  • sendAsEmail: 鍵をアップロードするエイリアス。このメールアドレスは、このエイリアスを使用して送信されたメールの From: ヘッダーに表示されます。

S/MIME 証明書と秘密鍵は、その形式で pkcs12 フィールドに存在する必要があります。リクエストで他のフィールドを設定しないでください。pkcs12 フィールドには、ユーザーの S/MIME 鍵と署名証明書チェーンの両方が含まれています。API は、このフィールドを受け入れる前に標準の検証を行い、次のことを確認します。

  • 件名が指定されたメールアドレスと一致している。
  • 有効期限が有効である。
  • 発行元の認証局(CA)が Google の信頼リストに含まれている。
  • 証明書が Gmail の技術的な制約を満たしている。

鍵が暗号化されている場合は、パスワードを encryptedKeyPassword フィールドに指定する必要があります。settings.sendAs.smimeInfo.insert メソッド呼び出しが成功すると、今後鍵を参照するために使用される settings.sendAs.smimeInfo リソース id が返されます。

ユーザーの S/MIME 鍵を一覧表示する

settings.sendAs.smimeInfo リソースで settings.sendAs.smimeInfo.list メソッドを使用して、指定されたエイリアスの指定されたユーザーの S/MIME 鍵のリストを返します。次のパスパラメータを使用して、ターゲット エイリアスを特定します。

  • userId: ユーザーのメールアドレス。特別な値 me を使用して、認証済みユーザーを示します。

  • sendAsEmail: 鍵を一覧表示するエイリアス。このメールアドレスは、このエイリアスを使用して送信されたメールの From: ヘッダーに表示されます。

エイリアスの S/MIME 鍵を取得する

settings.sendAs.smimeInfo.get メソッドを settings.sendAs.smimeInfo リソースで使用して、ユーザーの特定の [名前を付けて送信] エイリアスの特定の S/MIME 鍵を返します。次のパスパラメータを使用して、ターゲット エイリアスを特定します。

  • userId: ユーザーのメールアドレス。特別な値 me を使用して、認証済みユーザーを示します。

  • sendAsEmail: 鍵を取得するエイリアス。このメールアドレスは、このエイリアスを使用して送信されたメールの From: ヘッダーに表示されます。

S/MIME 鍵を削除する

settings.sendAs.smimeInfo リソースで settings.sendAs.smimeInfo.delete メソッドを使用して、エイリアスから指定された S/MIME 鍵を削除します。次のパスパラメータを使用して、ターゲット エイリアスを特定します。

  • userId: ユーザーのメールアドレス。特別な値 me を使用して、認証済みユーザーを示します。

  • sendAsEmail: 鍵を削除するエイリアス。このメールアドレスは、このエイリアスを使用して送信されたメールの From: ヘッダーに表示されます。

  • id: smimeInfo の不変 ID。

エイリアスのデフォルトの S/MIME 鍵を設定する

settings.sendAs.smimeInfo リソースで settings.sendAs.smimeInfo.setDefault メソッドを使用して、指定された S/MIME 鍵を指定されたエイリアスのデフォルトとしてマークします。次のパスパラメータを使用して、ターゲット エイリアスを特定します。

  • userId: ユーザーのメールアドレス。特別な値 me を使用して、認証済みユーザーを示します。

  • sendAsEmail: デフォルトとして設定する鍵のエイリアス。このメールアドレスは、このエイリアスを使用して送信されたメールの From: ヘッダーに表示されます。

  • id: smimeInfo の不変 ID。

コードサンプル

次のコードサンプルは、Gmail API を使用して、複数のユーザーがいる組織の S/MIME 証明書を管理する方法を示しています。

S/MIME 証明書の smimeInfo リソースを作成する

このコードサンプルは、ファイルから証明書を読み取り、Base64URL 文字列にエンコードして、pkcs12 フィールドを settings.sendAs.smimeInfo リソースに割り当てる方法を示しています。

Java

gmail/snippets/src/main/java/CreateSmimeInfo.java
import com.google.api.services.gmail.model.SmimeInfo;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

/* Class to demonstrate the use of Gmail Create SmimeInfo API */
public class CreateSmimeInfo {
  /**
   * Create an SmimeInfo resource for a certificate from file.
   *
   * @param filename Name of the file containing the S/MIME certificate.
   * @param password Password for the certificate file, or null if the file is not
   *                 password-protected.
   * @return An SmimeInfo object with the specified certificate.
   */
  public static SmimeInfo createSmimeInfo(String filename, String password) {
    SmimeInfo smimeInfo = null;
    InputStream in = null;

    try {
      File file = new File(filename);
      in = new FileInputStream(file);
      byte[] fileContent = new byte[(int) file.length()];
      in.read(fileContent);

      smimeInfo = new SmimeInfo();
      smimeInfo.setPkcs12(Base64.getUrlEncoder().encodeToString(fileContent));
      if (password != null && password.length() > 0) {
        smimeInfo.setEncryptedKeyPassword(password);
      }
    } catch (Exception e) {
      System.out.printf("An error occured while reading the certificate file: %s\n", e);
    } finally {
      try {
        if (in != null) {
          in.close();
        }
      } catch (IOException ioe) {
        System.out.printf("An error occured while closing the input stream: %s\n", ioe);
      }
    }
    return smimeInfo;
  }
}

Python

gmail/snippet/smime snippets/create_smime_info.py
import base64


def create_smime_info(cert_filename, cert_password):
  """Create an smimeInfo resource for a certificate from file.
  Args:
    cert_filename: Name of the file containing the S/MIME certificate.
    cert_password: Password for the certificate file, or None if the file is not
        password-protected.
  Returns : Smime object, including smime information
  """

  smime_info = None
  try:
    with open(cert_filename, "rb") as cert:
      smime_info = {}
      data = cert.read().encode("UTF-8")
      smime_info["pkcs12"] = base64.urlsafe_b64encode(data).decode()
      if cert_password and len(cert_password) > 0:
        smime_info["encryptedKeyPassword"] = cert_password

  except (OSError, IOError) as error:
    print(f"An error occurred while reading the certificate file: {error}")
    smime_info = None

  return smime_info


if __name__ == "__main__":
  print(create_smime_info(cert_filename="xyz", cert_password="xyz"))

S/MIME 証明書をアップロードする

証明書をアップロードするには、 settings.sendAs.smimeInfo.insert メソッドを呼び出し、リクエストの本文に settings.sendAs.smimeInfo リソースを指定します。

Java

gmail/snippets/src/main/java/InsertSmimeInfo.java
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.model.SmimeInfo;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;

/* Class to demonstrate the use of Gmail Insert Smime Certificate API*/
public class InsertSmimeInfo {
  /**
   * Upload an S/MIME certificate for the user.
   *
   * @param userId      User's email address.
   * @param sendAsEmail The "send as" email address, or null if it should be the same as userId.
   * @param smimeInfo   The SmimeInfo object containing the user's S/MIME certificate.
   * @return An SmimeInfo object with details about the uploaded certificate, {@code null} otherwise.
   * @throws IOException - if service account credentials file not found.
   */
  public static SmimeInfo insertSmimeInfo(String userId,
                                          String sendAsEmail,
                                          SmimeInfo smimeInfo)
      throws IOException {
        /* Load pre-authorized user credentials from the environment.
           TODO(developer) - See https://developers.google.com/identity for
            guides on implementing OAuth2 for your application. */
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
        .createScoped(GmailScopes.GMAIL_SETTINGS_SHARING);
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
        credentials);

    // Create the gmail API client
    Gmail service = new Gmail.Builder(new NetHttpTransport(),
        GsonFactory.getDefaultInstance(),
        requestInitializer)
        .setApplicationName("Gmail samples")
        .build();

    if (sendAsEmail == null) {
      sendAsEmail = userId;
    }

    try {
      SmimeInfo results = service.users().settings().sendAs().smimeInfo()
          .insert(userId, sendAsEmail, smimeInfo)
          .execute();
      System.out.printf("Inserted certificate, id: %s\n", results.getId());
      return results;
    } catch (IOException e) {
      System.err.printf("An error occured: %s", e);
    }
    return null;
  }
}

Python

gmail/snippet/smime snippets/insert_smime_info.py
import create_smime_info
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def insert_smime_info():
  """Upload an S/MIME certificate for the user.
  Print the inserted certificate's id
  Returns : Result object with inserted certificate id and other meta-data

  Load pre-authorized user credentials from the environment.
  TODO(developer) - See https://developers.google.com/identity
  for guides on implementing OAuth2 for the application.
  """
  creds, _ = google.auth.default()

  try:
    # create gmail api client
    service = build("gmail", "v1", credentials=creds)

    user_id = "gduser1@workspacesamples.dev"
    smime_info = create_smime_info.create_smime_info(
        cert_filename="xyz", cert_password="xyz"
    )
    send_as_email = None

    if not send_as_email:
      send_as_email = user_id

    # pylint: disable=maybe-no-member
    results = (
        service.users()
        .settings()
        .sendAs()
        .smimeInfo()
        .insert(userId=user_id, sendAsEmail=send_as_email, body=smime_info)
        .execute()
    )
    print(f'Inserted certificate; id: {results["id"]}')

  except HttpError as error:
    print(f"An error occurred: {error}")
    results = None

  return results


if __name__ == "__main__":
  insert_smime_info()

複数のユーザーの証明書を管理する

次のコードサンプルは、1 回のバッチ呼び出しで組織内の複数のユーザーの証明書を管理する方法を示しています。

CSV ファイルから証明書を挿入する

次の CSV ファイルの例では、ユーザー ID と各ユーザーの証明書のパスが一覧表示されます。

$ cat certificates.csv
user1@example.com,/path/to/user1_cert.p12,cert_password_1
user2@example.com,/path/to/user2_cert.p12,cert_password_2
user3@example.com,/path/to/user3_cert.p12,cert_password_3

Java

CreateSmimeInfo および InsertSmimeInfo サンプル を使用して、CSV ファイルで指定されたユーザーの証明書をアップロードできます。

gmail/snippets/src/main/java/InsertCertFromCsv.java
import com.google.api.services.gmail.model.SmimeInfo;
import java.io.File;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

/* Class to demonstrate the use of Gmail Insert Certificate from CSV File */
public class InsertCertFromCsv {
  /**
   * Upload S/MIME certificates based on the contents of a CSV file.
   *
   * <p>Each row of the CSV file should contain a user ID, path to the certificate, and the
   * certificate password.
   *
   * @param csvFilename Name of the CSV file.
   */
  public static void insertCertFromCsv(String csvFilename) {
    try {
      File csvFile = new File(csvFilename);
      CSVParser parser =
          CSVParser.parse(csvFile, java.nio.charset.StandardCharsets.UTF_8, CSVFormat.DEFAULT);
      for (CSVRecord record : parser) {
        String userId = record.get(0);
        String certFilename = record.get(1);
        String certPassword = record.get(2);
        SmimeInfo smimeInfo = CreateSmimeInfo.createSmimeInfo(certFilename,
            certPassword);
        if (smimeInfo != null) {
          InsertSmimeInfo.insertSmimeInfo(userId,
              userId,
              smimeInfo);
        } else {
          System.err.printf("Unable to read certificate file for userId: %s\n", userId);
        }
      }
    } catch (Exception e) {
      System.err.printf("An error occured while reading the CSV file: %s", e);
    }
  }
}

Python

create_smime_infoinsert_smime_info サンプルを使用して、CSV ファイルで指定されたユーザーの証明書をアップロードできます。

gmail/snippet/smime snippets/insert_cert_from_csv.py
import csv

import create_smime_info
import insert_smime_info


def insert_cert_from_csv(csv_filename):
  """Upload S/MIME certificates based on the contents of a CSV file.
  Each row of the CSV file should contain a user ID, path to the certificate,
  and the certificate password.

  Args:
    csv_filename: Name of the CSV file.
  """

  try:
    with open(csv_filename, "rb") as cert:
      csv_reader = csv.reader(cert, delimiter=",")
      next(csv_reader, None)  # skip CSV file header
      for row in csv_reader:
        user_id = row[0]
        cert_filename = row[1]
        cert_password = row[2]
        smime_info = create_smime_info.create_smime_info(
            cert_filename=cert_filename, cert_password=cert_password
        )
        if smime_info:
          insert_smime_info.insert_smime_info()
        else:
          print(f"Unable to read certificate file for user_id: {user_id}")
        return smime_info

  except (OSError, IOError) as error:
    print(f"An error occured while reading the CSV file: {error}")


if __name__ == "__main__":
  insert_cert_from_csv(csv_filename="xyz")

証明書の管理

このサンプルでは、settings.sendAs.smimeInfo リソースの複数のメソッドを組み合わせて、組織の証明書を管理する方法を示します。ユーザーの証明書が一覧表示されます。デフォルトの証明書の有効期限が切れているか、設定されていない場合は、指定されたファイルにある証明書がアップロードされます。次に、有効期限が最も長い証明書がデフォルトとして設定されます。

この関数は、前の Insert CSV ファイルから証明書を挿入する サンプルと同様に、CSV ファイルを処理します。

Java

gmail/snippets/src/main/java/UpdateSmimeCerts.java
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.model.ListSmimeInfoResponse;
import com.google.api.services.gmail.model.SmimeInfo;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

/* Class to demonstrate the use of Gmail Update Smime Certificate API*/
public class UpdateSmimeCerts {
  /**
   * Update S/MIME certificates for the user.
   *
   * <p>First performs a lookup of all certificates for a user. If there are no certificates, or
   * they all expire before the specified date/time, uploads the certificate in the specified file.
   * If the default certificate is expired or there was no default set, chooses the certificate with
   * the expiration furthest into the future and sets it as default.
   *
   * @param userId       User's email address.
   * @param sendAsEmail  The "send as" email address, or None if it should be the same as user_id.
   * @param certFilename Name of the file containing the S/MIME certificate.
   * @param certPassword Password for the certificate file, or None if the file is not
   *                     password-protected.
   * @param expireTime   DateTime object against which the certificate expiration is compared. If
   *                     None, uses the current time. @ returns: The ID of the default certificate.
   * @return The ID of the default certificate, {@code null} otherwise.
   * @throws IOException - if service account credentials file not found.
   */
  public static String updateSmimeCerts(String userId,
                                        String sendAsEmail,
                                        String certFilename,
                                        String certPassword,
                                        LocalDateTime expireTime)
      throws IOException {
        /* Load pre-authorized user credentials from the environment.
           TODO(developer) - See https://developers.google.com/identity for
            guides on implementing OAuth2 for your application. */
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
        .createScoped(GmailScopes.GMAIL_SETTINGS_SHARING);
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
        credentials);

    // Create the gmail API client
    Gmail service = new Gmail.Builder(new NetHttpTransport(),
        GsonFactory.getDefaultInstance(),
        requestInitializer)
        .setApplicationName("Gmail samples")
        .build();

    if (sendAsEmail == null) {
      sendAsEmail = userId;
    }

    ListSmimeInfoResponse listResults;
    try {
      listResults =
          service.users().settings().sendAs().smimeInfo().list(userId, sendAsEmail).execute();
    } catch (IOException e) {
      System.err.printf("An error occurred during list: %s\n", e);
      return null;
    }

    String defaultCertId = null;
    String bestCertId = null;
    LocalDateTime bestCertExpire = LocalDateTime.MIN;

    if (expireTime == null) {
      expireTime = LocalDateTime.now();
    }
    if (listResults != null && listResults.getSmimeInfo() != null) {
      for (SmimeInfo smimeInfo : listResults.getSmimeInfo()) {
        String certId = smimeInfo.getId();
        boolean isDefaultCert = smimeInfo.getIsDefault();
        if (isDefaultCert) {
          defaultCertId = certId;
        }
        LocalDateTime exp =
            LocalDateTime.ofInstant(
                Instant.ofEpochMilli(smimeInfo.getExpiration()), ZoneId.systemDefault());
        if (exp.isAfter(expireTime)) {
          if (exp.isAfter(bestCertExpire)) {
            bestCertId = certId;
            bestCertExpire = exp;
          }
        } else {
          if (isDefaultCert) {
            defaultCertId = null;
          }
        }
      }
    }
    if (defaultCertId == null) {
      String defaultId = bestCertId;
      if (defaultId == null && certFilename != null) {
        SmimeInfo smimeInfo = CreateSmimeInfo.createSmimeInfo(certFilename,
            certPassword);
        SmimeInfo insertResults = InsertSmimeInfo.insertSmimeInfo(userId,
            sendAsEmail,
            smimeInfo);
        if (insertResults != null) {
          defaultId = insertResults.getId();
        }
      }

      if (defaultId != null) {
        try {
          service.users().settings().sendAs().smimeInfo().setDefault(userId, sendAsEmail, defaultId)
              .execute();
          return defaultId;
        } catch (IOException e) {
          System.err.printf("An error occured during setDefault: %s", e);
        }
      }
    } else {
      return defaultCertId;
    }

    return null;
  }
}

Python

gmail/snippet/smime snippets/update_smime_cert.py
from datetime import datetime

import create_smime_info
import google.auth
import insert_smime_info
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def update_smime_cert(
    user_id, send_as_email, cert_filename, cert_password, expire_dt
):
  """Update S/MIME certificates for the user.

  First performs a lookup of all certificates for a user.  If there are no
  certificates, or they all expire before the specified date/time, uploads the
  certificate in the specified file.  If the default certificate is expired or
  there was no default set, chooses the certificate with the expiration furthest
  into the future and sets it as default.

  Args:
    user_id: User's email address.
    send_as_email: The "send as" email address, or None if it should be the same
        as user_id.
    cert_filename: Name of the file containing the S/MIME certificate.
    cert_password: Password for the certificate file, or None if the file is not
        password-protected.
    expire_dt: DateTime object against which the certificate expiration is
      compared.  If None, uses the current time.

  Returns:
    The ID of the default certificate.

  Load pre-authorized user credentials from the environment.
  TODO(developer) - See https://developers.google.com/identity
  for guides on implementing OAuth2 for the application.
  """
  if not send_as_email:
    send_as_email = user_id

  creds, _ = google.auth.default()

  try:
    # create gmail api client
    service = build("gmail", "v1", credentials=creds)

    # pylint: disable=maybe-no-member
    results = (
        service.users()
        .settings()
        .sendAs()
        .smimeInfo()
        .list(userId=user_id, sendAsEmail=send_as_email)
        .execute()
    )

  except HttpError as error:
    print(f"An error occurred during list: {error}")
    return None

  default_cert_id = None
  best_cert_id = (None, datetime.datetime.fromtimestamp(0))

  if not expire_dt:
    expire_dt = datetime.datetime.now()
  if results and "smimeInfo" in results:
    for smime_info in results["smimeInfo"]:
      cert_id = smime_info["id"]
      is_default_cert = smime_info["isDefault"]
      if is_default_cert:
        default_cert_id = cert_id
      exp = datetime.datetime.fromtimestamp(smime_info["expiration"] / 1000)
      if exp > expire_dt:
        if exp > best_cert_id[1]:
          best_cert_id = (cert_id, exp)
      else:
        if is_default_cert:
          default_cert_id = None

  if not default_cert_id:
    default_id = best_cert_id[0]
    if not default_id and cert_filename:
      create_smime_info.create_smime_info(
          cert_filename=cert_filename, cert_password=cert_password
      )
      results = insert_smime_info.insert_smime_info()
      if results:
        default_id = results["id"]

    if default_id:
      try:
        # pylint: disable=maybe-no-member
        service.users().settings().sendAs().smimeInfo().setDefault(
            userId=user_id, sendAsEmail=send_as_email, id=default_id
        ).execute()
        return default_id
      except HttpError as error:
        print(f"An error occurred during setDefault: {error}")
  else:
    return default_cert_id

  return None


if __name__ == "__main__":
  update_smime_cert(
      user_id="xyz",
      send_as_email=None,
      cert_filename="xyz",
      cert_password="xyz",
      expire_dt=None,
  )