解决uniapp X 使用crypto-js进行sha256加密,在鸿蒙模拟器上运行白屏的问题。
console.log("应该是64的倍数:", paddedBytes.length % 64 === 0);console.log("结果长度:", result.length, "(应为64)");console.log("前10个字节:", bytes.slice(0, 10));console.log("转换后的字节数组长度:", bytes.length);console.log("=
已验证加密结果与使用crypto-js相同。
// sha256.uts
// 适配鸿蒙系统的纯 TypeScript SHA-256 实现
// 辅助函数:循环右移
function rightRotate(n: number, bits: number): number {
return ((n >>> bits) | (n << (32 - bits))) >>> 0;
}
// 鸿蒙兼容的字符串转字节函数
function stringToUtf8Bytes(message: string): number[] {
// 尝试多种方法
// 方法1: 使用鸿蒙的 TextEncoder
try {
if (typeof globalThis.requireNapi === 'function') {
const util = requireNapi('@ohos.util');
if (util && util.TextEncoder) {
const encoder = new util.TextEncoder('utf-8');
const result = encoder.encode(message);
console.log('使用鸿蒙 TextEncoder 成功');
return Array.from(result);
}
}
} catch (error) {
console.debug('鸿蒙 TextEncoder 不可用,尝试其他方法');
}
// 方法2: 使用标准 TextEncoder
try {
if (typeof TextEncoder !== 'undefined') {
const encoder = new TextEncoder();
const result = encoder.encode(message);
console.log('使用标准 TextEncoder 成功');
return Array.from(result);
}
} catch (error) {
console.debug('标准 TextEncoder 不可用');
}
// 方法3: 手动实现 UTF-8 编码(确保在所有平台一致)
console.log('使用手动 UTF-8 编码');
return manualUtf8Encode(message);
}
// 手动实现 UTF-8 编码
function manualUtf8Encode(str: string): number[] {
const bytes: number[] = [];
for (let i = 0; i < str.length; i++) {
let code = str.charCodeAt(i);
// 处理代理对(4字节 UTF-8)
if (code >= 0xD800 && code <= 0xDBFF && i + 1 < str.length) {
const second = str.charCodeAt(i + 1);
if (second >= 0xDC00 && second <= 0xDFFF) {
// 有效的代理对
code = ((code - 0xD800) << 10) + (second - 0xDC00) + 0x10000;
i++;
}
}
// UTF-8 编码
if (code < 0x80) {
// 1字节
bytes.push(code);
} else if (code < 0x800) {
// 2字节
bytes.push(0xC0 | (code >> 6));
bytes.push(0x80 | (code & 0x3F));
} else if (code < 0x10000) {
// 3字节
bytes.push(0xE0 | (code >> 12));
bytes.push(0x80 | ((code >> 6) & 0x3F));
bytes.push(0x80 | (code & 0x3F));
} else {
// 4字节
bytes.push(0xF0 | (code >> 18));
bytes.push(0x80 | ((code >> 12) & 0x3F));
bytes.push(0x80 | ((code >> 6) & 0x3F));
bytes.push(0x80 | (code & 0x3F));
}
}
return bytes;
}
export function sha256(message: string): string {
console.log("开始 SHA256 计算,输入:", message);
// 使用适配的字符串转字节函数
const bytes = stringToUtf8Bytes(message);
console.log("转换后的字节数组长度:", bytes.length);
console.log("前10个字节:", bytes.slice(0, 10));
// 初始化哈希值(与 CryptoJS 一致)
let h0 = 0x6a09e667;
let h1 = 0xbb67ae85;
let h2 = 0x3c6ef372;
let h3 = 0xa54ff53a;
let h4 = 0x510e527f;
let h5 = 0x9b05688c;
let h6 = 0x1f83d9ab;
let h7 = 0x5be0cd19;
// 常量 K(前 64 个质数的立方根的小数部分的前 32 位)
const K = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
];
// 填充
const originalLength = bytes.length * 8;
const paddedBytes = [...bytes]; // 复制一份,避免修改原数组
// 添加 0x80
paddedBytes.push(0x80);
// 填充 0x00 直到长度 mod 64 = 56
while ((paddedBytes.length % 64) !== 56) {
paddedBytes.push(0x00);
}
// 添加原始长度(64 位大端)
const lengthHi = Math.floor(originalLength / 0x100000000);
const lengthLo = originalLength;
// 添加高32位
for (let i = 24; i >= 0; i -= 8) {
paddedBytes.push((lengthHi >>> i) & 0xff);
}
// 添加低32位
for (let i = 24; i >= 0; i -= 8) {
paddedBytes.push((lengthLo >>> i) & 0xff);
}
console.log("填充后总长度:", paddedBytes.length);
console.log("应该是64的倍数:", paddedBytes.length % 64 === 0);
// 处理每个 512 位块
for (let i = 0; i < paddedBytes.length; i += 64) {
const w = new Array(64);
// 前 16 个 32 位字
for (let j = 0; j < 16; j++) {
w[j] = (paddedBytes[i + j * 4] << 24) |
(paddedBytes[i + j * 4 + 1] << 16) |
(paddedBytes[i + j * 4 + 2] << 8) |
paddedBytes[i + j * 4 + 3];
}
// 扩展到 64 个 32 位字
for (let j = 16; j < 64; j++) {
const s0 = rightRotate(w[j - 15], 7) ^ rightRotate(w[j - 15], 18) ^ (w[j - 15] >>> 3);
const s1 = rightRotate(w[j - 2], 17) ^ rightRotate(w[j - 2], 19) ^ (w[j - 2] >>> 10);
w[j] = (w[j - 16] + s0 + w[j - 7] + s1) >>> 0; // 使用 >>> 0 确保无符号
}
// 初始化工作变量
let a = h0, b = h1, c = h2, d = h3, e = h4, f = h5, g = h6, h = h7;
// 压缩循环
for (let j = 0; j < 64; j++) {
const S1 = rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25);
const ch = (e & f) ^ (~e & g);
const temp1 = (h + S1 + ch + K[j] + w[j]) >>> 0;
const S0 = rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22);
const maj = (a & b) ^ (a & c) ^ (b & c);
const temp2 = (S0 + maj) >>> 0;
h = g;
g = f;
f = e;
e = (d + temp1) >>> 0;
d = c;
c = b;
b = a;
a = (temp1 + temp2) >>> 0;
}
// 更新哈希值
h0 = (h0 + a) >>> 0;
h1 = (h1 + b) >>> 0;
h2 = (h2 + c) >>> 0;
h3 = (h3 + d) >>> 0;
h4 = (h4 + e) >>> 0;
h5 = (h5 + f) >>> 0;
h6 = (h6 + g) >>> 0;
h7 = (h7 + h) >>> 0;
}
// 转为十六进制字符串
const toHex = (n: number) => n.toString(16).padStart(8, '0');
const result = toHex(h0) + toHex(h1) + toHex(h2) + toHex(h3) +
toHex(h4) + toHex(h5) + toHex(h6) + toHex(h7);
console.log("SHA256 计算结果:", result);
console.log("结果长度:", result.length, "(应为64)");
return result;
}
// 测试函数
export function testSha256() {
console.log("=== 开始测试 SHA256 实现 ===");
const testCases = [
{ input: "", expected: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" },
{ input: "000000", expected: "84d89877f0d4041efb6bf91a16f0248f2fd573e6af05c19f96bedb9f882f7882" },
{ input: "123456", expected: "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92" },
{ input: "hello", expected: "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824" }
];
testCases.forEach(({ input, expected }) => {
const actual = sha256(input);
const isCorrect = actual === expected;
console.log(`输入: "${input}"`);
console.log(`期望: ${expected}`);
console.log(`实际: ${actual}`);
console.log(`结果: ${isCorrect ? "✅ 通过" : "❌ 失败"}`);
console.log("---");
});
}
更多推荐



所有评论(0)