客户端公钥与服务端公钥不匹配问题
================

#### 问题现象

服务端java语言，API生成的ed25519和x25519公钥长度是32字节，而客户端的公钥getEncoded之后长度为44字节，两者不匹配，如何解决该问题？

问题代码如下：

_// x25519密钥对_
let keyGenX25519 = cryptoFramework.createAsyKeyGenerator('X25519');
let keyPairX25519 = keyGenX25519.generateKeyPairSync();
_// Ed25519密钥对_
let keyGenEd25519 = cryptoFramework.createAsyKeyGenerator('Ed25519');
let keyPairEd25519 = keyGenEd25519.generateKeyPairSync();
_// ed25519对x25519的公钥进行签名_
let publicKeyX25519: Uint8Array = keyPairX25519.pubKey.getEncoded().data

#### 背景知识

[getEncoded()](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-cryptoframework#getencoded)方法返回编码后的公钥，类型是Uint8Array，其长度为44字节。

#### 解决方案

使用[getAsyKeySpec](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-cryptoframework#getasykeyspec10)获取密钥参数，然后用[buffer.from](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-buffer#bufferfrom)根据密钥参数创建buffer对象，最后new Uint8Array()转换获取公钥。

代码如下：

import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { buffer } from '@kit.ArkTS';

@Entry
@Component
struct Index {
  build() {
    Row() {
      Button('公钥长度')
        .onClick(() => {
         _ // x25519密钥对_
          let keyGenX25519 = cryptoFramework.createAsyKeyGenerator('X25519');
          let keyPairX25519 = keyGenX25519.generateKeyPairSync();
        _  // Ed25519密钥对_
          let keyGenEd25519 = cryptoFramework.createAsyKeyGenerator('Ed25519');
          let keyPairEd25519 = keyGenEd25519.generateKeyPairSync();
          _// 转换32字节的公钥_
          let dd = keyPairEd25519.pubKey.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ED25519\_PK\_BN).toString(16); _// 步骤一_
          let cc = keyPairX25519.pubKey.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.X25519\_PK\_BN).toString(16);
          let publicKeyEd25519: Uint8Array = new Uint8Array(buffer.from(dd, 'hex').buffer); _// 步骤二_
          let publicKeyX25519: Uint8Array = new Uint8Array(buffer.from(cc, 'hex').buffer);
          console.info('hm-->', publicKeyX25519.length, publicKeyEd25519.length);
        });
    }
    .height('80%')
  }
}

日志打印：

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/6c/v3/USOh6HdpQIeccbvd6LoMgg/zh-cn_image_0000002628769116.png?HW-CC-KV=V1&HW-CC-Date=20260709T134158Z&HW-CC-Expire=86400&HW-CC-Sign=FEC213CD920054F1DDA564FD43E31594A02182409D8B838124B12A4A237A4F62 "点击放大")