提交 1af77832 编写于 作者: A Annie_wang

update docs

Signed-off-by: NAnnie_wang <annie.wangli@huawei.com>
上级 2e089195
...@@ -94,6 +94,7 @@ ...@@ -94,6 +94,7 @@
- File Management - File Management
- [@ohos.document](js-apis-document.md)
- [@ohos.environment](js-apis-environment.md) - [@ohos.environment](js-apis-environment.md)
- [@ohos.fileio](js-apis-fileio.md) - [@ohos.fileio](js-apis-fileio.md)
- [@ohos.fileManager](js-apis-filemanager.md) - [@ohos.fileManager](js-apis-filemanager.md)
......
...@@ -503,9 +503,7 @@ Asynchronously creates a directory. This method uses a callback to return the re ...@@ -503,9 +503,7 @@ Asynchronously creates a directory. This method uses a callback to return the re
- Example - Example
```js ```js
fileio.mkdir(path, function(err) { fileio.mkdir(path, function(err) {
if (!err) { console.info("mkdir successfully");
// Do something.
}
}); });
``` ```
...@@ -639,7 +637,8 @@ Asynchronously reads data from a file. This method uses a promise to return the ...@@ -639,7 +637,8 @@ Asynchronously reads data from a file. This method uses a promise to return the
let fd = fileio.openSync(path, 0o2); let fd = fileio.openSync(path, 0o2);
let buf = new ArrayBuffer(4096); let buf = new ArrayBuffer(4096);
fileio.read(fd, buf).then(function(readout){ fileio.read(fd, buf).then(function(readout){
console.info("read file data successfully:"+ JSON.stringify(readout)); console.info("read file data successfully");
console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer)));
}).catch(function(error){ }).catch(function(error){
console.info("read file data failed with error:"+ error); console.info("read file data failed with error:"+ error);
}); });
...@@ -671,8 +670,9 @@ Asynchronously reads data from a file. This method uses a callback to return the ...@@ -671,8 +670,9 @@ Asynchronously reads data from a file. This method uses a callback to return the
let fd = fileio.openSync(path, 0o2); let fd = fileio.openSync(path, 0o2);
let buf = new ArrayBuffer(4096); let buf = new ArrayBuffer(4096);
fileio.read(fd, buf, function (err, readOut) { fileio.read(fd, buf, function (err, readOut) {
if (!err) { if (readOut) {
console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer))) console.info("read file data successfully");
console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer)));
} }
}); });
``` ```
...@@ -756,6 +756,7 @@ Asynchronously deletes a directory. This method uses a callback to return the re ...@@ -756,6 +756,7 @@ Asynchronously deletes a directory. This method uses a callback to return the re
```js ```js
fileio.rmdir(path, function(err){ fileio.rmdir(path, function(err){
// Do something. // Do something.
console.info("rmdir successfully");
}); });
``` ```
...@@ -824,9 +825,7 @@ Asynchronously deletes a file. This method uses a callback to return the result. ...@@ -824,9 +825,7 @@ Asynchronously deletes a file. This method uses a callback to return the result.
- Example - Example
```js ```js
fileio.unlink(path, function(err) { fileio.unlink(path, function(err) {
if (!err) { console.info("remove file successfully");
// Do something.
}
}); });
``` ```
...@@ -879,7 +878,7 @@ Asynchronously writes data into a file. This method uses a promise to return the ...@@ -879,7 +878,7 @@ Asynchronously writes data into a file. This method uses a promise to return the
```js ```js
let fd = fileio.openSync(fpath, 0o100 | 0o2, 0o666); let fd = fileio.openSync(fpath, 0o100 | 0o2, 0o666);
fileio.write(fd, "hello, world").then(function(number){ fileio.write(fd, "hello, world").then(function(number){
console.info("write data to file successfully:"+ number); console.info("write data to file successfully and size is:"+ number);
}).catch(function(err){ }).catch(function(err){
console.info("write data to file failed with error:"+ err); console.info("write data to file failed with error:"+ err);
}); });
...@@ -911,8 +910,8 @@ Asynchronously writes data into a file. This method uses a callback to return th ...@@ -911,8 +910,8 @@ Asynchronously writes data into a file. This method uses a callback to return th
```js ```js
let fd = fileio.openSync(path, 0o100 | 0o2, 0o666); let fd = fileio.openSync(path, 0o100 | 0o2, 0o666);
fileio.write(fd, "hello, world", function (err, bytesWritten) { fileio.write(fd, "hello, world", function (err, bytesWritten) {
if (!err) { if (bytesWritten) {
console.log(bytesWritten) console.info("write data to file successfully and size is:"+ bytesWritten);
} }
}); });
``` ```
...@@ -962,7 +961,7 @@ Asynchronously calculates the hash value of a file. This method uses a promise t ...@@ -962,7 +961,7 @@ Asynchronously calculates the hash value of a file. This method uses a promise t
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ------ | ---- | ---------------------------------------- | | --------- | ------ | ---- | ---------------------------------------- |
| path | string | Yes | Absolute path of the target file. | | path | string | Yes | Absolute path of the target file. |
| algorithm | string | Yes | Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**.**sha256** is recommended for security purposes.| | algorithm | string | Yes | Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**. **sha256** is recommended for security purposes.|
- Return value - Return value
| Type | Description | | Type | Description |
...@@ -991,14 +990,14 @@ Asynchronously calculates the hash value of a file. This method uses a callback ...@@ -991,14 +990,14 @@ Asynchronously calculates the hash value of a file. This method uses a callback
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | --------------------------- | ---- | ---------------------------------------- | | --------- | --------------------------- | ---- | ---------------------------------------- |
| path | string | Yes | Absolute path of the target file. | | path | string | Yes | Absolute path of the target file. |
| algorithm | string | Yes | Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**.**sha256** is recommended for security purposes.| | algorithm | string | Yes | Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**. **sha256** is recommended for security purposes.|
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the hash value. The hash value is a hexadecimal string consisting of digits and uppercase letters.| | callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the hash value. The hash value is a hexadecimal string consisting of digits and uppercase letters.|
- Example - Example
```js ```js
fileio.hash(fpath, "sha256", function(err, hashStr) { fileio.hash(fpath, "sha256", function(err, hashStr) {
if (!err) { if (hashStr) {
console.log(hashStr) console.info("calculate file hash successfully:"+ hashStr);
} }
}); });
``` ```
...@@ -1091,7 +1090,7 @@ Asynchronously obtains file status information based on the file descriptor. Thi ...@@ -1091,7 +1090,7 @@ Asynchronously obtains file status information based on the file descriptor. Thi
- Return value - Return value
| Type | Description | | Type | Description |
| -------- | -------- | | ---------------------------- | ---------- |
| Promise&lt;[Stat](#stat)&gt; | Promise used to return the file status information obtained.| | Promise&lt;[Stat](#stat)&gt; | Promise used to return the file status information obtained.|
- Example - Example
...@@ -1221,7 +1220,7 @@ Synchronously truncates a file based on the file descriptor. ...@@ -1221,7 +1220,7 @@ Synchronously truncates a file based on the file descriptor.
- Example - Example
```js ```js
fileio.ftruncate(fd, len); fileio.ftruncateSync(fd, len);
``` ```
...@@ -1293,7 +1292,7 @@ Synchronously truncates a file based on the file path. ...@@ -1293,7 +1292,7 @@ Synchronously truncates a file based on the file path.
- Example - Example
```js ```js
fileio.ftruncate(path, len); fileio.truncateSync(path, len);
``` ```
...@@ -1486,7 +1485,8 @@ Asynchronously reads data from a file. This method uses a promise to return the ...@@ -1486,7 +1485,8 @@ Asynchronously reads data from a file. This method uses a promise to return the
- Example - Example
```js ```js
fileio.read(new ArrayBuffer(4096)).then(function(readout){ fileio.read(new ArrayBuffer(4096)).then(function(readout){
console.info("File data read successfully:"+ String.fromCharCode.apply(null, new Uint8Array(readout.buffer))); console.info("read file data successfully");
console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer)));
}).catch(function(err){ }).catch(function(err){
console.info("Failed to read file data. Error:"+ err); console.info("Failed to read file data. Error:"+ err);
}); });
...@@ -1516,8 +1516,9 @@ Asynchronously reads data from a file. This method uses a callback to return the ...@@ -1516,8 +1516,9 @@ Asynchronously reads data from a file. This method uses a callback to return the
```js ```js
let buf = new ArrayBuffer(4096); let buf = new ArrayBuffer(4096);
fileio.read(buf, function (err, readOut) { fileio.read(buf, function (err, readOut) {
if (!err) { if (readOut) {
console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer))) console.info("read file data successfully");
console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer)));
} }
}); });
``` ```
...@@ -2407,14 +2408,14 @@ Provides detailed file information. Before calling a method of the **Stat** clas ...@@ -2407,14 +2408,14 @@ Provides detailed file information. Before calling a method of the **Stat** clas
isBlockDevice(): boolean isBlockDevice(): boolean
Checks whether the current directory entry is a block special file. A block special file supports access by block only, and it is cached when accessed. Checks whether this file is a block special file. A block special file supports access by block only, and it is cached when accessed.
**System capability**: SystemCapability.FileManagement.File.FileIO **System capability**: SystemCapability.FileManagement.File.FileIO
- Return value - Return value
| Type | Description | | Type | Description |
| ------- | ---------------- | | ------- | ---------------- |
| boolean | Whether the directory entry is a block special file.| | boolean | Whether the file is a block special file.|
- Example - Example
```js ```js
...@@ -2426,14 +2427,14 @@ Checks whether the current directory entry is a block special file. A block spec ...@@ -2426,14 +2427,14 @@ Checks whether the current directory entry is a block special file. A block spec
isCharacterDevice(): boolean isCharacterDevice(): boolean
Checks whether the current directory entry is a character special file. A character special file supports random access, and it is not cached when accessed. Checks whether this file is a character special file. A character special file supports random access, and it is not cached when accessed.
**System capability**: SystemCapability.FileManagement.File.FileIO **System capability**: SystemCapability.FileManagement.File.FileIO
- Return value - Return value
| Type | Description | | Type | Description |
| ------- | ----------------- | | ------- | ----------------- |
| boolean | Whether the directory entry is a character special file.| | boolean | Whether the file is a character special file.|
- Example - Example
```js ```js
...@@ -2445,14 +2446,14 @@ Checks whether the current directory entry is a character special file. A charac ...@@ -2445,14 +2446,14 @@ Checks whether the current directory entry is a character special file. A charac
isDirectory(): boolean isDirectory(): boolean
Checks whether a directory entry is a directory. Checks whether this file is a directory.
**System capability**: SystemCapability.FileManagement.File.FileIO **System capability**: SystemCapability.FileManagement.File.FileIO
- Return value - Return value
| Type | Description | | Type | Description |
| ------- | ------------- | | ------- | ------------- |
| boolean | Whether the directory entry is a directory.| | boolean | Whether the file is a directory.|
- Example - Example
```js ```js
...@@ -2464,14 +2465,14 @@ Checks whether a directory entry is a directory. ...@@ -2464,14 +2465,14 @@ Checks whether a directory entry is a directory.
isFIFO(): boolean isFIFO(): boolean
Checks whether the current directory entry is a named pipe (or FIFO). Named pipes are used for inter-process communication. Checks whether this file is a named pipe (or FIFO). Named pipes are used for inter-process communication.
**System capability**: SystemCapability.FileManagement.File.FileIO **System capability**: SystemCapability.FileManagement.File.FileIO
- Return value - Return value
| Type | Description | | Type | Description |
| ------- | --------------------- | | ------- | --------------------- |
| boolean | Whether the directory entry is a FIFO.| | boolean | Whether the file is an FIFO.|
- Example - Example
```js ```js
...@@ -2483,14 +2484,14 @@ Checks whether the current directory entry is a named pipe (or FIFO). Named pipe ...@@ -2483,14 +2484,14 @@ Checks whether the current directory entry is a named pipe (or FIFO). Named pipe
isFile(): boolean isFile(): boolean
Checks whether a directory entry is a regular file. Checks whether this file is a regular file.
**System capability**: SystemCapability.FileManagement.File.FileIO **System capability**: SystemCapability.FileManagement.File.FileIO
- Return value - Return value
| Type | Description | | Type | Description |
| ------- | --------------- | | ------- | --------------- |
| boolean | Whether the directory entry is a regular file.| | boolean | Whether the file is a regular file.|
- Example - Example
```js ```js
...@@ -2502,14 +2503,14 @@ Checks whether a directory entry is a regular file. ...@@ -2502,14 +2503,14 @@ Checks whether a directory entry is a regular file.
isSocket(): boolean isSocket(): boolean
Checks whether a directory entry is a socket. Checks whether this file is a socket.
**System capability**: SystemCapability.FileManagement.File.FileIO **System capability**: SystemCapability.FileManagement.File.FileIO
- Return value - Return value
| Type | Description | | Type | Description |
| ------- | -------------- | | ------- | -------------- |
| boolean | Whether the directory entry is a socket.| | boolean | Whether the file is a socket.|
- Example - Example
```js ```js
...@@ -2521,14 +2522,14 @@ Checks whether a directory entry is a socket. ...@@ -2521,14 +2522,14 @@ Checks whether a directory entry is a socket.
isSymbolicLink(): boolean isSymbolicLink(): boolean
Checks whether a directory entry is a symbolic link. Checks whether this file is a symbolic link.
**System capability**: SystemCapability.FileManagement.File.FileIO **System capability**: SystemCapability.FileManagement.File.FileIO
- Return value - Return value
| Type | Description | | Type | Description |
| ------- | --------------- | | ------- | --------------- |
| boolean | Whether the directory entry is a symbolic link.| | boolean | Whether the file is a symbolic link.|
- Example - Example
```js ```js
...@@ -2731,7 +2732,7 @@ Asynchronously writes data into the stream. This method uses a promise to return ...@@ -2731,7 +2732,7 @@ Asynchronously writes data into the stream. This method uses a promise to return
```js ```js
let ss= fileio.createStreamSync(fpath, "r+"); let ss= fileio.createStreamSync(fpath, "r+");
ss.write("hello, world",{offset: 1,length: 5,position: 5,encoding :'utf-8'}).then(function (number){ ss.write("hello, world",{offset: 1,length: 5,position: 5,encoding :'utf-8'}).then(function (number){
console.info("write successfully:"+ number); console.info("write successfully and size is:"+ number);
}).catch(function(err){ }).catch(function(err){
console.info("write failed with error:"+ err); console.info("write failed with error:"+ err);
}); });
...@@ -2762,9 +2763,9 @@ Asynchronously writes data into the stream. This method uses a callback to retur ...@@ -2762,9 +2763,9 @@ Asynchronously writes data into the stream. This method uses a callback to retur
```js ```js
let ss= fileio.createStreamSync(fpath, "r+"); let ss= fileio.createStreamSync(fpath, "r+");
ss.write("hello, world", {offset: 1, length: 5, position: 5, encoding :'utf-8'}, function (err, bytesWritten) { ss.write("hello, world", {offset: 1, length: 5, position: 5, encoding :'utf-8'}, function (err, bytesWritten) {
if (!err) { if (bytesWritten) {
// do something // do something
console.log(bytesWritten); console.info("write successfully and size is:"+ bytesWritten);
} }
}); });
``` ```
...@@ -2829,6 +2830,7 @@ Asynchronously reads data from the stream. This method uses a promise to return ...@@ -2829,6 +2830,7 @@ Asynchronously reads data from the stream. This method uses a promise to return
let ss = fileio.createStreamSync(fpath, "r+"); let ss = fileio.createStreamSync(fpath, "r+");
ss.read(new ArrayBuffer(4096), {offset: 1, length: 5, position: 5}).then(function (readout){ ss.read(new ArrayBuffer(4096), {offset: 1, length: 5, position: 5}).then(function (readout){
console.info("read data successfully"); console.info("read data successfully");
console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer)));
}).catch(function(err){ }).catch(function(err){
console.info("read data failed with error:"+ err); console.info("read data failed with error:"+ err);
}); });
...@@ -2858,8 +2860,9 @@ Asynchronously reads data from the stream. This method uses a callback to return ...@@ -2858,8 +2860,9 @@ Asynchronously reads data from the stream. This method uses a callback to return
```js ```js
let ss = fileio.createStreamSync(fpath, "r+"); let ss = fileio.createStreamSync(fpath, "r+");
ss.read(new ArrayBuffer(4096),{offset: 1, length: 5, position: 5},function (err, readOut) { ss.read(new ArrayBuffer(4096),{offset: 1, length: 5, position: 5},function (err, readOut) {
if (!err) { if (readOut) {
// do something console.info("read data successfully");
console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer)));
} }
}); });
``` ```
...@@ -2917,7 +2920,7 @@ Asynchronously reads the next directory entry. This method uses a promise to ret ...@@ -2917,7 +2920,7 @@ Asynchronously reads the next directory entry. This method uses a promise to ret
```js ```js
let dir = fileio.opendirSync(path); let dir = fileio.opendirSync(path);
dir.read().then(function (dirent){ dir.read().then(function (dirent){
console.info("read successfully:"+ dirent.name); console.log("read successfully:"+JSON.stringify(dirent));
}).catch(function(err){ }).catch(function(err){
console.info("read failed with error:"+ err); console.info("read failed with error:"+ err);
}); });
...@@ -2941,9 +2944,9 @@ Asynchronously reads the next directory entry. This method uses a callback to re ...@@ -2941,9 +2944,9 @@ Asynchronously reads the next directory entry. This method uses a callback to re
```js ```js
let dir = fileio.opendirSync(path); let dir = fileio.opendirSync(path);
dir.read(function (err, dirent) { dir.read(function (err, dirent) {
if (!err) { if (dirent) {
// do something // do something
console.log(dirent.name) console.log("read successfully:"+JSON.stringify(dirent));
} }
}); });
``` ```
......
...@@ -362,16 +362,17 @@ Generates a key. This method uses an asynchronous callback to return the result. ...@@ -362,16 +362,17 @@ Generates a key. This method uses an asynchronous callback to return the result.
| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| keyAlias | string | Yes | Alias of the key. | | keyAlias | string | Yes | Alias of the key. |
| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. | | options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. |
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned. For details about the error codes, see **HuksResult**.| | callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If any other result is returned, see **HuksResult**.|
**Example** **Example**
```js ```js
var alias = 'alias'; /* Generate an RSA key of 512 bits. */
var keyAlias = 'keyAlias';
var properties = new Array(); var properties = new Array();
properties[0] = { properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huksHuksKeyAlg.HUKS_ALG_RSA value: huks.HuksKeyAlg.HUKS_ALG_RSA
}; };
properties[1] = { properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
...@@ -379,24 +380,22 @@ properties[1] = { ...@@ -379,24 +380,22 @@ properties[1] = {
}; };
properties[2] = { properties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE, tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT value:
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT |
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
}; };
properties[3] = { properties[3] = {
tag: huks.HuksTag.HUKS_TAG_PADDING, tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_NONE value: huks.HuksKeyPadding.HUKS_PADDING_OAEP
}; };
properties[4] = { properties[4] = {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB
};
properties[5] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST, tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_NONE value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
}; };
var options = { var options = {
properties: properties properties: properties
}; };
huks.generateKey(alias, options, function (err, data){}); huks.generateKey(keyAlias, options, function (err, data){});
``` ```
## huks.generateKey ## huks.generateKey
...@@ -418,41 +417,36 @@ Generates a key. This method uses a promise to return the result. ...@@ -418,41 +417,36 @@ Generates a key. This method uses a promise to return the result.
| Type | Description | | Type | Description |
| ----------------------------------- | -------------------------------------------------- | | ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned. For details about the error codes, see **HuksResult**.| | Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.|
**Example** **Example**
```js ```js
var alias = 'alias'; /* Generate an ECC key of 256 bits. */
var keyAlias = 'keyAlias';
var properties = new Array(); var properties = new Array();
properties[0] = { properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huksHuksKeyAlg.HUKS_ALG_RSA value: huks.HuksKeyAlg.HUKS_ALG_ECC
}; };
properties[1] = { properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512 value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256
}; };
properties[2] = { properties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE, tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT value:
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN |
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
}; };
properties[3] = { properties[3] = {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_NONE
};
properties[4] = {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB
};
properties[5] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST, tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_NONE value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
}; };
var options = { var options = {
properties: properties properties: properties
}; };
var result = huks.generateKey(alias, options); var result = huks.generateKey(keyAlias, options);
``` ```
## huks.deleteKey ## huks.deleteKey
...@@ -474,11 +468,12 @@ Deletes a key. This method uses an asynchronous callback to return the result. ...@@ -474,11 +468,12 @@ Deletes a key. This method uses an asynchronous callback to return the result.
**Example** **Example**
```js ```js
var alias = 'alias'; /* Set options to emptyOptions. */
var keyAlias = 'keyAlias';
var emptyOptions = { var emptyOptions = {
properties: [] properties: []
}; };
huks.deleteKey(alias, emptyOptions, function (err, data) {}); huks.deleteKey(keyAlias, emptyOptions, function (err, data) {});
``` ```
## huks.deleteKey ## huks.deleteKey
...@@ -500,16 +495,17 @@ Deletes a key. This method uses a promise to return the result. ...@@ -500,16 +495,17 @@ Deletes a key. This method uses a promise to return the result.
| Type | Description | | Type | Description |
| ----------------------------------- | -------------------------------------------------- | | ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned. For details about the error codes, see **HuksResult**.| | Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.|
**Example** **Example**
```js ```js
var alias = 'alias'; /* Set options to emptyOptions. */
var keyAlias = 'keyAlias';
var emptyOptions = { var emptyOptions = {
properties: [] properties: []
}; };
var result = huks.deleteKey(alias, emptyOptions); var result = huks.deleteKey(keyAlias, emptyOptions);
``` ```
## huks.getSdkVersion ## huks.getSdkVersion
...@@ -535,6 +531,7 @@ Obtains the SDK version of the current system. ...@@ -535,6 +531,7 @@ Obtains the SDK version of the current system.
**Example** **Example**
```js ```js
/* Set options to emptyOptions. */
var emptyOptions = { var emptyOptions = {
properties: [] properties: []
}; };
...@@ -560,31 +557,41 @@ Imports a key. This method uses an asynchronous callback to return the result. ...@@ -560,31 +557,41 @@ Imports a key. This method uses an asynchronous callback to return the result.
**Example** **Example**
```js ```js
/* Import an AES key of 256 bits. */
var plainTextSize32 = makeRandomArr(32);
function makeRandomArr(size) {
var arr = new Uint8Array(size);
for (var i = 0; i < size; i++) {
arr[i] = Math.floor(Math.random() * 10);
}
return arr;
};
var keyAlias = 'keyAlias'; var keyAlias = 'keyAlias';
var properties = new Array(); var properties = new Array();
properties[0] = { properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_DSA value: huks.HuksKeyAlg.HUKS_ALG_AES
}; };
properties[1] = { properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: 1024 value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256
}; };
properties[2] = { properties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE, tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY value:
huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
}; };
properties[3] = { properties[3] = {
tag: huks.HuksTag.HUKS_TAG_PADDING, tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_NONE value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7
}; };
properties[4] = { properties[4] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST, tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: HUKS_DIGEST_SHA1 value: huks.HuksCipherMode.HUKS_MODE_ECB
}; };
var options = { var options = {
properties: properties, properties: properties,
inData: importText inData: plainTextSize32
}; };
huks.importKey(keyAlias, options, function (err, data){}); huks.importKey(keyAlias, options, function (err, data){});
``` ```
...@@ -608,38 +615,50 @@ Imports a key. This method uses a promise to return the result. ...@@ -608,38 +615,50 @@ Imports a key. This method uses a promise to return the result.
| Type | Description | | Type | Description |
| ----------------------------------- | -------------------------------------------------- | | ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned. For details about the error codes, see **HuksResult**.| | Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.|
**Example** **Example**
```js ```js
/* Import an AES key of 128 bits. */
var plainTextSize32 = makeRandomArr(32);
function makeRandomArr(size) {
var arr = new Uint8Array(size);
for (var i = 0; i < size; i++) {
arr[i] = Math.floor(Math.random() * 10);
}
return arr;
};
/* Step 1 Generate a key. */
var keyAlias = 'keyAlias'; var keyAlias = 'keyAlias';
var properties = new Array(); var properties = new Array();
properties[0] = { properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM, tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_DSA value: huks.HuksKeyAlg.HUKS_ALG_AES
}; };
properties[1] = { properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: 1024 value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128
}; };
properties[2] = { properties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE, tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT
}; };
properties[3] = { properties[3] = {
tag: huks.HuksTag.HUKS_TAG_PADDING, tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_NONE value:huks.HuksKeyPadding.HUKS_PADDING_PKCS7
}; };
properties[4] = { properties[4] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST, tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: HUKS_DIGEST_SHA1 value: huks.HuksCipherMode.HUKS_MODE_ECB
}; };
var options = { var huksoptions = {
properties: properties, properties: properties,
inData: importText inData: plainTextSize32
}; };
var result = huks.importKey(keyAlias, options); var result = huks.importKey(keyAlias, huksoptions);
``` ```
## huks.exportKey ## huks.exportKey
...@@ -656,11 +675,12 @@ Exports a key. This method uses an asynchronous callback to return the result. ...@@ -656,11 +675,12 @@ Exports a key. This method uses an asynchronous callback to return the result.
| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | | keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. |
| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). |
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned. For details about the error codes, see **HuksResult**.<br/>**outData** contains the public key exported.| | callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned. **outData** contains the public key exported.|
**Example** **Example**
```js ```js
/* Set options to emptyOptions. */
var keyAlias = 'keyAlias'; var keyAlias = 'keyAlias';
var emptyOptions = { var emptyOptions = {
properties: [] properties: []
...@@ -692,6 +712,7 @@ Exports a key. This method uses a promise to return the result. ...@@ -692,6 +712,7 @@ Exports a key. This method uses a promise to return the result.
**Example** **Example**
```js ```js
/* Set options to emptyOptions. */
var keyAlias = 'keyAlias'; var keyAlias = 'keyAlias';
var emptyOptions = { var emptyOptions = {
properties: [] properties: []
...@@ -713,11 +734,12 @@ Obtains key properties. This method uses an asynchronous callback to return the ...@@ -713,11 +734,12 @@ Obtains key properties. This method uses an asynchronous callback to return the
| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | | keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. |
| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). |
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. In **errorCode**, **HUKS_SUCCESS** will be returned if the operation is successful; an error code will be returned otherwise. For details about the error codes, see **HuksResult**.| | callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. **HUKS_SUCCESS** will be returned if the operation is successful; an error code will be returned otherwise.|
**Example** **Example**
```js ```js
/* Set options to emptyOptions. */
var keyAlias = 'keyAlias'; var keyAlias = 'keyAlias';
var emptyOptions = { var emptyOptions = {
properties: [] properties: []
...@@ -744,11 +766,12 @@ Obtains key properties. This method uses a promise to return the result. ...@@ -744,11 +766,12 @@ Obtains key properties. This method uses a promise to return the result.
| Type | Description | | Type | Description |
| ------------------ | ------------------------------------------------------------ | | ------------------ | ------------------------------------------------------------ |
| Promise\<[HuksResult](#huksoptions)> | Promise used to return the result. In **errorCode**, **HUKS_SUCCESS** will be returned if the operation is successful; an error code will be returned otherwise. For details about the error codes, see **HuksResult**.| | Promise\<[HuksResult](#huksoptions)> | Promise used to return the result. In the return result, **HUKS_SUCCESS** will be returned for **errorCode** if the operation is successful; an error code will be returned otherwise. **properties** returns the parameters required for generating the key.|
**Example** **Example**
```js ```js
/* Set options to emptyOptions. */
var keyAlias = 'keyAlias'; var keyAlias = 'keyAlias';
var emptyOptions = { var emptyOptions = {
properties: [] properties: []
...@@ -775,6 +798,7 @@ Checks whether a key exists. This method uses an asynchronous callback to return ...@@ -775,6 +798,7 @@ Checks whether a key exists. This method uses an asynchronous callback to return
**Example** **Example**
```js ```js
/* Set options to emptyOptions. */
var keyAlias = 'keyAlias'; var keyAlias = 'keyAlias';
var emptyOptions = { var emptyOptions = {
properties: [] properties: []
...@@ -806,6 +830,7 @@ Checks whether a key exists. This method uses a promise to return the result. ...@@ -806,6 +830,7 @@ Checks whether a key exists. This method uses a promise to return the result.
**Example** **Example**
```js ```js
/* Set options to emptyOptions. */
var keyAlias = 'keyAlias'; var keyAlias = 'keyAlias';
var emptyOptions = { var emptyOptions = {
properties: [] properties: []
...@@ -814,6 +839,7 @@ var result = huks.isKeyExist(keyAlias, emptyOptions); ...@@ -814,6 +839,7 @@ var result = huks.isKeyExist(keyAlias, emptyOptions);
``` ```
## huks.init ## huks.init
init(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksHandle>) : void init(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksHandle>) : void
...@@ -830,34 +856,6 @@ Initializes a key. This method uses an asynchronous callback to return the resul ...@@ -830,34 +856,6 @@ Initializes a key. This method uses an asynchronous callback to return the resul
| options | [HuksOptions](#huksoptions) | Yes | Parameter set of the **Init** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameter set of the **Init** operation.|
| callback | AsyncCallback\<[HuksHandle](#hukshandle)> | Yes | Callback used to return the handle of the **Init** operation.| | callback | AsyncCallback\<[HuksHandle](#hukshandle)> | Yes | Callback used to return the handle of the **Init** operation.|
**Example**
```js
var alias = 'test001'
var properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HksKeyAlg.HKS_ALG_DH
};
properties[1] = {
tag: huks.HksTag.HKS_TAG_PURPOSE,
value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE
};
properties[2] = {
tag: huks.HksTag.HKS_TAG_KEY_SIZE,
value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096
};
var options = {
properties: properties
};
huks.init(alias, options, function(err, data) {
if (err.code !== 0) {
console.log("test init err information: " + JSON.stringify(err));
} else {
console.log(`test init data: ${JSON.stringify(data)}`);
}
})
```
## huks.init ## huks.init
...@@ -875,39 +873,6 @@ Initializes a key. This method uses a promise to return the result. ...@@ -875,39 +873,6 @@ Initializes a key. This method uses a promise to return the result.
| options | [HuksOptions](#huksoptions) | Yes | Parameter set of the **Init** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameter set of the **Init** operation.|
| promise | Promise\<[HuksHandle](#hukshandle)> | Yes | Promise used to return the handle of the **Init** operation.| | promise | Promise\<[HuksHandle](#hukshandle)> | Yes | Promise used to return the handle of the **Init** operation.|
**Example**
```js
var alias = 'test001'
var properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HksKeyAlg.HKS_ALG_DH
};
properties[1] = {
tag: huks.HksTag.HKS_TAG_PURPOSE,
value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE
};
properties[2] = {
tag: huks.HksTag.HKS_TAG_KEY_SIZE,
value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096
};
var options = {
properties: properties
};
huks.init(alias, options).then((data) => {
console.log(`test init data: ${JSON.stringify(data)}`);
handle1 = data.handle1;
handle2 = data.handle2;
handle = {
"handle1": handle1,
"handle2": handle2
};
}).catch((err) => {
console.log("test init err information: " + JSON.stringify(err))
})
```
## huks.update ## huks.update
...@@ -926,27 +891,6 @@ Updates a key. This method uses an asynchronous callback to return the result. ...@@ -926,27 +891,6 @@ Updates a key. This method uses an asynchronous callback to return the result.
| options | [HuksOptions](#huksoptions) | Yes | Parameter set of the **Update** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameter set of the **Update** operation.|
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback used to return the operation result.| | callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback used to return the operation result.|
**Example**
```js
var properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HksKeyAlg.HKS_ALG_DH
};
properties[1] = {
tag: huks.HksTag.HKS_TAG_PURPOSE,
value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE
};
properties[2] = {
tag: huks.HksTag.HKS_TAG_KEY_SIZE,
value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096
};
var options = {
properties: properties
};
huks.update(handle, options, function (err, data){});
```
## huks.update ## huks.update
...@@ -965,27 +909,6 @@ Updates a key. This method uses a promise to return the result. ...@@ -965,27 +909,6 @@ Updates a key. This method uses a promise to return the result.
| options | [HuksOptions](#huksoptions) | Yes | Parameter set of the **Update** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameter set of the **Update** operation.|
| promise | Promise\<[HuksResult](#huksresult)> | Yes| Promise used to return the operation result.| | promise | Promise\<[HuksResult](#huksresult)> | Yes| Promise used to return the operation result.|
**Example**
```js
var properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HksKeyAlg.HKS_ALG_DH
};
properties[1] = {
tag: huks.HksTag.HKS_TAG_PURPOSE,
value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE
};
properties[2] = {
tag: huks.HksTag.HKS_TAG_KEY_SIZE,
value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096
};
var options = {
properties: properties
};
var result = huks.update(handle, options)
```
## huks.finish ## huks.finish
...@@ -1003,27 +926,6 @@ Completes the key operation and releases resources. This method uses an asynchro ...@@ -1003,27 +926,6 @@ Completes the key operation and releases resources. This method uses an asynchro
| options | [HuksOptions](#huksoptions) | Yes | Parameter set of the **Finish** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameter set of the **Finish** operation.|
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback used to return the operation result.| | callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback used to return the operation result.|
**Example**
```js
var properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HksKeyAlg.HKS_ALG_DH
};
properties[1] = {
tag: huks.HksTag.HKS_TAG_PURPOSE,
value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE
};
properties[2] = {
tag: huks.HksTag.HKS_TAG_KEY_SIZE,
value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096
};
var options = {
properties: properties
};
huks.finish(handle, options, function (err, data){});
```
## huks.finish ## huks.finish
...@@ -1041,28 +943,6 @@ Completes the key operation and releases resources. This method uses a promise t ...@@ -1041,28 +943,6 @@ Completes the key operation and releases resources. This method uses a promise t
| options | [HuksOptions](#huksoptions) | Yes | Parameter set of the **Finish** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameter set of the **Finish** operation.|
| promise | Promise\<[HuksResult](#HuksResult)> | Yes| Promise used to return the operation result.| | promise | Promise\<[HuksResult](#HuksResult)> | Yes| Promise used to return the operation result.|
**Example**
```js
var properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HksKeyAlg.HKS_ALG_DH
};
properties[1] = {
tag: huks.HksTag.HKS_TAG_PURPOSE,
value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE
};
properties[2] = {
tag: huks.HksTag.HKS_TAG_KEY_SIZE,
value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096
};
var options = {
properties: properties
};
var result = huks.finish(handle, options)
```
## huks.abort ## huks.abort
...@@ -1083,23 +963,213 @@ Aborts the use of the key. This method uses an asynchronous callback to return t ...@@ -1083,23 +963,213 @@ Aborts the use of the key. This method uses an asynchronous callback to return t
**Example** **Example**
```js ```js
/* huks.init, huks.update, and huks.finish must be used together.
* If an error occurs in any of them, huks.abort must be called to terminate the use of the key.
*
* The following uses the callback of an RSA 1024-bit key as an example.
*/
import router from '@system.router';
import huks from '@ohos.security.huks';
async function routePage() {
let options = {
uri: 'pages/second'
}
try {
await router.push(options)
} catch (err) {
console.error(`fail callback, code: ${err.code}, msg: ${err.msg}`)
}
}
var alias = "HuksDemoRSA";
var properties = new Array(); var properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HksKeyAlg.HKS_ALG_DH
};
properties[1] = {
tag: huks.HksTag.HKS_TAG_PURPOSE,
value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE
};
properties[2] = {
tag: huks.HksTag.HKS_TAG_KEY_SIZE,
value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096
};
var options = { var options = {
properties: properties properties: properties,
inData: new Uint8Array(0)
}; };
huks.abort(handle, options, function (err, data){}); var handle = {};
var resultMessage = "";
async function generateKey() {
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_RSA
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_1024
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
};
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_OAEP
};
properties[4] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
};
huks.generateKey(alias, options);
}
function stringToUint8Array(str) {
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
var tmpUint8Array = new Uint8Array(arr);
return tmpUint8Array;
}
async function huksInit() {
await huks.init(alias, options).then((data) => {
console.log(`test init data: ${JSON.stringify(data)}`);
handle = {
"handle1": data.handle1,
"handle2": data.handle2
};
}).catch((err) => {
console.log("test init err information: " + JSON.stringify(err))
})
}
async function huksUpdate() {
let count = 2;
for (let i = 0; i < count; i++) {
options.inData = stringToUint8Array("huksHmacTest");
await huks.update(handle, options).then((data) => {
if (data.errorCode === 0) {
resultMessage += "update success!";
} else {
resultMessage += "update fail!";
}
}).catch((err) => {
resultMessage += "update times: " + count + (i + 1) + " fail catch errorMessage:" + JSON.stringify(err) + " "
});
console.log(resultMessage);
}
}
function huksFinish() {
options.inData = stringToUint8Array("HuksDemoHMAC");
huks.finish(handle, options).then((data) => {
if (data.errorCode === 0) {
resultMessage = "finish success!";
} else {
resultMessage = "finish fail errorCode: " + data.errorCode;
}
}).catch((err) => {
resultMessage = "Failed to complete the key operation. catch errorMessage:" + JSON.stringify(err)
});
console.log(resultMessage);
}
async function huksAbort() {
huks.abort(handle, options).then((data) => {
if (data.errorCode === 0) {
resultMessage = "abort success!";
} else {
resultMessage = "abort fail errorCode: " + data.errorCode;
}
}).catch((err) => {
resultMessage = "Failed to abort the use of the key. catch errorMessage:" + JSON.stringify(err)
});
console.log(resultMessage);
}
@Entry
@Component
struct Index {
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text('Hello World')
.fontSize(50)
.fontWeight(FontWeight.Bold)
Button() {
Text('Tocallback')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.width('50%')
.height('10%')
.backgroundColor('#0D9FFB')
.onClick(() => {
routePage()
})
Button() {
Text('generateKey')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.width('50%')
.height('10%')
.backgroundColor('#0D9FFB')
.onClick(() => {
generateKey()
})
Button() {
Text('huksInit')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.width('50%')
.height('10%')
.backgroundColor('#0D9FFB')
.onClick(() => {
huksInit()
})
Button() {
Text('huksUpdate')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.width('50%')
.height('10%')
.backgroundColor('#0D9FFB')
.onClick(() => {
huksUpdate()
})
Button() {
Text('huksFinish')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.width('50%')
.height('10%')
.backgroundColor('#0D9FFB')
.onClick(() => {
huksFinish()
})
Button() {
Text('huksAbort')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.width('50%')
.height('10%')
.backgroundColor('#0D9FFB')
.onClick(() => {
huksAbort()
})
}
.width('100%')
.height('100%')
}
}
``` ```
## huks.abort ## huks.abort
...@@ -1121,23 +1191,216 @@ Aborts the use of the key. This method uses a promise to return the result. ...@@ -1121,23 +1191,216 @@ Aborts the use of the key. This method uses a promise to return the result.
**Example** **Example**
```js ```js
/* huks.init, huks.update, and huks.finish must be used together.
* If an error occurs in any of them, huks.abort must be called to terminate the use of the key.
*
* The following uses the promise of an RSA 1024-bit key as an example.
*/
import router from '@system.router';
import huks from '@ohos.security.huks';
async function routePage() {
let options = {
uri: 'pages/second'
}
try {
await router.push(options)
} catch (err) {
console.error(`fail callback, code: ${err.code}, msg: ${err.msg}`)
}
}
var alias = "HuksDemoRSA";
var properties = new Array(); var properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HksKeyAlg.HKS_ALG_DH
};
properties[1] = {
tag: huks.HksTag.HKS_TAG_PURPOSE,
value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE
};
properties[2] = {
tag: huks.HksTag.HKS_TAG_KEY_SIZE,
value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096
};
var options = { var options = {
properties: properties properties: properties,
}; inData: new Uint8Array(0)
var result = huks.abort(handle, options); };
var handle = {};
var resultMessage = "";
function stringToUint8Array(str) {
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
var tmpUint8Array = new Uint8Array(arr);
return tmpUint8Array;
}
async function generateKey() {
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_RSA
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_1024
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT
};
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_OAEP
};
properties[4] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
};
huks.generateKey(alias, options, function (err, data) { });
}
async function huksInit() {
return new Promise((resolve, reject) => {
huks.init(alias, options, async function (err, data) {
if (data.errorCode === 0) {
resultMessage = "Initialization successful!"
handle = {
"handle1": data.handle1,
"handle2": data.handle2
}
} else {
resultMessage = "init fail errorCode: " + data.errorCode
}
});
});
}
async function huksUpdate() {
let count = 2;
for (let i = 0; i < count; i++) {
options.inData = stringToUint8Array("huksHmacTest");
new Promise((resolve, reject) => {
huks.update(handle, options, function (err, data) {
if (data.errorCode === 0) {
resultMessage += "update success!";
} else {
resultMessage += "update fail!";
}
});
});
console.log(resultMessage);
}
}
async function huksFinish() {
options.inData = stringToUint8Array("0");
new Promise((resolve, reject) => {
huks.finish(handle, options, function (err, data) {
if (data.errorCode === 0) {
resultMessage = "finish success!";
} else {
resultMessage = "finish fail errorCode: " + data.errorCode;
}
});
});
}
function huksAbort() {
new Promise((resolve, reject) => {
huks.abort(handle, options, function (err, data) {
console.log(`Huks_Demo hmac huksAbort1 data ${JSON.stringify(data)}`);
console.log(`Huks_Demo hmac huksAbort1 err ${JSON.stringify(err)}`);
});
});
}
@Entry
@Component
struct Index {
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text('Hello World')
.fontSize(50)
.fontWeight(FontWeight.Bold)
Button() {
Text('to Promise')
.fontSize(20)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.width('50%')
.height('10%')
.backgroundColor('#0D9FFB')
.onClick(() => {
router.back()
})
Button() {
Text('generateKey')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.width('50%')
.height('10%')
.backgroundColor('#0D9FFB')
.onClick(() => {
generateKey()
})
Button() {
Text('huksInit')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.width('50%')
.height('10%')
.backgroundColor('#0D9FFB')
.onClick(() => {
huksInit()
})
Button() {
Text('huksUpdate')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.width('50%')
.height('10%')
.backgroundColor('#0D9FFB')
.onClick(() => {
huksUpdate()
})
Button() {
Text('huksFinish')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.width('50%')
.height('10%')
.backgroundColor('#0D9FFB')
.onClick(() => {
huksFinish()
})
Button() {
Text('huksAbort')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 20
})
.width('50%')
.height('10%')
.backgroundColor('#0D9FFB')
.onClick(() => {
huksAbort()
})
}
.width('100%')
.height('100%')
}
}
``` ```
## HuksParam ## HuksParam
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册