nextstarproject / tools-fe

Online pure front end tools by nextstarproject
https://tools.nextstar.space
GNU General Public License v3.0
0 stars 1 forks source link

使用SubtleCrypto来创建和加解密数据 #49

Closed SpiritLing closed 10 months ago

SpiritLing commented 12 months ago

来源:https://developer.mozilla.org/zh-CN/docs/Web/API/SubtleCrypto

sha256 加密并转换为Hex或者Base64

async function digestMessage(message) {
  const encoder = new TextEncoder();
  const data = encoder.encode(message);
  const hash = await crypto.subtle.digest("SHA-256", data);
  return hash;
}
undefined
var = await digestMessage("123")
function _arrayBufferToBase64( buffer ) {
    var binary = '';
    var bytes = new Uint8Array( buffer );
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode( bytes[ i ] );
    }
    return window.btoa( binary );
}
// 转换乱码
function ab2str(buf) {
    return String.fromCharCode.apply(null, new Uint16Array(buf));
}
function buf2hex(buffer) { // buffer is an ArrayBuffer
  return [...new Uint8Array(buffer)]
      .map(x => x.toString(16).padStart(2, '0'))
      .join('');
}

ECDSA 创建和导出

let keyPair = await window.crypto.subtle.generateKey(
  {
    name: "ECDSA",
    namedCurve: "P-384",
  },
  true,
  ["sign", "verify"],
);

const exported = await window.crypto.subtle.exportKey("jwk",keyPair.privateKey);

function ab2str(buf) {
  return String.fromCharCode.apply(null, new Uint8Array(buf));
}

/*
Export the given key and write it into the "exported-key" space.
*/
async function exportCryptoKey(key) {
  const exported = await window.crypto.subtle.exportKey("pkcs8", key);
  const exportedAsString = ab2str(exported);
  const exportedAsBase64 = window.btoa(exportedAsString);
  const pemExported = `-----BEGIN PRIVATE KEY-----\n${exportedAsBase64}\n-----END PRIVATE KEY-----`;
return pemExported;

}

await exportCryptoKey(keyPair.privateKey)
SpiritLing commented 10 months ago

已经完成函数创建,但是并未使用,其中base64 hex string 和 ArrayBuffer 相互转换 https://gist.github.com/SpiritLing/40ef15a79feebbe762e3aa9c5e4ccbcf