hmac-export-key.html 2.44 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
<!DOCTYPE html>
<html>
<head>
<script src="../../resources/js-test-pre.js"></script>
<script src="resources/common.js"></script>
</head>
<body>
<p id="description"></p>
<div id="console"></div>

<script>
description("Test exporting an AES key.");

jsTestIsAsync = true;

var extractable = true;
17
var nonExtractable = false;
18 19 20 21 22 23

var jwkKey = {
    "kty": "oct",
    "k": "ahjkn-_387fgnsibf23qsvahjkn-_387fgnsibf23qs"
};

ap@apple.com's avatar
ap@apple.com committed
24
var jwkKeyAsArrayBuffer = asciiToUint8Array(JSON.stringify(jwkKey));
25 26

debug("Importing a JWK key...");
27
crypto.subtle.importKey("jwk", jwkKeyAsArrayBuffer, { name: "HMAC", hash: "SHA-256" }, extractable, ["sign", "verify"]).then(function(result) {
28 29
    key = result;

30 31 32 33 34 35
    shouldThrow('crypto.subtle.exportKey(null, key)');
    shouldThrow('crypto.subtle.exportKey(undefined, key)');
    shouldThrow('crypto.subtle.exportKey({}, key)');
    shouldThrow('crypto.subtle.exportKey("", key)');
    shouldThrow('crypto.subtle.exportKey("foobar", key)');

36 37 38 39
    debug("Exporting the key as raw data...");
    return crypto.subtle.exportKey("raw", key);
}).then(function(result) {
    exportedData = result;
ap@apple.com's avatar
ap@apple.com committed
40
    shouldBe("bytesToHexString(new Uint8Array(exportedData))", "'6a18e49feff7f3b7e09ec89b7f6deab2f6a18e49feff7f3b7e09ec89b7f6deab'");
41

42 43 44
    debug("Exporting the key as JWK...");
    return crypto.subtle.exportKey("jwk", key);
}).then(function(result) {
45
    exportedJWK = JSON.parse(bytesToASCIIString(result));
46 47 48
    shouldBe("exportedJWK.kty", "'oct'");
    shouldBe("exportedJWK.k", "'ahjkn-_387fgnsibf23qsvahjkn-_387fgnsibf23qs'");
    shouldBe("exportedJWK.alg", "'HS256'");
49
    shouldBe("exportedJWK.ext", "true");
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
    shouldBe("exportedJWK.use", "'sig'");

    debug("\nImporting a key that's not extractable...");
    return crypto.subtle.importKey("jwk", jwkKeyAsArrayBuffer, { name: "HMAC", hash: "SHA-256" }, nonExtractable, ["sign", "verify"]);
}).then(function(result) {
    key = result;

    debug("\nTrying to export as raw...");
    return crypto.subtle.exportKey("raw", key);
}).then(function(result) {
    testFailed("Promise wasn't rejected");
    finishJSTest();
}, function() {
    testPassed("Rejected, as expected");

    debug("Trying to export as jwk...");
    return crypto.subtle.exportKey("jwk", key);
}).then(function(result) {
    testFailed("Promise wasn't rejected");
    finishJSTest();
}, function() {
    testPassed("Rejected, as expected");

73 74 75 76 77 78 79
    finishJSTest();
});
</script>

<script src="../../resources/js-test-post.js"></script>
</body>
</html>