window.crypto返回352位密钥而不是256位密钥?

时间:2020-08-08 07:45:12

标签: javascript encryption window.crypto

我正在尝试使用window.crypto加密一些文本:

await crypto.subtle.encrypt(algorithm, key, dataArrayBuffer).catch(error => console.error(error));

但是我收到此错误AES key data must be 128 or 256 bits。我正在使用PBKDF2从密码创建256位密钥,并且将密钥长度指定为256

window.crypto.subtle.deriveKey(
            {
                "name": "PBKDF2",
                "salt": salt,
                "iterations": iterations,
                "hash": hash
            },
            baseKey,
            {"name": "AES-GCM", "length": 256}, //<------------
            true, 
            ["encrypt", "decrypt"]
            );

但是我最终在得到edi5Fou4yCdSdx3DX3Org+L2XFAsVdomVgpVqUGjJ1g=后得到了这个密钥exportKey并将其从ArrayBuffer转换为string个字节,长度为44个字节和352位...

哪个会解释该错误,但是如何从256的{​​{1}}创建实际的window.crypto位密钥?

JSFiddle:https://jsfiddle.net/6Lyaoudc/1/

1 个答案:

答案 0 :(得分:4)

显示的长度是指Base64编码的密钥。根据显示的值,一个32字节的密钥具有44字节(352位)的Base64编码长度,因此是正确的,请参见例如。 here

错误在于,在第二个importKey中(请参见注释从导入创建AES-GCM的CryptoKey ),而不是通过了Base64编码的密钥(即keyString)二进制密钥(即ArrayBuffer keyBytes)。如果通过keyBytes,则加密有效:

function deriveAKey(password, salt, iterations, hash) {

    // First, create a PBKDF2 "key" containing the password
    window.crypto.subtle.importKey(
        "raw",
        stringToArrayBuffer(password),
        {"name": "PBKDF2"},
        false,
        ["deriveKey"]).
    then(function(baseKey){
        // Derive a key from the password
        return window.crypto.subtle.deriveKey(
            {
                "name": "PBKDF2",
                "salt": salt,
                "iterations": iterations,
                "hash": hash
            },
            baseKey,
            {"name": "AES-GCM", "length": 256}, // Key we want.Can be any AES algorithm ("AES-CTR", "AES-CBC", "AES-CMAC", "AES-GCM", "AES-CFB", "AES-KW", "ECDH", "DH", or "HMAC")
            true,                               // Extractable
            ["encrypt", "decrypt"]              // For new key
            );
    }).then(function(aesKey) {
        // Export it so we can display it
        return window.crypto.subtle.exportKey("raw", aesKey);
    }).then(async function(keyBytes) {
        // Display key in Base64 format
        var keyS = arrayBufferToString(keyBytes);
        var keyB64 = btoa (keyS);
        console.log(keyB64);
        
        console.log('Key byte size: ', byteCount(keyB64));
        console.log('Key bit size: ', byteCount(keyB64) * 8);
        
        var keyString = stringToArrayBuffer(keyB64);
    
        const iv = window.crypto.getRandomValues(new Uint8Array(12));

        const algorithm = {
          name: 'AES-GCM',
          iv: iv,
        };

        //Create CryptoKey for AES-GCM from import
        const key = await crypto.subtle.importKey(
          'raw',//Provided key will be of type ArrayBuffer
          // keyString,
          keyBytes,                                                    // 1. Use keyBytes instead of keyString
          {
            name: "AES-GCM",
          },
          false,//Key not extractable
          ['encrypt', 'decrypt']
        );

        //Convert data to ArrayBuffer
        var data = "The quick brown fox jumps over the lazy dog";      // 2. Define data
        const dataArrayBuffer = new TextEncoder().encode(data);

        const encryptedArrayBuffer = await crypto.subtle.encrypt(algorithm, key, dataArrayBuffer).catch(error => console.error(error));
        
        var ivB64 = btoa(arrayBufferToString(iv));
        console.log(ivB64);                                            // 3. Display (Base64 encoded) IV
        
        var encB64 = btoa(arrayBufferToString(encryptedArrayBuffer));
        console.log(encB64.replace(/(.{56})/g,'$1\n'));                // 4. Display (Base64 encoded) ciphertext (different for each encryption, because of random salt and IV)

    }).catch(function(err) {
        console.error("Key derivation failed: " + err.message);
    });
}

//Utility functions

function stringToArrayBuffer(byteString){
    var byteArray = new Uint8Array(byteString.length);
    for(var i=0; i < byteString.length; i++) {
        byteArray[i] = byteString.codePointAt(i);
    }
    return byteArray;
}

function  arrayBufferToString(buffer){
    var byteArray = new Uint8Array(buffer);
    var byteString = '';
    for(var i=0; i < byteArray.byteLength; i++) {
        byteString += String.fromCodePoint(byteArray[i]);
    }
    return byteString;
}

function byteCount(s) {
    return encodeURI(s).split(/%..|./).length - 1;
}

var salt = window.crypto.getRandomValues(new Uint8Array(16));
var iterations = 5000;
var hash = "SHA-512";
var password = "password";

deriveAKey(password, salt, iterations, hash);

除了密钥外,该代码还显示IV和密文,每个Base64都进行了编码。密文可以被验证,例如here使用Base64编码的密钥和IV。