5

我正在尝试使用以下方法加密一些文本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的长度......44352

这可以解释错误,但我怎样才能从's创建一个实际的256位密钥?window.cryptoPBKDF2

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

4

1 回答 1

4

显示的长度是指 Base64 编码的密钥。根据显示的值,32 字节密钥的 Base64 编码长度为 44 字节(352 位),因此是正确的,请参见此处

该错误是第二个importKey(请参阅从 import 为 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 编码的。例如,可以使用 Base64 编码的密钥和 IV来验证密文。

于 2020-08-08T09:12:44.340 回答