目录

Cryptographic Algorithm

API Declaration

Add the following configuration to the features attribute in the manifest.json file:

{"name": "system.cipher"}

Module Import

Add the following configuration to the script element on the page where the API will be called:

import cipher from '@system.cipher'

Or

var cipher = require("@system.cipher")

Application Scope

Item

Description

Applicable devices

Mobile phones, tablets, and Vision products

Applicable regions

Global

Definition

API

Description

cipher.rsa(OBJECT)

Encrypts or decrypts data through RSA.

cipher.aes(OBJECT)

Encrypts or decrypts data through AES.

cipher.getRandomValues(int)

Obtains a random number.

[h2]cipher.rsa(OBJECT)

Description

Encrypts or decrypts data through RSA.

OBJECT parameters

Parameter

Type

Mandatory/Optional

Description

action

string

Mandatory

Encryption and decryption type. The options are as follows:

  • encrypt
  • decrypt

text

string

Mandatory

Text to be encrypted or decrypted. The text to be encrypted must be a common text. The text to be decrypted must be a binary value encoded using Base64. The default format is used for Base64 encoding.

key

string

Mandatory

RSA key used for encryption or decryption, which is a character string encrypted using Base64. During encryption, the parameter is a public key. During decryption, it is a private key.

transformation

string

Optional

RSA algorithm padding. The default value is RSA/None/OAEPWithSHA256AndMGF1Padding.

success

function

Optional

Callback upon success.

fail

function

Optional

Callback upon failure.

complete

function

Optional

Callback upon completion.

Parameters returned in success

Parameter

Type

Description

text

string

Text generated after encryption or decryption.

Result codes returned in fail

Result Code

Description

202

Incorrect input parameter.

Sample code

cipher.rsa({
     action: 'encrypt',
    // Text to be encrypted.
     text: '',
       transformation: 'RSA/None/OAEPWithSHA256AndMGF1Padding',
     // Encryption public key after Base64 encoding.
     key: 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDKmi0dUSVQ04hL6GZGPMFK8+d6\n' +
     'GzulagP27qSUBYxIJfE04KT+OHVeFFb6K+8nWDea5mkmZrIgp022zZVDgdWPNM62\n' +
     '3ouBwHlsfm2ekey8PpQxfXaj8lhM9t8rJlC4FEc0s8Qp7Q5/uYrowQbT9m6t7BFK\n' +
     '3egOO2xOKzLpYSqfbQIDAQAB',
     success: function(data){
       console.log("handling success: " + data.text);
     },
     fail: function (erromsg, errocode) {
       console. log ('cipher.rsa fail--------' + errocode + ': ' + erromsg);
     }
   });
var that=this;
cipher.rsa({
     action: 'decrypt',
    // Content to be decrypted, which is a binary value after Base64 encoding and a text after decryption.
     text: that.encryptedValue,
       transformation: 'RSA/None/OAEPWithSHA256AndMGF1Padding',
     // Private key for decryption after Base64 encoding.
     key: 'MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMqaLR1RJVDTiEvo\n' +
     'ZkY8wUrz53obO6VqA/bupJQFjEgl8TTgpP44dV4UVvor7ydYN5rmaSZmsiCnTbbN\n' +
     'lUOB1Y80zrbei4HAeWx+bZ6R7Lw+lDF9dqPyWEz23ysmULgURzSzxCntDn+5iujB\n' +
     'BtP2bq3sEUrd6A47bE4rMulhKp9tAgMBAAECgYBjsfRLPdfn6v9hou1Y2KKg+F5K\n' +
     'ZsY2AnIK+6l+sTAzfIAx7e0ir7OJZObb2eyn5rAOCB1r6RL0IH+MWaN+gZANNG9g\n' +
     'pXvRgcZzFY0oqdMZDuSJjpMTj7OEUlPyoGncBfvjAg0zdt9QGAG1at9Jr3i0Xr4X\n' +
     '6WrFhtfVlmQUY1VsoQJBAPK2Qj/ClkZNtrSDfoD0j083LcNICqFIIGkNQ+XeuTwl\n' +
     '+Gq4USTyaTOEe68MHluiciQ+QKvRAUd4E1zeZRZ02ikCQQDVscINBPTtTJt1JfAo\n' +
     'wRfTzA0Lvgig136xLLeQXREcgq1lzgkf+tGyUGYoy9BXsV0mOuYAT9ldja4jhJeq\n' +
     'cEulAkEAuSJ5KjV9dyb0RIFAz5C8d8o5KAodwaRIxJkPv5nCZbT45j6t9qbJxDg8\n' +
     'N+vghDlHI4owvl5wwVlAO8iQBy8e8QJBAJe9CVXFV0XJR/n/XnER66FxGzJjVi0f\n' +
     '185nOlFARI5CHG5VxxT2PUCo5mHBl8ctIj+rQvalvGs515VQ6YEVDCECQE3S0AU2\n' +
'BKyFVNtTpPiTyRUWqig4EbSXwjXdr8iBBJDLsMpdWsq7DCwv/ToBoLg+cQ4Crc5/\n' +
'5DChU8P30EjOiEo=',
     success: function(data){
       console.log("handling success: " + data.text);
     },
     fail: function (erromsg, errocode) {
       console. log ('cipher.rsa fail--------' + errocode + ': ' + erromsg);
     }
   });

[h2]cipher.aes(OBJECT) (1060+)

Description

Encrypts or decrypts data through AES.

OBJECT parameters

Parameter

Type

Mandatory/Optional

Description

action

string

Mandatory

Encryption and decryption type. The options are as follows:

  • encrypt
  • decrypt

text

string

Optional

Text to be encrypted or decrypted. The text to be encrypted must be a common text. The text to be decrypted must be a binary value encoded using Base64. The default format is used for Base64 encoding.

key

string

Optional

Key used for encryption or decryption, which is a character string encrypted using Base64. This parameter is required for processing the content specified by the text parameter.

transformation

string

Optional

Encryption mode and padding of the AES algorithm. The default value is AES/CBC/PKCS5Padding.

iv

string

Optional

Initial vector for AES-based encryption or decryption. The value is a character string encoded using Base64. The default value is the key value.

ivOffset

int

Optional

Offset of the initial vector for AES-based encryption or decryption. The default value is 0.

ivLen

int

Optional

Length of the initial vector for AES-based encryption or decryption. The default value is 16.

input(1079+)

ArrayBuffer

Optional

Content to be encrypted or decrypted. If text is set, the content set here will not be processed.

secretKey(1079+)

ArrayBuffer

Optional

Key used for encryption or decryption, which is required for processing the content specified by the input parameter.

initialVector(1079+)

ArrayBuffer

Optional

Initial vector for AES encryption and decryption, which is required for processing the content specified by the input parameter. If this parameter is not set, the value of secretKey will be used by default.

success

function

Optional

Callback upon success.

fail

function

Optional

Callback upon failure.

complete

function

Optional

Callback upon completion.

Parameters returned in success

Parameter

Type

Description

text

string

Text generated after encryption or decryption. The encrypted content is a binary value after Base64 encoding, and the decrypted content is a common text. If the decrypted content cannot be converted into a UTF-8 character string, an error occurs.

output(1079+)

ArrayBuffer

Encryption or decryption result of the value of input.

Result codes returned in fail

Result Code

Description

202

Incorrect input parameter.

Sample code

// Encryption
cipher.aes({
  action: 'encrypt',
  // Text to be encrypted.
  text: 'hello',
  // Key after Base64 encoding.
  key: 'NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=',
  transformation: 'AES/CBC/PKCS5Padding',
  ivOffset: 0,
  ivLen: 16,
  success: (data) => {
    console.log(`handling success: ${data.text}`)
  },
  fail: (data, code) => {
    console.log(`### cipher.aes fail ### ${code}: ${data}`)
  }
})
// Decryption
cipher.aes({
  action: 'decrypt',
  // Content to be decrypted, which is a binary value after Base64 encoding.
  text: '1o0kf2HXwLxHkSh5W5NhzA==\n',
  // Key after Base64 encoding.
  key: 'NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=',
  transformation: 'AES/CBC/PKCS5Padding',
  ivOffset: 0,
  ivLen: 16,
  success: (data) => {
    this.dealTxt = data.text
  },
  fail: (data, code) => {
    prompt.showToast({
      message: ("Decryption failed, code=" + code + ":" + data)
    })
  }
})

[h2]cipher.getRandomValues(int) (1073+)

Description

Obtains a random number.

OBJECT parameters

Type

Mandatory/Optional

Return Value

Description

int

Mandatory

string

When the input value is a positive integer ranging from 1 to 32, indicating the number of binary bits of a generated random number, a hexadecimal character string all in lowercase is returned.

For example, if the input value is 3 and the generated 3-digit random number is ['a','b','c'], 616263 is returned.

An empty string is returned in the case of invalid parameters or other exceptions.

Sample code

// Obtain a 16-digit random number and record logs.
let r16 = cipher.getRandomValues(16);
console.log(`random16:${r16}`);

Demo

<template>
  <!-- Only one root node is allowed in template. -->
  <div class="container">
    <input class="text" placeholder="please enter encrypt content" value="{{inputvale}}" onchange="getvalue" />
    <div class="cipherstyle">
      <input class="input" type="button" value="rsa encrypt" onclick="rsaencrypt" />
      <input class="input" type="button" value="rsa deciphering" onclick="rsadeciphering" />
      <input class="input" type="button" value="aes encrypt" onclick="aesencrypt" />
      <input class="input" type="button" value="aes deciphering" onclick="aesdeciphering" />
      <input class="input" type="button" value="getRandomValues" onclick="getRandomValues" />
    </div>
  </div>
</template>

<style>
    .container {
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }
    .cipherstyle {
      flex-direction: column;
      justify-content: center;
      align-items: center;
      width: 100%;
    }
    .text {
      font-size: 40px;
      width: 80%;
      height: 80px;
      margin-bottom: 10px;
    }
    .input {
      font-size: 50px;
      width: 80%;
      height: 80px;
      border-radius: 40px;
      margin-bottom: 10px;
      background-color: #00ced1;
    }
</style>

<script>
    import cipher from '@system.cipher';
    import prompt from '@system.prompt';
    module.exports = {
        data: {
            rsaencryptedValue: '',
            aesencryptedValue: '',
            inputvale: ''
        },
        onInit() {
            this.$page.setTitleBar({
                text: 'cipher',
                textColor: '#ffffff',
                backgroundColor: '#007DFF',
                backgroundOpacity: 0.5,
                menu: true
            });
        },
        getvalue(e) {
            this.inputvale = e.value;
            console.log(this.inputvale);
        },
        rsaencrypt() {
            var that = this;
            cipher.rsa({
                action: 'encrypt',
                text: that.inputvale,
                transformation: 'RSA/None/OAEPWithSHA256AndMGF1Padding',
                key: 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDKmi0dUSVQ04hL6GZGPMFK8+d6\n' +
                    'GzulagP27qSUBYxIJfE04KT+OHVeFFb6K+8nWDea5mkmZrIgp022zZVDgdWPNM62\n' +
                    '3ouBwHlsfm2ekey8PpQxfXaj8lhM9t8rJlC4FEc0s8Qp7Q5/uYrowQbT9m6t7BFK\n' +
                    '3egOO2xOKzLpYSqfbQIDAQAB',
                success: function (data) {
                    console.log("encrypt success: " + data.text);
                    that.rsaencryptedValue = data.text
                    prompt.showToast({
                        message: data.text,
                        duration: 2000,
                        gravity: 'center'
                    })
                },
                fail: function (erromsg, errocode) {
                    console.log('encrypt fail--------' + errocode + ': ' + erromsg);
                }
            });
        },
        rsadeciphering() {
            var that = this;
            cipher.rsa({
                action: 'decrypt',
                text: that.rsaencryptedValue,
                transformation: 'RSA/None/OAEPWithSHA256AndMGF1Padding',
                key: 'MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMqaLR1RJVDTiEvo\n' +
                    'ZkY8wUrz53obO6VqA/bupJQFjEgl8TTgpP44dV4UVvor7ydYN5rmaSZmsiCnTbbN\n' +
                    'lUOB1Y80zrbei4HAeWx+bZ6R7Lw+lDF9dqPyWEz23ysmULgURzSzxCntDn+5iujB\n' +
                    'BtP2bq3sEUrd6A47bE4rMulhKp9tAgMBAAECgYBjsfRLPdfn6v9hou1Y2KKg+F5K\n' +
                    'ZsY2AnIK+6l+sTAzfIAx7e0ir7OJZObb2eyn5rAOCB1r6RL0IH+MWaN+gZANNG9g\n' +
                    'pXvRgcZzFY0oqdMZDuSJjpMTj7OEUlPyoGncBfvjAg0zdt9QGAG1at9Jr3i0Xr4X\n' +
                    '6WrFhtfVlmQUY1VsoQJBAPK2Qj/ClkZNtrSDfoD0j083LcNICqFIIGkNQ+XeuTwl\n' +
                    '+Gq4USTyaTOEe68MHluiciQ+QKvRAUd4E1zeZRZ02ikCQQDVscINBPTtTJt1JfAo\n' +
                    'wRfTzA0Lvgig136xLLeQXREcgq1lzgkf+tGyUGYoy9BXsV0mOuYAT9ldja4jhJeq\n' +
                    'cEulAkEAuSJ5KjV9dyb0RIFAz5C8d8o5KAodwaRIxJkPv5nCZbT45j6t9qbJxDg8\n' +
                    'N+vghDlHI4owvl5wwVlAO8iQBy8e8QJBAJe9CVXFV0XJR/n/XnER66FxGzJjVi0f\n' +
                    '185nOlFARI5CHG5VxxT2PUCo5mHBl8ctIj+rQvalvGs515VQ6YEVDCECQE3S0AU2\n' +
                    'BKyFVNtTpPiTyRUWqig4EbSXwjXdr8iBBJDLsMpdWsq7DCwv/ToBoLg+cQ4Crc5/\n' +
                    '5DChU8P30EjOiEo=',
                success: function (data) {
                    console.log("decrypt success: " + data.text);
                    prompt.showToast({
                        message: data.text,
                        duration: 2000,
                        gravity: 'center'
                    })
                },
                fail: function (erromsg, errocode) {
                    console.log('decrypt fail--------' + errocode + ': ' + erromsg);
                }
            });
        },
        aesencrypt() {
            var that = this
            cipher.aes({
                action: 'encrypt',
                text: that.inputvale,
                key: 'NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=',
                transformation: 'AES/CBC/PKCS5Padding',
                ivOffset: 0,
                ivLen: 16,
                success: (data) => {
                    console.log(`encrypt success: ${data.text}`)
                    that.aesencryptedValue = data.text
                    prompt.showToast({
                        message: data.text,
                        duration: 2000,
                        gravity: 'center'
                    })
                },
                fail: (data, code) => {
                    console.log(`encrypt fail ### ${code}: ${data}`)
                }
            })
        },
        aesdeciphering() {
            var that = this
            cipher.aes({
                action: 'decrypt',
                text: that.aesencryptedValue,
                key: 'NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=',
                transformation: 'AES/CBC/PKCS5Padding',
                ivOffset: 0,
                ivLen: 16,
                success: (data) => {
                    this.dealTxt = data.text
                    console.log("decrypt success: " + data.text);
                    prompt.showToast({
                        message: data.text,
                        duration: 2000,
                        gravity: 'center'
                    })
                },
                fail: (data, code) => {
                    console.log(`decrypt fail ### ${code}: ${data}`);
                }
            })
        },
        getRandomValues() {
            let r16 = cipher.getRandomValues(16);
            console.log(`random16:${r16}`);
            prompt.showToast({
                message: `random16:${r16}`,
                duration: 2000,
                gravity: 'center'
            })
        }
    }
</script>

The following figure shows the final effect.

Version Change History

Version

Date

Description

1060

2019-12-10

Added the cipher.aes method.