Certificate Development

This topic walks you through on how to create a certificate object, obtain information about the certificate, and check the validity period of the certificate.

How to Develop

  1. Import the certFramework module.

    import certFramework from '@ohos.security.cert';
    
  2. Use cryptoCert.createX509Cert to create an X509Cert object based on the existing X.509 certificate data.

  3. Obtain certificate information.
    The following example shows how to obtain the certificate version and serial number. For more information, see X509Cert.

  4. Use X509Cert.getPublicKey to obtain the public key in the certificate and use X509Cert.verify to verify the signature. In this example, a self-signed certificate is used. Therefore, the public key in the certificate is obtained. In your app experience, obtain the public key for signature verification based on actual situation.

  5. Use X509Cert.checkValidityWithDate to check the certificate validity period. The input parameter date is used to check whether the specified date is within the validity period of the X.509 certificate.

import certFramework from '@ohos.security.cert';
import { BusinessError } from '@ohos.base';
import util from '@ohos.util'; 

// The following is an example of the certificate binary data, which varies with the service.
let certData = '-----BEGIN CERTIFICATE-----\n' +
  'MIIBLzCB1QIUO/QDVJwZLIpeJyPjyTvE43xvE5cwCgYIKoZIzj0EAwIwGjEYMBYG\n' +
  'A1UEAwwPRXhhbXBsZSBSb290IENBMB4XDTIzMDkwNDExMjAxOVoXDTI2MDUzMDEx\n' +
  'MjAxOVowGjEYMBYGA1UEAwwPRXhhbXBsZSBSb290IENBMFkwEwYHKoZIzj0CAQYI\n' +
  'KoZIzj0DAQcDQgAEHjG74yMIueO7z3T+dyuEIrhxTg2fqgeNB3SGfsIXlsiUfLTa\n' +
  'tUsU0i/sePnrKglj2H8Abbx9PK0tsW/VgqwDIDAKBggqhkjOPQQDAgNJADBGAiEA\n' +
  '0ce/fvA4tckNZeB865aOApKXKlBjiRlaiuq5mEEqvNACIQDPD9WyC21MXqPBuRUf\n' +
  'BetUokslUfjT6+s/X4ByaxycAA==\n' +
  '-----END CERTIFICATE-----\n';

// Certificate example.
function certSample(): void {
  let textEncoder = new util.TextEncoder();
  let encodingBlob: certFramework.EncodingBlob = {
    // Convert the certificate data from a string to a Unit8Array.
    data: textEncoder.encodeInto(certData),
    // Certificate format. Only PEM and DER are supported. In this example, the certificate is in PEM format.
    encodingFormat: certFramework.EncodingFormat.FORMAT_PEM
  };

  // Create an X509Cert object.
  certFramework.createX509Cert(encodingBlob, (err, x509Cert) => {
    if (err != null) {
      // The X509Cert object fails to be created.
      console.error(`createX509Cert failed, errCode:${err.code}, errMsg:${err.message}`);
      return;
    }
    // The X509Cert object is created.
    console.log('createX509Cert success');

    // Obtain the certificate version.
    let version = x509Cert.getVersion();
    let serial = x509Cert.getCertSerialNumber();
    console.log(`X509 version: ${version} , X509 serial:${serial}`);

    // Use the getPublicKey() method of the upper-level certificate object or the self-signed certificate object to obtain the public key object.
    try {
      let pubKey = x509Cert.getPublicKey();
      // Verify the certificate signature.
      x509Cert.verify(pubKey, (err, data) => {
        if (err == null) {
          // Signature verification is successful.
          console.log('verify success');
        } else {
          // Signature verification fails.
          console.error(`verify failed, errCode: ${err.code} , errMsg:${err.message}`);
        }
      });
    } catch (error) {
      let e: BusinessError = error as BusinessError;
      console.error(`getPublicKey failed, errCode: ${e.code} , errMsg:${e.message}`);
    }

    // Use a string to represent the date.
    let date = '20230930000001Z';

    // Check the validity period of the certificate.
    try {
      x509Cert.checkValidityWithDate(date);
    } catch (error) {
      let e: BusinessError = error as BusinessError;
      console.error(`checkValidityWithDate failed, errCode: ${e.code}, errMsg:${e.message}`);
    }
  });
}