我正在尝试使用 AES-CTR 算法解密浏览器上的数据。WebCrypto API要求将计数器作为BufferSource传递。如何将计数器(数字)转换为预期输入(字节数组)?
我使用的是全零 IV,因此计数器从 0 开始。假设我正在尝试解密计数器 = 445566 的数据。如何将 445566 转换为 ArrayBuffer?
const key = // retrieve decryption key
const encrypted = // retrieve encrypted data
const iv = new ArrayBuffer(16)
// iv is all zeros. I need it to represent 445566, how?
const algo = {
name: 'AES-CTR',
counter: iv,
length: 128
}
const decrypted = await crypto.subtle.decrypt(algo, key, encrypted)
Run Code Online (Sandbox Code Playgroud)
编辑:在挖掘了一些加密库之后,我最终使用了这个。它似乎做了我想做的事,但不知道正确性、性能等。
function numberToArrayBuffer(value) {
const view = new DataView(new ArrayBuffer(16))
for (var index = …Run Code Online (Sandbox Code Playgroud) 我正在使用Web Crypto API并使用generateKey函数生成RSA 密钥对。由于我的代码中存在一些错误,我删除了一些用户的公钥。我想知道是否有任何方法可以从私钥生成公钥?我知道这对于 ssh 密钥来说很容易实现。这是我生成 RSA 密钥对的示例代码:
const generateRSAKeys = (): Promise<CryptoKeyPair> => {
return crypto.subtle.generateKey(
{
name: 'RSA-OAEP',
modulusLength: 2048
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: { name: 'SHA-512' },
},
true,
['encrypt', 'decrypt', 'wrapKey', 'unwrapKey'],
);
Run Code Online (Sandbox Code Playgroud) javascript encryption rsa encryption-asymmetric webcrypto-api
在 Chrome 中,这会失败:
window.crypto.subtle.generateKey(
{
name: "RSA-OAEP",
modulusLength: 4096,
hash: {name: "SHA-256"},
},
true,
["sign", "verify", "encrypt", "decrypt"]
)
Run Code Online (Sandbox Code Playgroud)
为什么这是不可能的?为什么我无法创建可用于加密和签名的密钥对?RSA 密钥本身没有此限制。
我正在使用以下示例在Node.js中进行签名+验证:https://github.com/nodejs/node-v0.x-archive/issues/6904.验证在Node.js中成功,但在WebCrypto中失败.同样,使用WebCrypto签名的消息无法在Node.js中进行验证.
这是我用来验证使用WebCrypto从Node.js脚本生成的签名的代码 - https://jsfiddle.net/aj49e8sj/.在Chrome 54.0.2840.27和Firefox 48.0.2中进行了测试
// From https://github.com/nodejs/node-v0.x-archive/issues/6904
var keys = {
priv: '-----BEGIN EC PRIVATE KEY-----\n' +
'MHcCAQEEIF+jnWY1D5kbVYDNvxxo/Y+ku2uJPDwS0r/VuPZQrjjVoAoGCCqGSM49\n' +
'AwEHoUQDQgAEurOxfSxmqIRYzJVagdZfMMSjRNNhB8i3mXyIMq704m2m52FdfKZ2\n' +
'pQhByd5eyj3lgZ7m7jbchtdgyOF8Io/1ng==\n' +
'-----END EC PRIVATE KEY-----\n',
pub: '-----BEGIN PUBLIC KEY-----\n' +
'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEurOxfSxmqIRYzJVagdZfMMSjRNNh\n' +
'B8i3mXyIMq704m2m52FdfKZ2pQhByd5eyj3lgZ7m7jbchtdgyOF8Io/1ng==\n' +
'-----END PUBLIC KEY-----\n'
};
var message = (new TextEncoder('UTF-8')).encode('hello');
// Algorithm used in Node.js script is ecdsa-with-SHA1, key generated with prime256v1
var algorithm = {
name: 'ECDSA',
namedCurve: 'P-256',
hash: {
name: 'SHA-1'
}
};
// Signature …Run Code Online (Sandbox Code Playgroud) 我正在评估WebCrypto性能与第三方加密库SJCL和Forge的比较.我希望WebCrypto 更快,因为它是本机浏览器实现.这也已经过基准测试并且已经显示出来.
我使用Benchmark.js实现了以下测试来测试密钥派生(PBKDF2-SHA256),加密(AES-CBC)和解密(AES-CBC).这些测试显示web加密速度明显慢于SJCL和Forge加密/解密.
请看这里的小提琴:https://jsfiddle.net/kspearrin/1Lzvpzkz/
var iterations = 5000;
var keySize = 256;
sjcl.beware['CBC mode is dangerous because it doesn\'t protect message integrity.']();
// =========================================================
// Precomputed enc values for decrypt benchmarks
// =========================================================
var encIv = 'FX7Y3pYmcLIQt6WrKc62jA==';
var encCt = 'EDlxtzpEOfGIAIa8PkCQmA==';
// =========================================================
// Precomputed keys for benchmarks
// =========================================================
function sjclMakeKey() {
return sjcl.misc.pbkdf2('mypassword', 'a salt', iterations, keySize, null);
}
var sjclKey = sjclMakeKey();
function forgeMakeKey() …Run Code Online (Sandbox Code Playgroud) 使用JavaScript和WebCrypto API(不使用任何外部库),使用从用户提交的密码派生的密钥对字符串进行加密的最佳方法是什么?
这是一些代码,其中键不是派生的,而是仅由generatekey()函数生成的。目标是加密字符串,然后解密它以验证我们是否返回了原始字符串:
var secretmessage = "";
var password = "";
var key_object = null;
var promise_key = null;
var encrypted_data = null;
var encrypt_promise = null;
var vector = window.crypto.getRandomValues(new Uint8Array(16));
var decrypt_promise = null;
var decrypted_data = null;
function encryptThenDecrypt() {
secretmessage = document.getElementById("secretmessageField").value; // some string to encrypt
promise_key = window.crypto.subtle.generateKey(
{
name: "AES-GCM",
length: 128
},
false,
["encrypt", "decrypt"]
);
promise_key.then(function(key) {
key_object = key;
encrypt_data();
});
promise_key.catch = function(e) {
alert("Error while generating …Run Code Online (Sandbox Code Playgroud) 我有以下代码来使用 Javascript Webcrypto-API 解密 AES 加密数据,但它会导致“OperationError”,并显示消息“操作因操作特定原因而失败”:
function loadHexToArrybuffer(hex)
{
return new Uint8Array(hex.match(/[\da-f]{2}/gi).map(h => parseInt(h, 16)));
}
var iv = loadHexToArrybuffer("47b79d24e3ec47c528abdaed8f3fafde");
var rawKey = loadHexToArrybuffer("8af4d72873e4016cd73a1d5b851e9cb2");
var encryptedData = loadHexToArrybuffer("2bb7a12a7e59f9fa3c3d4ff0eb502cde3187338cc3137af785995b364fc5b3fe9c208f225c7472bb3de55de18a665863f63030d652b870c4610a70bc771e8bc584df7c3bd2ce3fc1940115e556178e740891f7cac450204a4959916ac9c9cd5aedd92cc7e74a7a581a6d47a6c29fb46eee13ffd3f70616844f8e2bb929c60ad9")
async function test()
{
var algorithm = {name: "AES-CBC", iv: iv};
var key = await window.crypto.subtle.importKey("raw", rawKey, algorithm, false, ["decrypt"]);
try
{
var decrypted = await window.crypto.subtle.decrypt(algorithm, key, encryptedData);
}
catch (e)
{
console.log(e); // OperationError: The operation failed for an operation-specific reason
}
}
test();Run Code Online (Sandbox Code Playgroud)
有人可以帮我吗?先谢谢了!
我正在尝试使用 webcrypto 运行代码,但似乎无法导入 ECDH 公钥。我错过了什么?
我收到此错误:无法使用指定的密钥用法创建密钥。
浏览器:Google Chrome 版本 71.0.3578.98(官方版本)(64 位)
(在 Firefox 上工作正常)。
window.crypto.subtle
.generateKey(
{
name: 'ECDH',
namedCurve: 'P-256',
},
true,
['deriveKey', 'deriveBits']
)
.then(function(key) {
return window.crypto.subtle
.exportKey('raw', key.publicKey)
.then(function(ecdhPub) {
return window.crypto.subtle
.importKey(
'raw',
ecdhPub,
{
name: 'ECDH',
namedCurve: 'P-256',
},
false,
['deriveKey', 'deriveBits']
)
.then(function(ecdhPubKey) {
console.log('DONE !!', ecdhPubKey)
})
.catch(function(err) {
console.log('COULD NOT IMPORT...')
console.error(err)
})
})
.catch(function(err) {
console.log('COULD NOT EXPORT...')
console.error(err)
})
})
.catch(function(err) {
console.log('COULD NOT GENERATE KEYS...')
console.error(err) …Run Code Online (Sandbox Code Playgroud)很难为javascript中的Web Crypto API设置熵或种子。
为什么会这样呢?这会使开发人员感到困难吗?
设置种子可让您确定地运行样本数据。Web Crypto API也恰好被烘焙到我正在使用的库中。我尝试实现的库的这一功能也几乎被放弃了,因为这个问题有多难。
在我的 Web 应用程序中,当用户注销我的应用程序并在再次登录后恢复它时,我试图将数据存储在本地存储中。此数据是私有的,因此在保存之前需要对其进行加密。由于该要求,该过程如下所示:
加密:
解密:
这是代码(打字稿):
interface Data {
queue: string;
initializationVector: string;
date: string;
}
private getEncryptionKey(): void {
const date: string = this.getDateParamForEncryptionKeyGeneration();
const params = new HttpParams().set('date', date);
this.encryptionKeyDate = DateSerializer.deserialize(date);
this.http.get(this.ENCRYPTION_KEY_ENDPOINT, {params}).subscribe((response: {key: string}) => {
const seed = response.key.slice(0, 32);
window.crypto.subtle.importKey(
'raw',
new TextEncoder().encode(seed),
'AES-GCM',
true,
['encrypt', 'decrypt']
).then(
(key: CryptoKey) => {
this.encryptionKey = key;
this.decrypt();
}
);
}); …Run Code Online (Sandbox Code Playgroud) webcrypto-api ×10
javascript ×6
encryption ×5
cryptography ×4
rsa ×2
aes ×1
benchmark.js ×1
ecdh ×1
ecdsa ×1
node.js ×1
passwords ×1
sjcl ×1
string ×1
typescript ×1