DEV Community

HarmonyOS
HarmonyOS

Posted on

Enabling Secure and Flexible Password Generation in the Application

Read the original article:Enabling Secure and Flexible Password Generation in the Application

Requirement Description

User wants to generate strong, random, and customizable passwords directly from the application. The password generator should allow the user to define specific preferences such as including numbers, uppercase letters, and special characters. The generated password must be long enough and complex enough to resist brute-force and dictionary attacks. Users should also be able to adjust the password length according to their needs, for example shorter passwords for temporary use cases and longer, highly secure ones for sensitive accounts. The feature should work instantly and reliably without requiring external dependencies, ensuring that users can quickly produce secure passwords when creating or updating login credentials.

Background Knowledge

HarmonyOS provides the CryptoArchitectureKit, which includes cryptographically secure random number generation APIs. These APIs are designed to produce unpredictable values that meet modern security standards and can be used as a foundation for generating strong passwords. Unlike standard pseudo-random number generators, cryptographically secure randomness cannot be easily predicted or reproduced, which is essential for password generation. Strong passwords typically combine multiple character sets (letters, numbers, special symbols) and sufficient length to increase entropy and make attacks computationally infeasible. By leveraging the CryptoArchitectureKit, developers can implement a password generator that is both secure and efficient, while giving users flexibility to adapt the generated passwords to various application requirements and system policies.

Implementation Steps

  • Added a new page StrongPasswordGenerator.ets to the project.
  • Implemented UI elements for user preferences: checkboxes for numbers, special characters, and uppercase letters, plus a text input for password length.
  • Used CryptoArchitectureKit (cryptoFramework.createRandom()) to generate cryptographically secure random bytes.
  • Mapped random output to selected character sets to build the final password string.
  • Displayed the generated password in the UI and added validation to limit the length to 12 characters.

Code Snippet / Configuration

This method generates a cryptographically secure random password based on user preferences.

  • It creates a random number generator using CryptoArchitectureKit.
  • Uses a seed and generates random bytes of the desired length (default 6 if not specified).
  • Builds a character set depending on user selections (lowercase letters by default, plus uppercase, numbers, and special characters if enabled).
  • Maps each random byte to one character from the set and joins them into a string.
  • Finally, it assigns the generated password to this.randomValue so it can be displayed in the UI.
  async doRand() {
    let rand = cryptoFramework.createRandom();
    let seed = new Uint8Array([1, 2, 3]);
    rand.setSeed({ data: seed });

    let len = this.digitNumber > 0 ? this.digitNumber : 6;
    let randOutput = await rand.generateRandom(len);

    let chars = 'abcdefghijklmnopqrstuvwxyz';
    if (this.upperCaseSensitivity) {
      chars += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    }
    if (this.includeNumber) {
      chars += '0123456789';
    }
    if (this.includeSpecialChar) {
      chars += '!@#$%^&*()?' ;
    }
    let password = Array.from(randOutput.data)
      .map(n => chars[n % chars.length])
      .join('');
    this.randomValue = password;
  }
Enter fullscreen mode Exit fullscreen mode
  • Creates the UI layout for the Strong Password Generator page.
  • Contains three checkboxes so the user can choose whether to include special characters, numbers, and uppercase letters.
  • Has a text input to let the user define the password length.
  • Provides a “Generate” button that calls doRand() to create a random password.
  • Displays the generated password (or a warning if length > 12).
  • Uses Column and Row layouts to structure the UI, with padding and alignment.
// Example UI elements in StrongPasswordGenerator
Checkbox({ name: 'includeNumber' })
  .onChange((value: boolean) => this.includeNumber = value)

TextInput({ placeholder: 'Password length' })
  .onChange((value: string) => this.digitNumber = parseInt(value))

Button('Generate')
  .onClick(async () => await this.doRand());
Enter fullscreen mode Exit fullscreen mode

Test Results

  • Passwords were successfully generated according to user preferences, including numbers, special characters, and uppercase letters.
  • Different lengths were tested, and the maximum length restriction of 12 characters worked as expected.
  • Each generated password was unique and cryptographically secure, demonstrating the reliability of the CryptoArchitectureKit.
  • The UI elements (checkboxes, input field, and button) responded correctly to user interactions.

cke_7929.gif

Limitations or Considerations

CryptoArchitectureKit, is not working on the previewer.

Related Documents or Links

https://developer.huawei.com/consumer/en/doc/harmonyos-references/capi-cryptoarchitecturekit

Written by Aycanur Ucar

Top comments (0)