DEV Community

GeorgeGcs
GeorgeGcs

Posted on

【HarmonyOS 5】Detailed Guide to Sensitive Information Local Storage

【HarmonyOS 5】Detailed Guide to Sensitive Information Local Storage

##HarmonyOS Development Capabilities ##HarmonyOS SDK Application Services##HarmonyOS Financial Applications (Financial Management#

Preface

HarmonyOS already ensures the security of user sensitive information through multi-layered security mechanisms. However, on this basis, third-party applications often need to further encrypt sensitive user information for local storage.

This article will expand on HarmonyOS's inherent security mechanisms and finally explain common solutions for local storage of sensitive information.

一、Hardware-Level Security Isolation and Encryption

Trusted Execution Environment (TEE)

TEE, as an independent secure area, is isolated from the main operating system and is used to store core sensitive data such as encryption keys and biometric templates. For example, user fingerprint information is verified within TEE to prevent man-in-the-middle attacks.

  • Key Management: Key generation, storage, and usage are all completed within TEE. For example, AES encryption keys are generated by a hardware random number generator and stored in TEE's secure storage area to ensure keys are not exposed to the main system.

Full Disk Encryption (FDE)

All data stored on the device is encrypted by default, including user files and application data. Even if the device is lost or cracked, attackers cannot directly read the original data.

  • Dynamic Encryption: Data is real-time encrypted when written to storage media and automatically decrypted when read, transparent to the user.

二、Software-Level Security Mechanisms

Sandbox Isolation

Each application has an exclusive sandbox directory (/data/data/), which cannot be directly accessed by other applications. For example, a bank application's transaction records stored in the sandbox cannot be read by a social application.

  • Path Isolation: Applications can only access files within their own sandbox; system files and other application data are strictly restricted.

Data Encryption and Key Management

Symmetric Encryption

Uses the AES algorithm to encrypt local files, databases, etc. For example, user chat records are encrypted and stored using AES-256, with keys managed by TEE.

Asymmetric Encryption

Used for key exchange and digital signatures. For example, when an application synchronizes data across devices, it uses RSA to encrypt session keys to ensure transmission security.

Full Lifecycle Key Management

Key generation, distribution, update, and destruction are uniformly managed by the system. For example, encryption keys are rotated regularly to reduce leakage risks.

Dynamic Permission Management

Principle of Least Privilege

Applications can only apply for necessary permissions. For example, when a map application requests location permission, the system defaults to recommending a blurred location (1km accuracy) instead of precise location.

Real-time Permission Monitoring

When a background application abnormally calls the camera or microphone, the system triggers a "privacy shield" to intercept and notify the user.

  • Permission Transparency: Users can view the application's 24-hour device usage records in the control center, including camera and microphone activation duration.

三、Privacy Enhancement Technologies

Privacy Space

Independent Encrypted Storage

Users can create a privacy space accessed via fingerprint or password to store highly sensitive data (such as ID cards and bank card information). The privacy space is completely isolated from the main space, with data encrypted and stored.

Hidden Entry

The privacy space entry can be hidden and only activated via a specific fingerprint or password, enhancing concealment.

Secure Erasure

Physical Destruction

When data is deleted, the system uses secure erasure technology (such as multiple overwrites) to ensure data cannot be recovered. For example, after a user deletes chat records, the storage block is overwritten with random data.

Cloud Synchronized Erasure

When a device is lost, users can remotely erase local data through the "Find Device" function to prevent leakage.

四、Distributed Security and Compliance

Cross-Device Data Synchronization

Encrypted Transmission

Data is encrypted using the TLS protocol when synchronized between devices. For example, when contacts are synchronized between a phone and tablet, data is transmitted via SSL encryption.

Device Security Level Matching

Based on device security levels (e.g., phone as SL2, watch as SL1), it restricts the synchronization of data security labels. For example, a watch cannot synchronize confidential-level data.

五、Developer Solutions for Local Sensitive Information Storage

In summary, HarmonyOS constructs an end-to-end sensitive information protection system through multi-dimensional security mechanisms such as hardware isolation, encryption technology, dynamic permissions, and privacy spaces. Its core design philosophy is "least privilege, deep isolation, hardware encryption, and user control," ensuring the security and privacy of user data during storage, transmission, and usage. Developers can easily implement applications that meet the highest security standards through the security APIs and toolchain provided by the system.

1. Encrypt Data Using System Encryption Libraries

HarmonyOS provides encryption and decryption modules supporting algorithms such as AES and RSA. For details, refer to the official documentation: Encryption/Decryption Introduction and Algorithm Specifications.

2. Complete DEMO for Encrypting User IDs Using National Cryptography SM2

The financial industry generally implements encryption through national cryptography or third-party encryption SDKs. The operation logic is consistent with the following example, which uses SM2 encryption combined with preference storage to encrypt and decrypt user IDs locally. This DEMO generates an SM2 key pair, encrypts the user ID with the public key and stores it in preferences, then decrypts the encrypted data using the private key:

import { preferences } from '@ohos.data.preferences';
import { BusinessError } from '@ohos.base';
import { huks } from '@ohos.security.huks';
import { util } from '@ohos.util';
import { common } from '@ohos.app.ability';

// Preference file name
const PREFERENCES_NAME = 'user_id_storage';

// Encryption algorithm enumeration
enum EncryptionAlgorithm {
  SM2 = 'SM2',
  // More algorithms can be added as needed
}

/**
 * Encryption utility class
 */
class EncryptionUtils {
  private keyAlias: string;

  constructor(keyAlias: string) {
    this.keyAlias = keyAlias;
  }

  /**
   * Generate encryption key
   * @param algorithm Encryption algorithm
   */
  async generateKey(algorithm: EncryptionAlgorithm) {
    let properties: Array<huks.HuksParam>;
    switch (algorithm) {
      case EncryptionAlgorithm.SM2:
        properties = [
          {
            tag: huks.HuksTag.ALGORITHM,
            value: huks.HuksKeyAlg.SM2
          },
          {
            tag: huks.HuksTag.KEY_SIZE,
            value: huks.HuksKeySize.SM2_256
          },
          {
            tag: huks.HuksTag.PURPOSE,
            value: huks.HuksKeyPurpose.ENCRYPT | huks.HuksKeyPurpose.DECRYPT
          }
        ];
        break;
      default:
        throw new Error(`Unsupported algorithm: ${algorithm}`);
    }
    const options: huks.HuksOptions = {
      properties
    };
    await huks.generateKeyItem(this.keyAlias, options)
      .then((data) => {
        console.info(`Generate ${algorithm} key success, data = ${JSON.stringify(data)}`);
      })
      .catch((error: Error) => {
        console.error(`Generate ${algorithm} key failed, ${JSON.stringify(error)}`);
        throw error;
      });
  }

  /**
   * Encrypt data
   * @param data Data to be encrypted
   * @param algorithm Encryption algorithm
   * @returns Encrypted data
   */
  async encrypt(data: string, algorithm: EncryptionAlgorithm): Promise<string> {
    let properties: Array<huks.HuksParam>;
    switch (algorithm) {
      case EncryptionAlgorithm.SM2:
        properties = [
          {
            tag: huks.HuksTag.ALGORITHM,
            value: huks.HuksKeyAlg.SM2
          },
          {
            tag: huks.HuksTag.KEY_SIZE,
            value: huks.HuksKeySize.SM2_256
          },
          {
            tag: huks.HuksTag.PURPOSE,
            value: huks.HuksKeyPurpose.ENCRYPT
          },
          {
            tag: huks.HuksTag.DIGEST,
            value: huks.HuksKeyDigest.SM3
          }
        ];
        break;
      default:
        throw new Error(`Unsupported algorithm: ${algorithm}`);
    }
    const options: huks.HuksOptions = {
      properties,
      inData: new Uint8Array(data.split('').map(c => c.charCodeAt(0)))
    };
    let handleObj = await huks.initSession(this.keyAlias, options)
    const result = await huks.finishSession(handleObj.handle, options)
      .catch((error: Error) => {
        console.error(`Finish ${algorithm} encryption session failed: ${JSON.stringify(error)}`);
        throw error;
      });

    const base64Helper = new util.Base64Helper();
    const retStr = base64Helper.encodeToStringSync(result.outData as Uint8Array);
    return retStr;
  }

  /**
   * Decrypt data
   * @param encryptedData Encrypted data
   * @param algorithm Encryption algorithm
   * @returns Decrypted data
   */
  async decrypt(encryptedData: string, algorithm: EncryptionAlgorithm): Promise<string> {
    let properties: Array<huks.HuksParam>;
    switch (algorithm) {
      case EncryptionAlgorithm.SM2:
        properties = [
          {
            tag: huks.HuksTag.ALGORITHM,
            value: huks.HuksKeyAlg.SM2
          },
          {
            tag: huks.HuksTag.KEY_SIZE,
            value: huks.HuksKeySize.SM2_256
          },
          {
            tag: huks.HuksTag.PURPOSE,
            value: huks.HuksKeyPurpose.DECRYPT
          },
          {
            tag: huks.HuksTag.DIGEST,
            value: huks.HuksKeyDigest.SM3
          }
        ];
        break;
      default:
        throw new Error(`Unsupported algorithm: ${algorithm}`);
    }
    const base64Helper = new util.Base64Helper();
    const inData = base64Helper.decodeSync(encryptedData);
    const options: huks.HuksOptions = {
      properties,
      inData
    };
    let handleObj = await huks.initSession(this.keyAlias, options)
    const result = await huks.finishSession(handleObj.handle, options)
      .catch((error: Error) => {
        console.error(`Finish ${algorithm} decryption session failed: ${JSON.stringify(error)}`);
        throw error;
      });

    const retStr = base64Helper.encodeToStringSync(result.outData as Uint8Array);
    return retStr;
  }
}

/**
 * Preference utility class
 */
class PreferencesUtils {
  private preFs: preferences.Preferences | null = null;
  private context: common.UIAbilityContext;

  constructor(context: common.UIAbilityContext) {
    this.context = context;
  }

  /**
   * Initialize preference instance
   */
  async init() {
    const options: preferences.Options = { name: PREFERENCES_NAME };
    this.preFs = await preferences.getPreferences(this.context, options);
  }

  /**
   * Store data
   * @param key Key
   * @param value Value
   */
  async put(key: string, value: string) {
    await this.preFs?.put(key, value)
      .then(() => console.info(`Data ${key} stored successfully`))
      .catch((err: BusinessError) => {
        console.error(`Storage failed: ${err.code}, ${err.message}`);
      });
    await this.preFs?.flush();
  }

  /**
   * Read data
   * @param key Key
   * @returns Value or null
   */
  async get(key: string): Promise<preferences.ValueType> {
    const res = await this.preFs?.get(key, 'default') || "";
    return res;
  }
}
Enter fullscreen mode Exit fullscreen mode

Key Considerations for Sensitive Information Storage

  1. Key Management Best Practices:

    • Never hardcode keys in code; use TEE or secure storage provided by the system.
    • Implement key rotation policies (e.g., update keys quarterly).
  2. Encryption Algorithm Selection:

    • For financial applications, use national cryptography algorithms (SM2, SM4) or industry-standard AES-256.
    • Avoid using outdated algorithms (e.g., DES).
  3. Data Classification and Protection:

    • Classify data by sensitivity (confidential, private, public) and apply different encryption policies.
    • Do not store plaintext sensitive data (e.g., credit card numbers, ID cards).
  4. Compliance and Audit:

    • Comply with local data protection regulations (e.g., GDPR, China's Personal Information Protection Law).
    • Log encryption/decryption operations for audit purposes, ensuring non-repudiation.

By combining HarmonyOS's native security mechanisms with proper encryption practices, developers can build a robust sensitive information protection system that balances security and user experience.

Top comments (0)