使用 Gmail API 管理 S/MIME 证书

本文档介绍了如何在 Gmail API 中使用 S/MIME 电子邮件证书。

Gmail API 提供程序化访问权限,用于管理 Google Workspace 网域中用户的 S/MIME 电子邮件证书。

管理员必须为网域启用托管 S/MIME,证书才能正常使用。

S/MIME 标准为 MIME 数据的公钥加密和签名提供了规范。在用户账号中配置 S/MIME 证书后,Gmail 会以以下方式使用这些证书:

  • 使用用户证书和私钥为外发邮件签名。

  • 使用用户私钥解密收到的邮件。

  • 使用收件人证书和公钥加密外发邮件。

  • 使用发件人证书和公钥验证收到的邮件。

您可以使用 Gmail API 生成各个 S/MIME 证书并上传。每个 S/MIME 证书都适用于用户电子邮件账号的特定别名。别名包括主邮箱和自定义“发件人”地址。API 会将单个 S/MIME 证书标记为每个别名的默认证书。

如需详细了解别名,请参阅使用 Gmail API 管理别名和签名。

授权 API 访问权限

如需授权访问 Gmail API,请使用以下方法之一:

  1. 使用具有 全网域授权服务账号。如需了解这些术语的说明,请参阅了解身份验证和 授权。如需 启用此选项,请参阅创建访问 凭据

  2. 使用标准 OAuth 2.0 流程,该流程需要最终用户同意才能获取 OAuth 2.0 访问令牌。如需了解详情,请参阅了解 身份验证和授权

    如需使用此选项,网域管理员必须在 Google 管理控制台中选中为收发电子邮件启用 S/MIME 加密 复选框。如需了解详情,请参阅在 Google 管理控制台中启用托管 S/MIME

ACL 范围

Gmail API 依赖于与 Gmail sendAs 方法相同的 same ACL scopes 范围:

  • gmail.settings.basic:更新主 SendAs S/MIME 时需要此范围。

  • gmail.settings.sharing:更新自定义 发件人 S/MIME 时需要此范围。

配置 S/MIME 密钥

settings.sendAs.smimeInfo 资源提供了多种管理 S/MIME 证书的方法。每个证书都与用户的某个发件人别名相关联。

如需确定用户的发件人别名,请对 settings.sendAs 资源使用 settings.sendAs.list 方法。

上传 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 资源使用 settings.sendAs.smimeInfo.get 方法,返回用户的特定发件人别名的特定 S/MIME 密钥。使用以下路径参数标识目标别名:

  • userId:用户的电子邮件地址。使用特殊值 me 表示经过身份验证的用户。

  • sendAsEmail:您要为其检索密钥的别名。此电子邮件地址会显示在使用此别名发送的邮件的 From: 标头中。

删除 S/MIME 密钥

settings.sendAs.smimeInfo 资源使用 settings.sendAs.smimeInfo.delete 方法,从别名中删除指定的 S/MIME 密钥。使用以下路径参数标识目标别名:

  • userId:用户的电子邮件地址。使用特殊值 me 表示经过身份验证的用户。

  • sendAsEmail:您要为其删除密钥的别名。此电子邮件地址会显示在使用此别名发送的邮件的 From: 标头中。

  • idsmimeInfo 的不可变 ID。

为别名设置默认 S/MIME 密钥

settings.sendAs.smimeInfo 资源使用 settings.sendAs.smimeInfo.setDefault 方法,将指定的 S/MIME 密钥标记为指定别名的默认密钥。使用以下路径参数标识目标别名:

  • userId:用户的电子邮件地址。使用特殊值 me 表示经过身份验证的用户。

  • sendAsEmail:要设置为默认密钥的别名。此电子邮件地址会显示在使用此别名发送的邮件的 From: 标头中。

  • idsmimeInfo 的不可变 ID。

代码示例

以下代码示例展示了如何使用 Gmail API 管理具有多个用户的组织的 S/MIME 证书:

为 S/MIME 证书创建 smimeInfo 资源

此代码示例展示了如何从文件中读取证书,将其编码为 Base64网址 字符串,并将其分配给 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()

管理多个用户的证书

这些代码示例展示了如何在一次批量调用中管理组织中多个用户的证书:

从 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")

证书管理

此示例结合了 settings.sendAs.smimeInfo 资源中的多种方法,展示了如何管理组织的证书。它列出了用户的证书。如果默认证书已过期或未设置,它会上传在指定文件中找到的证书。然后,它会将有效期最长的证书设置为默认证书。

然后,此函数会处理 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,
  )