Reputation: 127
I ran into a problem when I tried to use the Crypto API on firefox. (doc) I get a TypeError when I try to encrypt a clear text using this function :
window.crypto.subtle.encrypt(algo_enc,key,padded_clear_txt);
(doc)
This is how I defined my parameters:
algo_enc:
var iv = new Int32Array(4) ;//4-32 bit integers (128 bits)
window.crypto.getRandomValues(iv); //defining the IV
var algo_enc = {"name": "AES-CBC", iv}
key:
var alg_key = {"name":"AES-CBC","length":128};
var key = window.crypto.subtle.generateKey(alg_key,false,["encrypt","decrypt"]);
padded-clear-txt is a 256 bits (2*128) message that I want to encrypt.
This is the error I get when I execute the encrypt function :
Argument 2 of SubtleCrypto.encrypt does not implement interface CryptoKey.
The generation of the key went well, and it's a CryptoKey object, but I still get this error. So maybe this is a bug I should report...
Upvotes: 4
Views: 6432
Reputation: 39241
WebCrypto functions return Promises. They are not synchronous. The result is received in a callback. See this full example
window.crypto.subtle.generateKey( { name: "AES-CBC", length: 128 }, false, ["encrypt", "decrypt"] )
.then(function(key){
var iv = window.crypto.getRandomValues(new Uint8Array(16))
window.crypto.subtle.encrypt({ name: "AES-CBC",iv: iv,}, key, dataToEncrypt )
.then(function(encrypted){
//returns an ArrayBuffer containing the encrypted data
}).catch(function(err){
console.error(err);
});
}).catch(function(err){
console.error(err);
});
Note that webcrypto uses ArrayBuffer for input and output data
Upvotes: 6