HarmonyOS 翻译代码?

转成ts后,发现有库找不到,不知道在ArkTS上怎么用?转换的ts代码:

import { CC_SHA256_DIGEST_LENGTH, CC_SHA256 } from 'crypto';
export function stringSHA256(content: string): string {
  const utf8Encoder = new TextEncoder();
  const keyData = utf8Encoder.encode(content);
  const digest = new Uint8Array(CC_SHA256_DIGEST_LENGTH);
  CC_SHA256(keyData, keyData.length, digest);
  const tokenBytes = new Uint32Array(digest.buffer);
  return `${tokenBytes[0].toString(16).padStart(8, '0')}${tokenBytes[1].toString(16).padStart(8, '0')}${tokenBytes[2].toString(16).padStart(8, '0')}${tokenBytes[3].toString(16).padStart(8, '0')}${tokenBytes[4].toString(16).padStart(8, '0')}${tokenBytes[5].toString(16).padStart(8, '0')}${tokenBytes[6].toString(16).padStart(8, '0')}${tokenBytes[7].toString(16).padStart(8, '0')}`;
}
阅读 433
1 个回答

TextEncoder用于将字符串编码为字节数组,支持多种编码格式,包括utf-8、utf-16le/be等。

TextDecoder用于将字节数组解码为字符串,可以处理多种编码格式,包括utf-8、utf-16le/be、iso-8859和windows-1251等不同的编码格式。

import { util } from '@kit.ArkTS';
// 创建编码器 
let textEncoder:util.TextEncoder = new util.TextEncoder('gbk');
let buffer:ArrayBuffer = new ArrayBuffer(20);
let encodeResult:Uint8Array = new Uint8Array(buffer);
// 编码 
encodeResult = textEncoder.encodeInto('hello');
console.info('Encode result: ', encodeResult);
// 创建解码器 
let textDecoder = util.TextDecoder.create('gbk');
// 解码 
let decodeResult = textDecoder.decodeWithStream(encodeResult);
console.info('Decode result: ', decodeResult);

SHA256可参考:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/crypto-generate-message-digest-V5\#%E6%91%98%E8%A6%81%E7%AE%97%E6%B3%95%E4%B8%80%E6%AC%A1%E6%80%A7%E4%BC%A0%E5%85%A5

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进