如何使用服务端下发的RSA公钥（字符串）对明文数据进行加密
=============================

将服务器下发的RSA公钥字符串赋值给\`pubKeyStr\`，即可实现。具体代码参考如下：

import { buffer, util } from '@kit.ArkTS';
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
_/\*\*_
 _\* Encrypt using RSA asymmetric key (PKCS1 mode)_
 _\* @param message Clear text data to be encrypted_
 _\* @returns Encrypted string, encoded in base64 format_
 _\*/_
export async function encryptRSA(message: string) {
  _// Server issues RSA public key string (base64 encoding)_
  let pubKeyStr = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDFQArGDm5BXM4jHHuZGIb/kUoqrSjXkjqPLgrDmqBFxNyYsyxvyFRO10nStQwdRkQkh5lZ5sqC1G/z6lyDPpEySTBo9S5GLZ2Tj4yinNjcMXmOwiHfyQAQo9LwdlyTedwRchg0fYewWBVTVhGcWPowT1aA+GnQhYwNmaS/iKQsNQIDAQAB";
  _// Initialize Base64 tool instance_
  let base64Helper = new util.Base64Helper();
  _// Convert the public key to Uint8Array and package it as a DataBlob type_
  let pubKeyBlob: cryptoFramework.DataBlob = { data: base64Helper.decodeSync(pubKeyStr) };
  _// Create RSA key generator_
  let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024');
  _// Convert the public key wrapper data pubKeyBlob into a key pair type KeyPair_
  let keyPair = await rsaGenerator.convertKey(pubKeyBlob, null);
  _// Create a Cipher object_
  let cipher = cryptoFramework.createCipher('RSA1024|PKCS1');
  _// Initialize encryption mode and specify the key keyPair. pubKey_
  await cipher.init(cryptoFramework.CryptoMode.ENCRYPT\_MODE, keyPair.pubKey, null);
  _// Packaging requires encrypted plaintext_
  let plainTextBlob: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) };
  _// Pass in plaintext and retrieve encrypted data_
  let encryptBlob = await cipher.doFinal(plainTextBlob);
  _// Return encrypted string_
  return base64Helper.encodeToStringSync(encryptBlob.data);
}

**参考链接**

[使用RSA非对称密钥（PKCS1模式）加解密](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/crypto-rsa-asym-encrypt-decrypt-pkcs1)