HarmonyOS 鸿蒙Next中JWT签名

HarmonyOS 鸿蒙Next中JWT签名 目前找到官放提供的JWT签名,这个应该是java版本的。有ArkTS版本的吗?

https://developer.huawei.com/consumer/cn/doc/atomic-guides/atomic-devicesecurity-deviceverify-token

8 回复

ArkTS目前未内置专门的JWT库,但可通过以下方式实现

第三方库

ohpm install [@ohos](/user/ohos)/jsonwebtoken
  1. 同步签名 ( 默认算法:HMAC SHA256 )
import jwt from "[@ohos](/user/ohos)/jsonwebtoken";
let token = jwt.sign({ foo: 'bar' }, 'shhhhh');
  1. 异步签名
jwt.sign({ foo: 'bar' }, privateKey, { algorithm: 'RS256' }, function(err, token) {
  console.log(token);
});
  1. RSA SHA256算法,使用私钥同步签名
// sign with RSA SHA256
let privateKey = "";
let token = jwt.sign({ foo: 'bar' }, privateKey, { algorithm: 'RS256' });
  1. RSA SHA256算法,使用公钥验证签名
let publicKey = ""
const decoded =  jwt.verify(signatrue,publicKey);

参考地址

[https://ohpm.openharmony.cn/#/cn/detail/@ohos%2Fjsonwebtoken](https://ohpm.openharmony.cn/#/cn/detail/@ohos%2Fjsonwebtoken)

更多关于HarmonyOS 鸿蒙Next中JWT签名的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


楼主可以通过原生加密能力结合第三方库实现,主要设计两个模块: @kit.UniversalKeystoreKit实现密钥管理与签名操作和处理Header/Payload编码及签名拼接或使用适配的第三方库。

实现步骤

  1. 构造Header/Payload:按JWT规范定义数据结构并Base614编码
  2. 签名生成:使用UniversalKeystoreKit进行数据签名
  3. JWT拼接:组合编码后的Header、Payload与签名生成最终Token

关键API

密钥生成/导入

import { huks } from '[@kit](/user/kit).UniversalKeystoreKit';

const keyAlias = 'jwt_signing_key';

const properties: huks.HuksOptions = {
  properties: [
    { tag: huks.HuksTag.HUKS_TAG_ALGORITHM, value: huks.HuksKeyAlg.HUKS_ALG_ECC },
    { tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 },
    { tag: huks.HuksTag.HUKS_TAG_PURPOSE, value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN }
  ]
};

await huks.generateKeyItem(keyAlias, properties);

数据签名

const handle = await huks.initSession(keyAlias, signOptions);

await huks.updateSession(handle, signOptions, dataToSign);

const signature = await huks.finishSession(handle, signOptions);

找HarmonyOS工作还需要会Flutter技术的哦,有需要Flutter教程的可以学学大地老师的教程,很不错,B站免费学的哦:https://www.bilibili.com/video/BV1S4411E7LY/?p=17

背景知识:

JSON Web Token(JWT)是一个开放的行业标准(RFC 7519),它定义了一种简洁的、自包含的协议格式,用于在通信双方传递json对象,传递的信息经过数字签名可以被验证和信任。ArkTs代码可以使用@ohos/jsonwebtoken。该库是一款适用于 openharmony 环境的 Json Web Token实现。

问题解决:

1、签名

try {
    let secretOrPrivateKey: string = "JWTPage"
    let token = jwt.sign({ name: 'xxxx' }, this.secretOrPrivateKey)
    console.log("JWTPage " + token)
    this.token = token
} catch (e) {
    console.error("JWTPage " + JSON.stringify(e))
}

2、验签

let res = jwt.verify(this.token, this.secretOrPrivateKey)
console.log("JWTPage " + JSON.stringify(res))

完整代码:

import jwt from "[@ohos](/user/ohos)/jsonwebtoken";


@Entry
@Component
struct JWTPage {
    @State message: string = 'Hello World';
    secretOrPrivateKey: string = "JWTPage"
    token: string = ""

    build() {
        Column() {
            Button("签名")
                .fontSize(20)
                .fontColor(Color.White)
                .fontWeight(FontWeight.Bold)
                .onClick(() => {
                    try {
                        let token = jwt.sign({ name: 'xxxx' }, this.secretOrPrivateKey)
                        console.log("JWTPage " + token)
                        this.token = token
                    } catch (e) {
                        console.error("JWTPage " + JSON.stringify(e))
                    }
                })

            Button("验签")
                .fontSize(20)
                .fontColor(Color.White)
                .fontWeight(FontWeight.Bold)
                .onClick(() => {
                    let res = jwt.verify(this.token, this.secretOrPrivateKey)
                    console.log("JWTPage " + JSON.stringify(res))
                })
        }
        .height('100%')
        .width('100%')
    }
}

日志:

cke_18586.png

三方仓库:https://ohpm.openharmony.cn/#/cn/detail/@ohos%2Fjsonwebtoken

如果您使用其他开发语言,请选择对应的JWT开源组件进行开发。

文档已经给了指引链接,这个应该只能后端语言生成,可以在指引的链接里面找一下自己语言的示例,

JWT签名在HarmonyOS Next中通过系统提供的安全模块实现,使用HMAC或RSA算法生成签名。签名过程基于Header、Payload和密钥,确保数据完整性和来源验证。鸿蒙Next的API支持直接调用签名功能,无需依赖外部库。

目前HarmonyOS Next官方暂未提供ArkTS版本的JWT签名实现。建议通过以下方式处理:

  1. 使用现有的Java实现,通过FFI(Foreign Function Interface)在ArkTS中调用
  2. 基于现有JWT规范自行实现ArkTS版本的签名算法(如HMAC-SHA256)
  3. 关注官方文档更新,后续可能会提供原生ArkTS支持

当前可参考提供的Java实现理解签名机制,再移植到ArkTS。

回到顶部