DEV Community

HarmonyOS
HarmonyOS

Posted on

Encrypting Local Data in ArkTS

Read the original article:Encrypting Local Data in ArkTS

In modern application development, particularly on platforms like HarmonyOS NEXT, securing user data is a critical aspect of delivering trustworthy and compliant applications.

Introduction

When developing modern mobile applications, securing user data is not just a best practice — it’s a necessity. Whether it’s user credentials, tokens, or preferences, leaving sensitive data unencrypted can lead to serious security breaches. In this article, we’ll explore how to encrypt local data in ArkTS applications using the HarmonyOS NEXTcryptoFramework.

By the end of this article, you’ll know how to encrypt and decrypt local data safely and implement secure storage in your HarmonyOS NEXT apps.

Local Storage in ArkTS: The Security Challenge

ArkTS provides several mechanisms to store local data:

Storage TypeEncrypted by DefaultTypical Use Cases@LocalStorage / @AppStorage❌ NoUI-bound state, preferencesFile System APIs❌ NoStructured data, local filesKey-Value Storage❌ NoConfig files, session state

By default, these mechanisms do not encrypt data at rest. To meet security standards, manual encryption is essential before saving sensitive information.

🔐 Choosing the Right Encryption Strategy

To protect local data in ArkTS:

  • Use HarmonyOS NEXT CryptoFramework (or permitted 3rd-party libraries).
  • Store encryption keys securely using KeyStore or secure hardware.
  • Encrypt data before saving, and decrypt it when retrieving.
  • Avoid hardcoded keys and plain text storage.

🧪 Implementation Example: Encrypting a Token

Let’s walk through a real-world implementation of AES encryption using cryptoFramework.

  • Import Modules
import cryptoFramework from '@ohos.security.cryptoFramework';
import { Logger } from '@ohos.hilog';
Enter fullscreen mode Exit fullscreen mode
  • Full Example Code
@Entry
@Component
struct EncryptExample {
@State encryptedData: string = '';

aboutToAppear() {
this.encryptAndStoreData('mySensitiveToken123');
}

private async encryptAndStoreData(data: string) {
try {
const keyAlias = 'MyAESKey';
const aesKey = await cryptoFramework.generateKey({
algorithm: 'AES',
keySize: 256,
alias: keyAlias
});

const encrypted = await cryptoFramework.encrypt({
algorithm: 'AES',
keyAlias: keyAlias,
data: data
});

this.encryptedData = encrypted;
Logger.info('EncryptExample', `Encrypted data: ${encrypted}`);

// Store encrypted data
LocalStorage.setItem('secureToken', encrypted);

} catch (err) {
Logger.error('EncryptExample', `Encryption error: ${JSON.stringify(err)}`);
}
}

private async decryptData() {
try {
const keyAlias = 'MyAESKey';
const encrypted = LocalStorage.getItem('secureToken');

const decrypted = await cryptoFramework.decrypt({
algorithm: 'AES',
keyAlias: keyAlias,
data: encrypted
});

Logger.info('EncryptExample', `Decrypted data: ${decrypted}`);
} catch (err) {
Logger.error('EncryptExample', `Decryption error: ${JSON.stringify(err)}`);
}
}

build() {
Column() {
Text(`Encrypted: ${this.encryptedData}`).padding(16)
Button('Decrypt and Log').onClick(() => this.decryptData())
}
}
}
Enter fullscreen mode Exit fullscreen mode

⚠️ Limitations and Considerations

  • Key storage: Use KeyStore or secure hardware. Never store keys in plain text.
  • Performance: Encryption adds overhead. Only encrypt what is necessary.
  • Logging: Never log raw sensitive data.
  • Lifecycle: Ensure encryption/decryption are tested across app lifecycle events.

✅ Good Practices

PracticeRecommendationKey HandlingStore in KeyStore or hardware-backed vaultEncryption ScopeOnly encrypt sensitive fieldsFallback HandlingManage key loss gracefully LoggingAvoid logging sensitive or decrypted data

Conclusion

Storing local data securely in ArkTS apps is achievable and essential. By using the HarmonyOS NEXT cryptoFramework, developers can build applications that respect user privacy and align with modern security standards. Whether you're storing tokens, settings, or credentials, encrypting local data should be a default practice, not an afterthought.

📚 References

Crypto Framework
Security

Written by Zulfu Balkan

Top comments (0)