管理 S/MIME 憑證

Gmail S/MIME API 提供程式輔助存取權,可為 Google Workspace 網域中的使用者管理 S/MIME 電子郵件憑證。

管理員必須為網域啟用 S/MIME,憑證才能運作。

S/MIME 標準提供公開金鑰加密和 MIME 資料簽署的規格。在使用者帳戶中設定 S/MIME 憑證後,Gmail 會以以下方式使用該憑證:

  • Gmail 會使用使用者的憑證和私密金鑰簽署傳送的郵件。
  • Gmail 會使用使用者的私密金鑰解密傳入的郵件。
  • Gmail 會使用收件者的憑證和公開金鑰加密傳出郵件。
  • Gmail 會使用寄件者的憑證和公開金鑰驗證傳入的郵件。

您可以產生個別的 S/MIME 憑證,然後使用 API 上傳。每個 S/MIME 憑證都會對應至使用者電子郵件帳戶的特定別名。別名包括主要電子郵件地址,以及自訂的「寄件者身分」地址。系統會將單一 S/MIME 憑證標示為每個別名的預設值。

授權 API 存取權

授權存取 API 的方式有兩種:

  1. 您可以使用服務帳戶,並設定全網域授權委派功能。如需這些條款的說明,請參閱驗證和授權總覽條款。如要瞭解如何啟用這個選項,請參閱「建立具有全網域授權委派功能的服務帳戶
  2. 您可以使用標準 OAuth2 流程,要求使用者同意才能取得 Oauth2 存取權杖。詳情請參閱驗證和授權總覽。如要使用這個選項,網域管理員必須在網域控制面板中勾選「啟用 S/MIME API 使用者存取權」核取方塊。

ACL 範圍

這個 API 會使用與 Gmail sendAs 方法相同的 ACL 範圍

gmail.settings.basic
如要更新主要 SendAs S/MIME,就必須使用這個範圍。
gmail.settings.sharing
如要透過 S/MIME 更新自訂內容,就必須使用這個權限範圍。

使用 API

users.settings.sendAs.smimeInfo 資源提供用於管理 S/MIME 憑證的方法。每張憑證都會與使用者的一個「以身分代發」別名建立關聯。

上傳 S/MIME 金鑰

使用 smimeInfo.insert() 方法,為使用者所屬別名上傳新的 S/MIME 金鑰。您可以使用下列參數識別目標別名:

userId
使用者的電子郵件地址。您可以使用特殊值 me 來指出目前已驗證的使用者。
sendAsEmail
您要上傳金鑰的別名。這是使用這個別名傳送郵件時,會顯示在「寄件者:」標頭中的電子郵件地址。

S/MIME 憑證和私密金鑰應以該格式出現在 pkcs12 欄位中;要求中不得設定其他欄位。PKCS12 欄位應包含使用者 S/MIME 金鑰和簽署憑證鏈結。API 會先對這個欄位執行標準驗證,再接受該欄位,驗證項目如下:

  • 主旨與指定的電子郵件地址相符。
  • 到期日有效。
  • 核發憑證的憑證授權單位 (CA) 在我們的信任清單中。
  • 憑證符合 Gmail 的技術限制。

如果金鑰已加密,密碼應位於 encryptedKeyPassword 欄位中。成功的 insert() 呼叫會傳回 smimeInfo 的 ID,可用於日後參照金鑰。

列出使用者的 S/MIME 金鑰

使用 smimeInfo.list() 方法,針對指定別名的使用者傳回 S/MIME 金鑰清單。您可以使用下列參數識別目標別名:

userId
使用者的電子郵件地址。您可以使用特殊值 me 來指出目前已驗證的使用者。
sendAsEmail
用於列出金鑰的別名。這是使用這個別名傳送郵件時,會顯示在「寄件者:」標頭中的電子郵件地址。

擷取別名的 S/MIME 金鑰

使用 smimeInfo.get() 方法,針對使用者的特定「傳送者」別名,傳回特定 S/MIME 金鑰。您可以使用下列參數識別目標別名:

userId
使用者的電子郵件地址。您可以使用特殊值 me 來指出目前已驗證的使用者。
sendAsEmail
您要擷取金鑰的別名。這是使用這個別名傳送郵件時,會顯示在「寄件者:」標頭中的電子郵件地址。

刪除 S/MIME 金鑰

使用 smimeInfo.delete() 方法,從別名中刪除指定的 S/MIME 金鑰。您可以使用下列參數識別目標別名:

userId
使用者的電子郵件地址。您可以使用特殊值 me 來指出目前已驗證的使用者。
sendAsEmail
您要擷取金鑰的別名。這是使用這個別名傳送郵件時,會顯示在「寄件者:」標頭中的電子郵件地址。
id
SmimeInfo 的固定 ID。

為別名設定預設 S/MIME 金鑰

使用 smimeInfo.setDefault() 方法,將指定的 S/MIME 金鑰標示為指定別名的預設值。您可以使用下列參數識別目標別名:

userId
使用者的電子郵件地址。您可以使用特殊值 me 來指出目前已驗證的使用者。
sendAsEmail
您要擷取金鑰的別名。這是使用這個別名傳送郵件時,會顯示在「寄件者:」標頭中的電子郵件地址。
id
SmimeInfo 的固定 ID。

程式碼範例

以下程式碼範例示範如何使用 API 管理擁有多位使用者的機構的 S/MIME 憑證。

為 S/MIME 憑證建立 SmimeInfo 資源

以下程式碼範例示範如何從檔案讀取憑證,將其編碼為 base64url 字串,然後指派至 smimeInfo 資源的 pkcs12 欄位:

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 憑證

如要上傳憑證,請呼叫 smimeInfo.insert,並在要求主體中提供 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()

管理多位使用者憑證的範例

您可能會想一次管理機構中多位使用者的憑證。以下範例說明如何在單一批次呼叫中管理多位使用者的憑證。

從 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

您可以使用先前提到的 createSmimeInfoinsertSmimeInfo 呼叫,依 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")

憑證管理功能

這個範例會結合 smimeInfo API 的多個呼叫,說明如何管理貴機構的憑證。它會列出使用者的憑證,如果預設憑證已過期或未設定,就會上傳指定檔案中找到的憑證。然後將到期日最晚的憑證設為預設值。

接著,這會從處理 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,
  )