Web Crypto 加密,解密,生成密钥,签名

Tags
webapi
Created
Sep 23, 2018 2:59 PM

A CryptoKey object can be obtained using  SubtleCrypto.generateKey(), SubtleCrypto.deriveKey() (从另一个CryptoKey生成)or SubtleCrypto.importKey()  (从其它格式)

// extractable : 能否提取(SubtleCrypto.exportKey => ArrayBuffer),usages: 用途, 之间允许的key生成算法可能不一样

crypto.subtle.generateKey(

{ name: "ECDH", namedCurve: "P-256" },

true,          // false for production

['deriveBits'])

//crypto 另外一个属性

var array = new Uint32Array(10);

window.crypto.getRandomValues(array);

SHA-256算法字符串哈希值

====

function sha256(str) {

// We transform the string into an arraybuffer.

var buffer = new TextEncoder("utf-8").encode(str);

return crypto.subtle.digest("SHA-256", buffer).then(hash => {

// 返回数组缓存

return hex(hash);

});

}

function hex(buffer) { // 转成16进制

var hexCodes = [];

var view = new DataView(buffer);

for (var i = 0; i < view.byteLength; i += 4) {

// Using getUint32 reduces the number of iterations needed (we         process 4 bytes each time)

var value = view.getUint32(i)

// toString(16) will give the hex representation of the number without padding

var stringValue = value.toString(16)

// We use concatenation and slice for padding.

var padding = '00000000'

var paddedValue = (padding + stringValue).slice(-padding.length)

hexCodes.push(paddedValue);

}

// Join all the hex strings into one

return hexCodes.join("");

}

sha256("foobar").then(function(digest) {

console.log(digest);

}); // outputs “c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2"

SuperMade with Super