ohos.security.crypto_framework (Cryptographic Algorithm Library Framework)

Note:

Currently in the beta phase.

Provides a unified cryptographic algorithm library interface for encryption and decryption operations, shielding the underlying hardware and algorithm libraries.

Import Module

import kit.CryptoArchitectureKit.*

Usage Instructions

API example code usage instructions:

  • If the first line of example code contains a "// index.cj" comment, it indicates that the example can be compiled and run in the "index.cj" file of the Cangjie template project.
  • If the example requires obtaining the Context application context, it needs to be configured in the "main_ability.cj" file of the Cangjie template project.

For details about the example project and configuration template mentioned above, refer to Cangjie Example Code Instructions.

func createCipher(String)

public func createCipher(transformation: String): Cipher

Description: Obtains a corresponding Cipher instance by specifying the algorithm name.

For supported specifications, see Symmetric Key Encryption/Decryption Algorithm Specifications and Asymmetric Key Encryption/Decryption Algorithm Specifications.

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22

Parameters:

Parameter Name Type Mandatory Default Value Description
transformation String Yes - Combination of the algorithm name (including key length), encryption mode, and padding method for the Cipher to be generated.

Return Value:

Type Description
Cipher Returns the encryption/decryption generator object.

Exceptions:

Example:

// index.cj

import kit.CryptoArchitectureKit.*
import ohos.business_exception.BusinessException
import kit.PerformanceAnalysisKit.Hilog

try {
    let cipherAlgName = "3DES192|ECB|PKCS7"
    let cipher = createCipher(cipherAlgName)
} catch (e: BusinessException) {
    Hilog.info(0, "test", "${e.message}")
}

func createMac(String)

public func createMac(algName: String): Mac

Description: Generates a Mac instance for message authentication code calculation and operations.

System Capability: SystemCapability.Security.CryptoFramework.Mac

Since: 22

Parameters:

Parameter Name Type Mandatory Default Value Description
algName String Yes - Specifies the digest algorithm.

Return Value:

Type Description
Mac Returns the Mac object generated by the specified input algorithm.

Exceptions:

Example:

// index.cj

import kit.CryptoArchitectureKit.*
import ohos.business_exception.BusinessException
import kit.PerformanceAnalysisKit.Hilog

try {
    var mac = createMac("SHA256")
} catch (e: BusinessException) {
    Hilog.info(0, "test", "${e.message}")
}

func createMd(String)

public func createMd(algName: String): Md

Description: Generates an Md instance for message digest calculation and operations.

System Capability: SystemCapability.Security.CryptoFramework.MessageDigest

Since: 22

Parameters:

Parameter Name Type Mandatory Default Value Description
algName String Yes - Specifies the digest algorithm.

Return Value:

Type Description
Md Returns the Md object generated by the specified input algorithm.

Exceptions:

Example:

// index.cj

import kit.CryptoArchitectureKit.*
import ohos.business_exception.BusinessException
import kit.PerformanceAnalysisKit.Hilog

try {
    let md = createMd("SHA256")
} catch (e: BusinessException) {
    Hilog.info(0, "test", "${e.message}")
}

func createRandom()

public func createRandom(): Random

Description: Generates a Random instance for random number calculation and seed setting.

System Capability: SystemCapability.Security.CryptoFramework.Rand

Since: 22

Return Value:

Type Description
Random Returns the Random object generated by the specified input algorithm.

Exceptions:

Example:

// index.cj

import kit.CryptoArchitectureKit.*
import ohos.business_exception.BusinessException
import kit.PerformanceAnalysisKit.Hilog

try {
    let rand = createRandom()
} catch (e: BusinessException) {
    Hilog.info(0, "test", "${e.message}")
}

func createSymKeyGenerator(String)

public func createSymKeyGenerator(algName: String): SymKeyGenerator

Description: Obtains a symmetric key generator instance by specifying the algorithm name string.

For supported specifications, see Symmetric Key Generation and Conversion Specifications.

System Capability: SystemCapability.Security.CryptoFramework.Key.SymKey

Since: 22

Parameters:

Parameter Name Type Mandatory Default Value Description
algName String Yes - Algorithm name of the symmetric key generator to be generated. For specific values, see the "String Parameters" section in Symmetric Key Generation and Conversion Specifications.

Return Value:

Type Description
SymKeyGenerator Returns the symmetric key generator object.

Exceptions:

  • BusinessException: For corresponding error codes, see Universal Error Codes.

    Error Code ID Error Message
    801 This operation is not supported.

Example:

// index.cj

import kit.CryptoArchitectureKit.*
import ohos.business_exception.BusinessException
import kit.PerformanceAnalysisKit.Hilog

try {
    let symKeyGenerator = createSymKeyGenerator("3DES192")
} catch (e: BusinessException) {
    Hilog.info(0, "test", "${e.message}")
}

interface Key

public interface Key {
    prop format: String
    prop algName: String
    func getEncoded(): DataBlob
}

Description: Key (interface). Its subclass objects need to be generated in advance when running cryptographic algorithms (such as encryption/decryption) and passed into the createCipher(String) method of the Cipher instance.

Keys can be generated by key generators.

System Capability: SystemCapability.Security.CryptoFramework.Key

Since: 22

prop algName

prop algName: String

Description: Algorithm name (including length) corresponding to the key.

Type: String

Read/Write Attribute: Read-only

System Capability: SystemCapability.Security.CryptoFramework.Key

Since: 22

prop format

prop format: String

Description: Format of the key.

Type: String

Read/Write Attribute: Read-only

System Capability: SystemCapability.Security.CryptoFramework.Key

Since: 22

func getEncoded()

func getEncoded(): DataBlob

Description: Synchronous method to obtain the byte stream of key data. The key can be a symmetric key, public key, or private key. The public key format complies with ASN.1 syntax, X.509 specification, and DER encoding format. The private key format complies with ASN.1 syntax, PKCS#8 specification, and DER encoding method.

Note:

When generating a private key using key parameters in RSA algorithm, the private key object does not support getEncoded.

System Capability: SystemCapability.Security.CryptoFramework.Key

Since: 22

Return Value:

Type Description
DataBlob Used to view the specific content of the key.

Example:

// index.cj

import kit.CryptoArchitectureKit.*
import ohos.business_exception.BusinessException
import kit.PerformanceAnalysisKit.Hilog

try {
    let generator = createSymKeyGenerator("3DES192") // The key is generated by a key generator. The generation process is omitted here.
    let key = generator.generateSymKey()
    let encodedKey = key.getEncoded()
} catch (e: BusinessException) {
    Hilog.info(0, "test", "${e.message}")
}

class ParamsSpec

public class ParamsSpec {
    mut prop algName: String
    mut prop iv: DataBlob
}

Description: Encryption/decryption parameters. Its subclass objects need to be constructed during symmetric encryption/decryption and passed into the createCipher(String) method.

Applies to symmetric encryption/decryption modes that require parameters such as iv (for modes without parameters such as iv, like ECB mode, no construction is needed; pass None in createCipher(String)).

Note:

Since the params parameter of createCipher(String) is of type ParamsSpec (parent class), but the actual requirement is to pass a specific subclass object (such as IvParamsSpec), the algName parameter of the parent class ParamsSpec should be set when constructing the subclass object, so that the algorithm library knows which subclass object is passed during init().

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22

var algName

mut var algName: String

Description: Indicates the algorithm mode of symmetric encryption/decryption parameters. Optional values are as follows:
- IvParamsSpec: Applicable to CBCMagIc_StrINgCTRMagIc_StrINgOFBMagIc_StrINgCFB mode.
- GcmParamsSpec: Applicable to GCM mode.
- CcmParamsSpec: Applicable to CCM mode.

Type: String

Read/Write Attribute: Read/Write

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22## class Cipher

public class Cipher {}

Function: Provides cryptographic algorithm operations. By sequentially calling the createCipher(String), update(), and doFinal() methods in this class, symmetric encryption/decryption and asymmetric encryption/decryption can be achieved.

A complete encryption/decryption process differs slightly between symmetric and asymmetric encryption:

  • Symmetric Encryption/Decryption: init is mandatory, update is optional (and allows multiple updates for large data encryption/decryption), and doFinal is mandatory. After doFinal completes, a new encryption/decryption process can be initiated by calling init again.
  • RSA/SM2 Asymmetric Encryption/Decryption: init is mandatory, update is not supported, and doFinal is mandatory (allowing multiple consecutive doFinal calls for large data encryption/decryption). RSA does not support repeated init calls; switching encryption/decryption modes or padding schemes requires recreating a Cipher object.

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since Version: 22

prop algName

public prop algName: String

Function: The algorithm name specified by the cryptographic generator.

Type: String

Read-Write Capability: Read-only

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since Version: 22

func initialize(CryptoMode, Key, ?ParamsSpec)

public func initialize(opMode: CryptoMode, key: Key, params: ?ParamsSpec): Unit

Function: Initializes the cipher object for encryption/decryption, obtaining results via registered callback functions.

This function can only be used after creating a Cipher instance with createCipher.

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since Version: 22

Parameters:

Parameter Type Required Default Value Description
opMode CryptoMode Yes - Encryption or decryption mode.
key Key Yes - Specifies the key for encryption/decryption.
params ?ParamsSpec Yes - Specifies parameters for encryption/decryption. For algorithm modes like ECB that do not require parameters, None can be passed.

Exceptions:

  • BusinessException: Corresponding error codes are listed below. Refer to crypto framework error codes.

    Error Code ID Error Message
    17620001 Memory error.
    17620002 Runtime error.
    17630001 Cryptographic operation error.

Example:

// index.cj

import kit.CryptoArchitectureKit.*
import ohos.business_exception.BusinessException
import kit.PerformanceAnalysisKit.Hilog

try {
    let skg = createSymKeyGenerator("AES128")
    let sk = skg.convertKey(DataBlob([83, 217, 231, 76, 28, 113, 23, 219, 250, 71, 209, 210, 205, 97, 32, 159]))
    let encoder = createCipher("AES128|CBC|PKCS7")
    let ivBlob = DataBlob([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
    var ivParamsSpec = IvParamsSpec("IvParamsSpec", ivBlob)
    ivParamsSpec.algName = "IvParamsSpec"
    ivParamsSpec.iv = ivBlob
    encoder.initialize(CryptoMode.EncryptMode, sk, ivParamsSpec)
    let message = "This is a test"
    let blob = DataBlob(message.toArray())
    let encryptText = encoder.doFinal(blob)
} catch (e: BusinessException) {
    Hilog.info(0, "test", "${e.message}")
}

func doFinal(?DataBlob)

public func doFinal(data: ?DataBlob): DataBlob

Function:
(1) In symmetric encryption/decryption, doFinal encrypts/decrypts the remaining data (generated by block modes) and the data passed in this call, finalizing the operation and returning the result.

If the data volume is small, data can be passed in one go via doFinal without using update. If update has already been used in the current process, None can be passed for the data parameter in doFinal.

The output of doFinal varies by symmetric encryption/decryption mode:

  • For GCM and CCM symmetric encryption: The concatenated results of all update and doFinal calls yield "ciphertext + authTag," where the last 16 bytes (GCM) or 12 bytes (CCM) are the authTag, and the rest is ciphertext. (If data is None, doFinal returns only the authTag.) The authTag must be provided in GcmParamsSpec or CcmParamsSpec during decryption.
  • For other symmetric modes and GCM/CCM decryption: The concatenated results of all update and doFinal calls yield the complete plaintext/ciphertext.

(2) For RSA/SM2 asymmetric encryption/decryption, doFinal encrypts/decrypts the passed data. For large data, multiple doFinal calls can be made, with results concatenated to form the complete plaintext/ciphertext.

Note:

  • In symmetric operations, calling doFinal marks the end of a process, clearing the Cipher instance's state. To start a new process, init() must be called again with full parameters (e.g., even for the same Cipher instance and key, params must be provided for decryption if it was used in encryption).
  • If decryption fails, verify that the data and init parameters match, including whether the authTag from GCM encryption is correctly provided in GcmParamsSpec.
  • doFinal may return an empty result. Check .data for non-null values before accessing to avoid exceptions.

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since Version: 22

Parameters:

Parameter Type Required Default Value Description
data ?DataBlob Yes - Data to encrypt/decrypt. None is allowed, but {data: Array<UInt8>()} is not.

Return Value:

Type Description
DataBlob Returns the encrypted/decrypted result as DataBlob.

Exceptions:

  • BusinessException: Refer to crypto framework error codes.

    Error Code ID Error Message
    17620001 Memory error.
    17620002 Runtime error.
    17630001 Cryptographic operation error.

Example:

// index.cj  

import kit.CryptoArchitectureKit.*  
import ohos.business_exception.BusinessException  
import kit.PerformanceAnalysisKit.Hilog  

try {  
    let skg = createSymKeyGenerator("AES128")  
    let sk = skg.convertKey(DataBlob([83, 217, 231, 76, 28, 113, 23, 219, 250, 71, 209, 210, 205, 97, 32, 159]))  
    let encoder = createCipher("AES128|CBC|PKCS7")  
    let ivBlob = DataBlob([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])  
    var ivParamsSpec = IvParamsSpec("IvParamsSpec", ivBlob)  
    ivParamsSpec.algName = "IvParamsSpec"  
    ivParamsSpec.iv = ivBlob  
    encoder.initialize(CryptoMode.EncryptMode, sk, ivParamsSpec)  
    let message = "This is a test"  
    let blob = DataBlob(message.toArray())  
    let encryptText = encoder.doFinal(blob)  
} catch (e: BusinessException) {  
    Hilog.info(0, "test", "${e.message}")  
}  

func update(DataBlob)

public func update(data: DataBlob): DataBlob  

Function: Incrementally updates encryption/decryption operations, returning intermediate results.

This function can only be used after initializing a Cipher instance with createCipher(String).

Note:

  • For symmetric operations, if unfamiliar with block modes, check if update and doFinal results are non-empty and concatenate them to form complete ciphertext/plaintext. Block modes and specifications affect outputs.
    • ECB/CBC: Outputs are block-aligned. Unprocessed data is buffered until the next update/doFinal. doFinal pads remaining data per the padding scheme.
    • Stream-like modes may produce ciphertexts of the same length as plaintexts.
  • update is optional (direct doFinal is possible) or can be called multiple times. No size limits are imposed, but large data should use multiple update calls.
  • RSA/SM2 asymmetric operations do not support update.

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since Version: 22

Parameters:

Parameter Type Required Default Value Description
data DataBlob Yes - Data to encrypt/decrypt. {data: Array<UInt8>()} is invalid.

Return Value:

Type Description
DataBlob Returns the incremental result as DataBlob.

Exceptions:

  • BusinessException: Refer to crypto framework error codes.

    Error Code ID Error Message
    17620001 Memory error.
    17620002 Runtime error.
    17630001 Cryptographic operation error.

Example:

// index.cj  

import kit.CryptoArchitectureKit.*  
import ohos.business_exception.BusinessException  
import kit.PerformanceAnalysisKit.Hilog  

try {  
    let skg = createSymKeyGenerator("AES128")  
    let sk = skg.convertKey(DataBlob([83, 217, 231, 76, 28, 113, 23, 219, 250, 71, 209, 210, 205, 97, 32, 159]))  
    let cipher = createCipher("AES128|CBC|PKCS7")  
    let ivBlob = DataBlob([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])  
    var ivParamsSpec = IvParamsSpec("IvParamsSpec", ivBlob)  
    ivParamsSpec.algName = "IvParamsSpec"  
    ivParamsSpec.iv = ivBlob  
    cipher.initialize(CryptoMode.EncryptMode, sk, ivParamsSpec)  
    let plainText: DataBlob = DataBlob("this is test".toArray())  
    cipher.update(plainText)  
} catch (e: BusinessException) {  
    Hilog.info(0, "test", "${e.message}")  
}  

class Mac

public class Mac {}  

Function: The Mac class performs MAC (Message Authentication Code) computations. Instantiate via createMac.

System Capability: SystemCapability.Security.CryptoFramework.Mac

Since Version: 22

prop algName

public prop algName: String  

Function: The digest algorithm name.

Type: String

Read-Write Capability: Read-only

System Capability: SystemCapability.Security.CryptoFramework.Mac

Since Version: 22

func initialize(SymKey)

public func initialize(key: SymKey): Unit  

Function: Initializes Mac computation with a symmetric key, obtaining results via callbacks.

System Capability: SystemCapability.Security.CryptoFramework.Mac

Since Version: 22

Parameters:

Parameter Type Required Default Value Description
key SymKey Yes - Shared symmetric key.

Example:

// index.cj  

import kit.CryptoArchitectureKit.*  
import ohos.business_exception.BusinessException  
import kit.PerformanceAnalysisKit.Hilog  

try {  
    let skg = createSymKeyGenerator("AES128")  
    let sk = skg.generateSymKey()  
    let mac = createMac("SHA256")  
    mac.initialize(sk)  
} catch (e: BusinessException) {  
    Hilog.info(0, "test", "${e.message}")  
}  

func doFinal()

public func doFinal(): DataBlob  

Function: Returns the MAC computation result.

System Capability: SystemCapability.Security.CryptoFramework.Mac

Since Version: 22

Return Value:

Type Description
DataBlob The computed MAC as DataBlob.

Example:

// index.cj  

import kit.CryptoArchitectureKit.*  
import ohos.business_exception.BusinessException  
import kit.PerformanceAnalysisKit.Hilog  

try {  
    let mac = createMac("SHA256")  
    let skg = createSymKeyGenerator("AES128")  
    let sk = skg.generateSymKey()  
    mac.initialize(sk)  
    let blob = DataBlob("this is test!".toArray())  
    mac.update(blob)  
    mac.doFinal()  
} catch (e: BusinessException) {  
    Hilog.info(0, "test", "${e.message}")  
}  

func getMacLength()

public func getMacLength(): UInt32  

Function: Returns the MAC length in bytes.

System Capability: SystemCapability.Security.CryptoFramework.Mac

Since Version: 22

Return Value:

Type Description
UInt32 The byte length of the MAC result.

Example:

// index.cj  

import kit.CryptoArchitectureKit.*  
import ohos.business_exception.BusinessException  
import kit.PerformanceAnalysisKit.Hilog  

try {  
    let mac = createMac("SHA256")  
    let skg = createSymKeyGenerator("AES128")  
    let sk = skg.generateSymKey()  
    mac.initialize(sk)  
    let blob = DataBlob("this is test!".toArray())  
    mac.update(blob)  
    mac.doFinal()  
    var macLen = mac.getMacLength()  
} catch (e: BusinessException) {  
    Hilog.info(0, "test", "${e.message}")  
}  

func update(DataBlob)

public func update(input: DataBlob): Unit  

Function: Updates the MAC computation with input data.

System Capability: SystemCapability.Security.CryptoFramework.Mac

Since Version: 22

Parameters:

Parameter Type Required Default Value Description
input DataBlob Yes - Input message.

Example:

// index.cj  

import kit.CryptoArchitectureKit.*  
import ohos.business_exception.BusinessException  
import kit.PerformanceAnalysisKit.Hilog  

try {  
    let mac = createMac("SHA256")  
    let skg = createSymKeyGenerator("AES128")  
    let sk = skg.generateSymKey()  
    mac.initialize(sk)  
    let blob = DataBlob("this is test!".toArray())  
    mac.update(blob)  
} catch (e: BusinessException) {  
    Hilog.info(0, "test", "${e.message}")  
}  
```## class Md

```cangjie
public class Md {}

Function: The Md class, which can be used to perform MD (Message Digest) calculations by invoking Md methods. Before invocation, an Md instance must be constructed via createMd.

System Capability: SystemCapability.Security.CryptoFramework.MessageDigest

Since: 22

prop algName

public prop algName: String

Function: Represents the specified digest algorithm name.

Type: String

Read/Write Permission: Read-only

System Capability: SystemCapability.Security.CryptoFramework.MessageDigest

Since: 22

func digest()

public func digest(): DataBlob

Function: Returns the calculation result of Md.

System Capability: SystemCapability.Security.CryptoFramework.MessageDigest

Since: 22

Return Value:

Type Description
DataBlob Returns the calculated result as a DataBlob.

Exceptions:

  • BusinessException: Corresponding error codes are listed below. Refer to crypto framework error codes.

    Error Code ID Error Message
    17620001 Memory error.
    17630001 Crypto operation error.

Example:

// index.cj

import kit.CryptoArchitectureKit.*
import ohos.business_exception.BusinessException
import kit.PerformanceAnalysisKit.Hilog

try {
    let md = createMd("SHA256")
    let blob: DataBlob = DataBlob("test".toArray())
    md.update(blob)
    let res = md.digest()
} catch (e: BusinessException) {
    Hilog.info(0, "test", "${e.message}")
}

func getMdLength()

public func getMdLength(): UInt32

Function: Gets the length of the Md message digest (in bytes).

System Capability: SystemCapability.Security.CryptoFramework.MessageDigest

Since: 22

Return Value:

Type Description
UInt32 Returns the byte length of the Md calculation result.

Exceptions:

  • BusinessException: Corresponding error codes are listed below. Refer to crypto framework error codes.

    Error Code ID Error Message
    17630001 Crypto operation error.

Example:

// index.cj

import kit.CryptoArchitectureKit.*
import ohos.business_exception.BusinessException
import kit.PerformanceAnalysisKit.Hilog

try {
    let md = createMd("SHA256")
    let mdLen = md.getMdLength()
} catch (e: BusinessException) {
    Hilog.info(0, "test", "${e.message}")
}

func update(DataBlob)

public func update(input: DataBlob): Unit

Function: Updates the Md calculation with the input message.

System Capability: SystemCapability.Security.CryptoFramework.MessageDigest

Since: 22

Parameters:

Parameter Type Required Default Value Description
input DataBlob Yes - The input message.

Exceptions:

  • BusinessException: Corresponding error codes are listed below. Refer to crypto framework error codes.

    Error Code ID Error Message
    17620001 Memory operation failed.
    17630001 Crypto operation error.

Example:

// index.cj

import kit.CryptoArchitectureKit.*
import ohos.business_exception.BusinessException
import kit.PerformanceAnalysisKit.Hilog

try {
    let md = createMd("SHA256")
    let blob: DataBlob = DataBlob("test".toArray())
    md.update(blob)
} catch (e: BusinessException) {
    Hilog.info(0, "test", "${e.message}")
}

class Random

public class Random {}

Function: The Random class, which can be used to perform random number calculations by invoking Random methods. Before invocation, a Random instance must be constructed via createRandom.

System Capability: SystemCapability.Security.CryptoFramework.Rand

Since: 22

prop algName

public prop algName: String

Function: Represents the currently used random number generation algorithm. Currently, only "CTR_DRBG" is supported.

Type: String

Read/Write Permission: Read-only

System Capability: SystemCapability.Security.CryptoFramework.Rand

Since: 22

func generateRandom(Int32)

public func generateRandom(len: Int32): DataBlob

Function: Generates a random number of the specified length and returns it.

System Capability: SystemCapability.Security.CryptoFramework.Rand

Since: 22

Parameters:

Parameter Type Required Default Value Description
len Int32 Yes - The length of the random number to generate, in bytes. The range is [1, INT32_MAX].

Return Value:

Type Description
DataBlob A DataBlob object.

Exceptions:

  • BusinessException: Corresponding error codes are listed below. Refer to crypto framework error codes.

    Error Code ID Error Message
    17620001 Memory error.
    17630001 Crypto operation error.

Example:

// index.cj

import kit.CryptoArchitectureKit.*
import ohos.business_exception.BusinessException
import kit.PerformanceAnalysisKit.Hilog

try {
    let rand = createRandom()
    let promiseGenerateRand = rand.generateRandom(12)
} catch (e: BusinessException) {
    Hilog.info(0, "test", "${e.message}")
}

func setSeed(DataBlob)

public func setSeed(seed: DataBlob): Unit

Function: Sets the specified seed.

System Capability: SystemCapability.Security.CryptoFramework.Rand

Since: 22

Parameters:

Parameter Type Required Default Value Description
seed DataBlob Yes - The seed to set.

Exceptions:

  • BusinessException: Corresponding error codes are listed below. Refer to crypto framework error codes.

    Error Code ID Error Message
    17620001 Memory error.

Example:

// index.cj

import kit.CryptoArchitectureKit.*
import ohos.business_exception.BusinessException
import kit.PerformanceAnalysisKit.Hilog

try {
    let rand = createRandom()
    rand.setSeed(DataBlob("test".toArray()))
} catch (e: BusinessException) {
    Hilog.info(0, "test", "${e.message}")
}

class SymKey

public class SymKey <:  Key {}

Function: A symmetric key, which is a subclass of Key. It must be passed into the createCipher(String) method of a Cipher instance for symmetric encryption and decryption.

Symmetric keys can be generated via the symmetric key generator SymKeyGenerator.

System Capability: SystemCapability.Security.CryptoFramework.Key.SymKey

Since: 22

Parent Type:

prop algName

public prop algName: String

Function: The algorithm name specified by the symmetric key generator.

Type: String

Read/Write Permission: Read-only

System Capability: SystemCapability.Security.CryptoFramework.Key.SymKey

Since: 22

prop format

public prop format: String

Function: The format of the key.

Type: String

Read/Write Permission: Read-only

System Capability: SystemCapability.Security.CryptoFramework.Key.SymKey

Since: 22

func clearMem()

public func clearMem(): Unit

Function: A synchronous method that clears the key content in the underlying system memory. It is recommended to call this function when the symmetric key instance is no longer needed to avoid prolonged retention of key data in memory.

System Capability: SystemCapability.Security.CryptoFramework.Key.SymKey

Since: 22

Example:

// index.cj

import kit.CryptoArchitectureKit.*
import kit.PerformanceAnalysisKit.*
import ohos.business_exception.BusinessException
import kit.PerformanceAnalysisKit.Hilog

try {
    let generator = createSymKeyGenerator("3DES192")
    let key = generator.generateSymKey()
    var encodedKey = key.getEncoded()
    Hilog.info(0, "AppLogCj", "key blob: ${encodedKey.data}") // Display key content.
    key.clearMem()
    encodedKey = key.getEncoded()
    Hilog.info(0, "AppLogCj", "key blob: ${encodedKey.data}") // Display all 0s.
} catch (e: BusinessException) {
    Hilog.info(0, "test", "${e.message}")
}

func getEncoded()

public func getEncoded(): DataBlob

Function: A synchronous method that retrieves the byte stream of the key data. The key can be a symmetric key, public key, or private key. The public key format complies with ASN.1 syntax, X.509 specification, and DER encoding format. The private key format complies with ASN.1 syntax, PKCS#8 specification, and DER encoding method.

System Capability: SystemCapability.Security.CryptoFramework.Key.SymKey

Since: 22

Return Value:

Type Description
DataBlob Used to view the specific content of the key.

Exceptions:

  • BusinessException: Corresponding error codes are listed below. Refer to universal error codes and crypto framework error codes.

    Error Code ID Error Message
    801 This operation is not supported.
    17620001 Memory error.
    17630001 Crypto operation error.

Example:

// index.cj

import kit.CryptoArchitectureKit.*
import kit.PerformanceAnalysisKit.*
import ohos.business_exception.BusinessException
import kit.PerformanceAnalysisKit.Hilog

try {
    let generator = createSymKeyGenerator("3DES192")
    let key = generator.generateSymKey()
    var encodedKey = key.getEncoded()
    Hilog.info(0, "AppLogCj", "key blob: ${encodedKey.data}") // Display key content.
} catch (e: BusinessException) {
    Hilog.info(0, "test", "${e.message}")
}
```## class SymKeyGenerator

```cangjie
public class SymKeyGenerator {}

Function: Symmetric key generator.

Before using the methods of this class, you need to first construct a symKeyGenerator instance using the createSymKeyGenerator method.

System Capability: SystemCapability.Security.CryptoFramework.Key.SymKey

Since: 22

prop algName

public prop algName: String

Function: The algorithm name specified by the symmetric key generator.

Type: String

Read-Write Capability: Read-only

System Capability: SystemCapability.Security.CryptoFramework.Key.SymKey

Since: 22

func convertKey(DataBlob)

public func convertKey(key: DataBlob): SymKey

Function: Generates a symmetric key based on the specified data.

This function can only be used after creating a symmetric key generator with createSymKeyGenerator.

Note:

For symmetric keys of the HMAC algorithm, if a specific hash algorithm (e.g., "HMAC|SHA256") was specified when creating the symmetric key generator, binary key data consistent with the hash length must be passed (e.g., 256-bit key data for SHA256). If no specific hash algorithm was specified when creating the symmetric key generator (e.g., only "HMAC" was specified), any binary key data with a length in the range [1,4096] (in bytes) can be passed.

System Capability: SystemCapability.Security.CryptoFramework.Key.SymKey

Since: 22

Parameters:

Parameter Type Required Default Description
key DataBlob Yes - Specified key material data.

Return Value:

Type Description
SymKey Returns the symmetric key SymKey.

Exceptions:

  • BusinessException: Corresponding error codes are listed below. Refer to crypto framework error codes.

    Error Code ID Error Message
    17620001 Memory error.

Example:

// index.cj

import kit.CryptoArchitectureKit.*
import ohos.business_exception.BusinessException
import kit.PerformanceAnalysisKit.Hilog

try {
    let arr: Array<UInt8> = [0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56, 0xad, 0x47, 0xfc, 0x5a,
        0x46, 0x39, 0xee, 0x7c, 0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72] // keyLen = 192 (24 bytes)
    let symAlgName = "3DES192"
    let symKeyGenerator = createSymKeyGenerator(symAlgName)
    symKeyGenerator.convertKey(DataBlob(arr))
} catch (e: BusinessException) {
    Hilog.info(0, "test", "${e.message}")
}

func generateSymKey()

public func generateSymKey(): SymKey

Function: Obtains a randomly generated key from this symmetric key generator.

This function can only be used after creating a symmetric key generator with createSymKeyGenerator.

Currently, OpenSSL's RAND_priv_bytes() is supported as the underlying capability for generating random keys.

System Capability: SystemCapability.Security.CryptoFramework.Key.SymKey

Since: 22

Return Value:

Type Description
SymKey Symmetric key SymKey.

Exceptions:

  • BusinessException: Corresponding error codes are listed below. Refer to crypto framework error codes.

    Error Code ID Error Message
    17620001 Memory error.

Example:

// index.cj

import kit.CryptoArchitectureKit.*
import ohos.business_exception.BusinessException
import kit.PerformanceAnalysisKit.Hilog

try {
    let symAlgName = "AES128"
    let symKeyGenerator = createSymKeyGenerator(symAlgName)
    let symKey = symKeyGenerator.generateSymKey()
} catch (e: BusinessException) {
    Hilog.info(0, "test", "${e.message}")
}

struct CcmParamsSpec

public struct CcmParamsSpec <: ParamsSpec {
    public init(algName: String, iv: DataBlob, add: DataBlob, authTag: DataBlob)
}

Function: A subclass of encryption/decryption parameters ParamsSpec, used as a parameter for the createCipher(String) method during symmetric encryption/decryption.

Applicable to CCM mode.

Note:

Its algName property (inherited from the parent class ParamsSpec) must be specified before being passed to the createCipher(String) method.

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22

Parent Type:

prop aad

public mut prop aad: DataBlob

Function: Specifies the encryption/decryption parameter aad, with a length of 8 bytes.

Type: DataBlob

Read-Write Capability: Read-write

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22

prop authTag

public mut prop authTag: DataBlob

Function: Specifies the encryption/decryption parameter authTag, with a length of 12 bytes.
When encrypting in CCM mode, you need to obtain the DataBlob output by doFinal() and extract its last 12 bytes as the authTag in the CcmParamsSpec parameter for the createCipher(String) method during decryption.

Type: DataBlob

Read-Write Capability: Read-write

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22

prop iv

public mut prop iv: DataBlob

Function: Specifies the encryption/decryption parameter iv, with a length of 7 bytes.

Type: DataBlob

Read-Write Capability: Read-write

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22

init(String, DataBlob, DataBlob, DataBlob)

public init(algName: String, iv: DataBlob, aad: DataBlob, authTag: DataBlob)

Function: Creates a CcmParamsSpec instance.

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22

Parameters:

Parameter Type Required Default Description
algName String Yes - Specifies the algorithm mode for symmetric encryption/decryption parameters. Options are:
- IvParamsSpec: Applicable to CBCMagIc_StrINgCTRMagIc_StrINgOFBMagIc_StrINgCFB modes.
- GcmParamsSpec: Applicable to GCM mode.
- CcmParamsSpec: Applicable to CCM mode.
iv DataBlob Yes - Specifies the encryption/decryption parameter iv, with a length of 7 bytes.
aad DataBlob Yes - Specifies the encryption/decryption parameter aad, with a length of 8 bytes.
authTag DataBlob Yes - Specifies the encryption/decryption parameter authTag, with a length of 12 bytes. When encrypting in CCM mode, you need to obtain the DataBlob output by doFinal() or doFinalSync() and extract its last 12 bytes as the authTag in the CcmParamsSpec parameter for the init() or initSync() method during decryption.

Example:

// index.cj

import kit.CryptoArchitectureKit.*
import ohos.business_exception.BusinessException
import kit.PerformanceAnalysisKit.Hilog

try {
    let ccm = GcmParamsSpec("CcmParamsSpec", DataBlob(Array<UInt8>(7, repeat: 1)), DataBlob(Array<UInt8>(8, repeat: 1)), DataBlob(Array<UInt8>(12, repeat: 1)))
} catch (e: BusinessException) {
    Hilog.info(0, "test", "${e.message}")
}

struct DataBlob

public struct DataBlob {
    public DataBlob(
        public let data: Array<UInt8>
    )
}

Function: A data type for storing arrays.

System Capability: SystemCapability.Security.CryptoFramework

Since: 22

let data

public let data: Array<UInt8>

Function: Data.

Type: Array<UInt8>

Read-Write Capability: Read-only

System Capability: SystemCapability.Security.CryptoFramework

Since: 22

init(Array<UInt8>)

public init(data: Array<UInt8>)

Function: Creates a DataBlob object.

System Capability: SystemCapability.Security.CryptoFramework

Since: 22

Parameters:

Parameter Type Required Default Description
data Array<UInt8> Yes - The array to store.

struct GcmParamsSpec

public struct GcmParamsSpec <: ParamsSpec {
    public init(algName: String, iv: DataBlob, add: DataBlob, authTag: DataBlob)
}

Function: A subclass of encryption/decryption parameters ParamsSpec, used as a parameter for the createCipher(String) method during symmetric encryption/decryption.

Applicable to GCM mode.

Note:

Its algName property (inherited from the parent class ParamsSpec) must be specified before being passed to the createCipher(String) method.

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22

Parent Type:

prop aad

public mut prop aad: DataBlob

Function: Specifies the encryption/decryption parameter aad, with a length of 8 bytes.

Type: DataBlob

Read-Write Capability: Read-write

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22

prop authTag

public mut prop authTag: DataBlob

Function: Specifies the encryption/decryption parameter authTag, with a length of 16 bytes.
When encrypting in GCM mode, you need to obtain the DataBlob output by doFinal() and extract its last 16 bytes as the authTag in the GcmParamsSpec parameter for the createCipher(String) method during decryption.

Type: DataBlob

Read-Write Capability: Read-write

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22

prop iv

public mut prop iv: DataBlob

Function: Specifies the encryption/decryption parameter iv, with a length of 12 bytes.

Type: DataBlob

Read-Write Capability: Read-write

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22

init(String, DataBlob, DataBlob, DataBlob)

public init(algName: String, iv: DataBlob, aad: DataBlob, authTag: DataBlob)

Function: Creates a GcmParamsSpec instance.

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22

Parameters:

Parameter Type Required Default Description
algName String Yes - Specifies the algorithm mode for symmetric encryption/decryption parameters. Options are:
- IvParamsSpec: Applicable to CBCMagIc_StrINgCTRMagIc_StrINgOFBMagIc_StrINgCFB modes.
- GcmParamsSpec: Applicable to GCM mode.
- CcmParamsSpec: Applicable to CCM mode.
iv DataBlob Yes - Specifies the encryption/decryption parameter iv, with a length of 12 bytes.
aad DataBlob Yes - Specifies the encryption/decryption parameter aad, with a length of 8 bytes.
authTag DataBlob Yes - Specifies the encryption/decryption parameter authTag, with a length of 16 bytes.
When encrypting in GCM mode, you need to obtain the DataBlob output by doFinal() and extract its last 16 bytes as the authTag in the GcmParamsSpec parameter for the createCipher(String) method during decryption.

Example:

// index.cj

import kit.CryptoArchitectureKit.*
import ohos.business_exception.BusinessException
import kit.PerformanceAnalysisKit.Hilog

try {
    let gcm = GcmParamsSpec("GcmParamsSpec", DataBlob(Array<UInt8>(12, repeat: 1)), DataBlob(Array<UInt8>(8, repeat: 1)), DataBlob(Array<UInt8>(16, repeat: 1)))
} catch (e: BusinessException) {
    Hilog.info(0, "test", "${e.message}")
}
```## struct IvParamsSpec

```cangjie
public struct IvParamsSpec <: ParamsSpec {
    public init(algName: String, iv: DataBlob)
}

Function: A subclass of encryption/decryption parameters ParamsSpec, used as a parameter for the createCipher(String) method during symmetric encryption/decryption.

Applicable to encryption/decryption modes that only use iv as a parameter, such as CBC, CTR, OFB, and CFB.

Note:

The algName property (inherited from the parent class ParamsSpec) must be specified before passing it to the createCipher(String) method.

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22

Parent Type:

prop iv

public mut prop iv: DataBlob

Function: Specifies the encryption/decryption parameter iv. Common values are as follows:
- For AES in CBCMagIc_StrINgCTRMagIc_StrINgOFBMagIc_StrINgCFB modes: iv length is 16 bytes
- For 3DES in CBCMagIc_StrINgOFBMagIc_StrINgCFB modes: iv length is 8 bytes
- For SM4 in CBCMagIc_StrINgCTRMagIc_StrINgOFBMagIc_StrINgCFB modes: iv length is 16 bytes.

Type: DataBlob

Read/Write Capability: Readable and Writable

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22

init(String, DataBlob)

public init(algName: String, iv: DataBlob)

Function: Creates an instance of IvParamsSpec.

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22

Parameters:

Parameter Type Required Default Value Description
algName String Yes - Specifies the algorithm mode for symmetric encryption/decryption parameters. Possible values:
- IvParamsSpec: Applicable to CBCMagIc_StrINgCTRMagIc_StrINgOFBMagIc_StrINgCFB modes.
- GcmParamsSpec: Applicable to GCM mode.
- CcmParamsSpec: Applicable to CCM mode.
iv DataBlob Yes - Specifies the encryption/decryption parameter iv. Common values:
- For AES in CBCMagIc_StrINgCTRMagIc_StrINgOFBMagIc_StrINgCFB modes: iv length is 16 bytes
- For 3DES in CBCMagIc_StrINgOFBMagIc_StrINgCFB modes: iv length is 8 bytes
- For SM4 in CBCMagIc_StrINgCTRMagIc_StrINgOFBMagIc_StrINgCFB modes: iv length is 16 bytes.

Example:

// index.cj

import kit.CryptoArchitectureKit.*
import ohos.business_exception.BusinessException
import kit.PerformanceAnalysisKit.Hilog

try {
    let iv = IvParamsSpec("IvParamsSpec", DataBlob(Array<UInt8>(8, repeat: 1)))
} catch (e: BusinessException) {
    Hilog.info(0, "test", "${e.message}")
}

enum CryptoMode

public enum CryptoMode <: Equatable<CryptoMode> & ToString {
    | EncryptMode
    | DecryptMode
    | ...
}

Function: Represents encryption/decryption operations.

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22

Parent Types:

  • Equatable<CryptoMode>
  • ToString

DecryptMode

DecryptMode

Function: Represents a decryption operation.

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22

EncryptMode

EncryptMode

Function: Represents an encryption operation.

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22

func !=(CryptoMode)

public operator func !=(other: CryptoMode): Bool

Function: Determines whether two enum values are not equal.

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22

Parameters:

Parameter Type Required Default Value Description
other CryptoMode Yes - Another enum value.

Return Value:

Type Description
Bool Returns true if the two enum values are not equal, otherwise false.

func ==(CryptoMode)

public operator func ==(other: CryptoMode): Bool

Function: Determines whether two enum values are equal.

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22

Parameters:

Parameter Type Required Default Value Description
other CryptoMode Yes - Another enum value.

Return Value:

Type Description
Bool Returns true if the two enum values are equal, otherwise false.

func toString()

public func toString(): String

Function: Gets the value of the enum.

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22

Return Value:

Type Description
String The description of the enum.

enum CipherSpecItem

public enum CipherSpecItem <: Equatable<CipherSpecItem> & ToString {
    | OaepMdNameStr
    | OaepMgfNameStr
    | OaepMgf1MdStr
    | OaepMgf1PsrcUint8Arr
    | ...
}

Function: Represents an enum for encryption/decryption parameters. Currently only supports RSA and SM2 algorithms.

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22

Parent Types:

  • Equatable<CipherSpecItem>
  • ToString

OaepMdNameStr

OaepMdNameStr

Function: Represents the algorithm name for the message digest function when using PKCS1_OAEP mode in RSA algorithm.

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22

OaepMgfNameStr

OaepMgfNameStr

Function: Represents the mask generation algorithm (currently only supports MGF1) when using PKCS1_OAEP mode in RSA algorithm.

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22

OaepMgf1MdStr

OaepMgf1MdStr

Function: Represents the message digest algorithm for MGF1 mask generation when using PKCS1_OAEP mode in RSA algorithm.

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22

OaepMgf1PsrcUint8Arr

OaepMgf1PsrcUint8Arr

Function: Represents the byte stream of pSource when using PKCS1_OAEP mode in RSA algorithm.

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22

func !=(CipherSpecItem)

public operator func !=(other: CipherSpecItem): Bool

Function: Determines whether two enum values are not equal.

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22

Parameters:

Parameter Type Required Default Value Description
other CipherSpecItem Yes - Another enum value.

Return Value:

Type Description
Bool Returns true if the two enum values are not equal, otherwise false.

func ==(CipherSpecItem)

public operator func ==(other: CipherSpecItem): Bool

Function: Determines whether two enum values are equal.

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22

Parameters:

Parameter Type Required Default Value Description
other CipherSpecItem Yes - Another enum value.

Return Value:

Type Description
Bool Returns true if the two enum values are equal, otherwise false.

func toString()

public func toString(): String

Function: Gets the value of the enum.

System Capability: SystemCapability.Security.CryptoFramework.Cipher

Since: 22

Return Value:

Type Description
String The description of the enum.

enum Result

public enum Result <: ToString {
    | InvalidParams
    | NotSupport
    | ErrOutOfMemory
    | ErrRuntimeError
    | ErrCryptoOperation
    | ...
}

Function: Represents execution results.

System Capability: SystemCapability.Security.CryptoFramework

Since: 22

Parent Type:

  • ToString

ErrCryptoOperation

ErrCryptoOperation

Function: Error occurred when calling a third-party algorithm library API.

System Capability: SystemCapability.Security.CryptoFramework

Since: 22

ErrOutOfMemory

ErrOutOfMemory

Function: Memory error.

System Capability: SystemCapability.Security.CryptoFramework

Since: 22

ErrRuntimeError

ErrRuntimeError

Function: External runtime error.

System Capability: SystemCapability.Security.CryptoFramework

Since: 22

InvalidParams

InvalidParams

Function: Invalid input parameters.

System Capability: SystemCapability.Security.CryptoFramework

Since: 22

NotSupport

NotSupport

Function: Operation not supported.

System Capability: SystemCapability.Security.CryptoFramework

Since: 22### func getValue()

public func getValue(): Int32

Function: Gets the value of the enumeration.

System Capability: SystemCapability.Security.CryptoFramework

Since: 22

Return Value:

Type Description
Int32 The value of the enumeration.

func toString()

public func toString(): String

Function: Gets the description of the enumeration.

System Capability: SystemCapability.Security.CryptoFramework

Since: 22

Return Value:

Type Description
String The description of the enumeration.