Quản lý chứng chỉ S/MIME

API S/MIME của Gmail cung cấp quyền truy cập có lập trình để quản lý các chứng chỉ email S/MIME cho người dùng trong miền Google Workspace .

Quản trị viên phải bật S/MIME cho miền để các chứng chỉ hoạt động.

Tiêu chuẩn S/MIME cung cấp quy cách cho việc mã hoá bằng khoá công khai và ký dữ liệu MIME. Việc định cấu hình chứng chỉ S/MIME trong tài khoản của người dùng sẽ khiến Gmail sử dụng chứng chỉ đó theo các cách sau:

  • Gmail sử dụng chứng chỉ và khoá riêng tư của người dùng để ký thư gửi đi.
  • Gmail sử dụng khoá riêng tư của người dùng để giải mã thư đến.
  • Gmail sử dụng chứng chỉ và khoá công khai của người nhận để mã hoá thư gửi đi.
  • Gmail sử dụng chứng chỉ của người gửi và khoá công khai để xác minh thư đến.

Bạn tạo từng chứng chỉ S/MIME và tải các chứng chỉ đó lên bằng API. Mỗi chứng chỉ S/MIME dành cho một email đại diện cụ thể của một tài khoản email người dùng. Bí danh bao gồm địa chỉ email chính cũng như địa chỉ "Gửi dưới dạng" tuỳ chỉnh. Một chứng chỉ S/MIME được đánh dấu là mặc định cho mỗi bí danh.

Đang cấp quyền truy cập API

Có hai hình thức uỷ quyền truy cập vào API:

  1. Bạn có thể sử dụng tài khoản dịch vụ với tính năng uỷ quyền trên toàn miền. Để biết nội dung giải thích về các thuật ngữ này, hãy tham khảo bài viết Điều khoản tổng quan về xác thực và uỷ quyền. Để biết thông tin về cách bật tuỳ chọn này, hãy tham khảo phần Tạo tài khoản dịch vụ bằng cách uỷ quyền trên toàn miền
  2. Bạn có thể sử dụng một quy trình OAuth2 tiêu chuẩn cần có sự đồng ý của người dùng cuối để lấy mã truy cập Oauth2. Để biết thêm thông tin, hãy tham khảo phần Tổng quan về xác thực và uỷ quyền Để sử dụng tuỳ chọn này, quản trị viên miền phải bật hộp đánh dấu "Đã bật quyền truy cập của người dùng cuối API S/MIME" trong Bảng điều khiển miền.

Phạm vi ACL

API này dựa vào cùng một phạm vi ACL như các phương thức SendAs của Gmail:

gmail.settings.basic
Bạn phải sử dụng phạm vi này để cập nhật Phần mở rộng thư Internet an toàn/đa mục đích (S/MIME) chính của SendA.
gmail.settings.sharing
Bạn bắt buộc phải sử dụng phạm vi này để cập nhật từ S/MIME tuỳ chỉnh.

Sử dụng API

Tài nguyên users.settings.sendAs.smimeInfo cung cấp các phương thức mà bạn dùng để quản lý chứng chỉ S/MIME. Mỗi chứng chỉ được liên kết với một bí danh gửi dưới dạng cho người dùng.

Tải khoá S/MIME lên

Sử dụng phương thức smimeInfo.insert() để tải khoá S/MIME mới lên cho một bí danh thuộc về người dùng. Bạn xác định bí danh mục tiêu bằng các tham số sau:

userId
Địa chỉ email của người dùng. Bạn có thể sử dụng giá trị đặc biệt me để cho biết người dùng đang được xác thực.
sendAsEmail
Email đại diện mà bạn đang tải khoá lên. Đây là địa chỉ email xuất hiện trong tiêu đề "Từ:" cho thư được gửi bằng bí danh này.

Chứng chỉ S/MIME và khoá riêng tư phải hiển thị trong trường pkcs12 ở định dạng đó; không được đặt trường nào khác trong yêu cầu. Trường PKCS12 dự kiến sẽ chứa cả khoá S/MIME của người dùng và chuỗi chứng chỉ ký. API sẽ thực hiện các quy trình xác thực tiêu chuẩn trên trường này trước khi chấp nhận, xác minh những thông tin sau:

  • Tiêu đề khớp với địa chỉ email đã chỉ định.
  • Các ngày hết hạn hợp lệ.
  • Tổ chức phát hành chứng chỉ (CA) nằm trong danh sách đáng tin cậy của chúng tôi.
  • Chứng chỉ phù hợp với giới hạn kỹ thuật của Gmail.

Nếu khoá được mã hoá thì mật khẩu phải nằm trong trường encryptedKeyPassword. Các lệnh gọi insert() thành công sẽ trả về mã nhận dạng của smimeInfo có thể dùng để tham chiếu đến khoá trong tương lai.

Liệt kê khoá S/MIME của người dùng

Sử dụng phương thức smimeInfo.list() để trả về danh sách khoá S/MIME cho người dùng đã cho đối với bí danh đã cho. Bạn xác định bí danh mục tiêu bằng các tham số sau:

userId
Địa chỉ email của người dùng. Bạn có thể sử dụng giá trị đặc biệt me để cho biết người dùng đang được xác thực.
sendAsEmail
Tên đại diện liệt kê các khoá. Đây là địa chỉ email xuất hiện trong tiêu đề "Từ:" cho thư được gửi bằng bí danh này.

Truy xuất khoá S/MIME cho email đại diện

Sử dụng phương thức smimeInfo.get() để trả về các khoá S/MIME cụ thể cho một email đại diện cụ thể để gửi cho người dùng. Bạn xác định bí danh mục tiêu bằng các tham số sau:

userId
Địa chỉ email của người dùng. Bạn có thể sử dụng giá trị đặc biệt me để cho biết người dùng đang được xác thực.
sendAsEmail
Bí danh mà bạn đang truy xuất các khoá. Đây là địa chỉ email xuất hiện trong tiêu đề "Từ:" cho thư được gửi bằng bí danh này.

Xoá khoá S/MIME

Sử dụng phương thức smimeInfo.delete() để xoá khoá S/MIME đã chỉ định khỏi một bí danh. Bạn xác định bí danh mục tiêu bằng các tham số sau:

userId
Địa chỉ email của người dùng. Bạn có thể sử dụng giá trị đặc biệt me để cho biết người dùng đang được xác thực.
sendAsEmail
Bí danh mà bạn đang truy xuất các khoá. Đây là địa chỉ email xuất hiện trong tiêu đề "Từ:" của thư được gửi bằng bí danh này.
id
Mã nhận dạng bất biến của SmimeInfo.

Đặt khoá S/MIME mặc định cho email đại diện

Sử dụng phương thức smimeInfo.setDefault() để đánh dấu khoá S/MIME đã chỉ định làm khoá mặc định cho bí danh đã chỉ định. Bạn xác định bí danh mục tiêu bằng các tham số sau:

userId
Địa chỉ email của người dùng. Bạn có thể sử dụng giá trị đặc biệt me để cho biết người dùng đang được xác thực.
sendAsEmail
Bí danh mà bạn đang truy xuất các khoá. Đây là địa chỉ email xuất hiện trong tiêu đề "Từ:" của thư được gửi bằng bí danh này.
id
Mã nhận dạng bất biến của SmimeInfo.

Mã mẫu

Các mã mẫu sau đây minh hoạ cách sử dụng API để quản lý chứng chỉ S/MIME cho tổ chức có nhiều người dùng.

Tạo tài nguyên SmimeInfo cho chứng chỉ S/MIME

Mã mẫu sau đây minh hoạ cách đọc một chứng chỉ từ tệp, mã hoá thành một chuỗi base64url và gán chứng chỉ đó cho trường pkcs12 của tài nguyên 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/đoạn mã smime/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"))

Đang tải chứng chỉ S/MIME lên

Để tải một chứng chỉ lên, hãy gọi smimeInfo.insert và cung cấp tài nguyên smimeInfo trong phần nội dung của yêu cầu:

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/đoạn mã smime/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()

Ví dụ về việc quản lý nhiều chứng chỉ của người dùng

Bạn có thể muốn quản lý chứng chỉ cho nhiều người dùng trong tổ chức cùng một lúc. Các ví dụ sau đây cho thấy cách quản lý chứng chỉ cho nhiều người dùng trong một lệnh gọi hàng loạt.

Chèn chứng chỉ từ tệp CSV

Giả sử bạn có tệp CSV liệt kê mã nhận dạng người dùng và đường dẫn đến chứng chỉ của từng người dùng:

$ 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

Bạn có thể sử dụng các lệnh gọi createSmimeInfoinsertSmimeInfo từ trước để tải các chứng chỉ lên như được chỉ định trong tệp 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

Bạn có thể sử dụng các lệnh gọi create_smime_infoinsert_smime_info từ trước để tải các chứng chỉ lên như được chỉ định trong tệp CSV:

gmail/snippet/smime snippet/insert_certification_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")

Quản lý chứng chỉ

Ví dụ này kết hợp một số lệnh gọi từ API smimeInfo để cho biết cách bạn có thể quản lý các chứng chỉ cho tổ chức của mình. Trình phân tích cú pháp liệt kê các chứng chỉ cho người dùng và nếu chứng chỉ mặc định đã hết hạn hoặc chưa được đặt, thì chứng chỉ này sẽ tải lên chứng chỉ có trong tệp đã chỉ định. Sau đó, phương thức này sẽ đặt chứng chỉ có thời hạn xa nhất trong tương lai làm mặc định.

Sau đó, hàm này sẽ được gọi từ một hàm xử lý tệp CSV như trong ví dụ trước.

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/đoạn mã smime/update_smime_certification.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,
  )