最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - TypeError when encrypting data using the WebAPI window.crypto.subtle.encrypt() - Stack Overflow

programmeradmin7浏览0评论

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...

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...

Share Improve this question edited Feb 17, 2017 at 18:30 Artjom B. 62k26 gold badges135 silver badges230 bronze badges asked Feb 17, 2017 at 16:09 wattswatts 1273 silver badges7 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

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

发布评论

评论列表(0)

  1. 暂无评论