interop.html 2.14 KB
Newer Older
Daniel Hofmann's avatar
Daniel Hofmann committed
1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html lang="de">
    <head>
        <meta charset="utf-8">
        <title>AES (in CBC mode) language interop tester</title>

        <!-- notes:
              - host locally!
        --!>
        <script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js"></script>
    </head>
    <body>
13
14
15
        <input id="plaintext" type="text" name="plaintext" autofocus="autofocus" placeholder="My Secret..">
        <p id="ciphertext"></p>
        <p id="key"></p>
Daniel Hofmann's avatar
Daniel Hofmann committed
16
17
18
19
    </body>
    <script>
        "use strict";

20
        var bs = 16;  // aes block size is 16 bytes
Daniel Hofmann's avatar
Daniel Hofmann committed
21

22
23
24
25
26
27
        document.getElementById('plaintext').onkeypress = function(e) {
          var event = e || window.event;
          var charCode = event.which || event.keyCode;
        
          if (charCode == '13') {  // enter pressed
            var plaintext = document.getElementById("plaintext").value;
Daniel Hofmann's avatar
Daniel Hofmann committed
28

29
30
31
            // note: no need for a key derivation functioni, we're _generating_ a key from scratch _every time_
            var key = CryptoJS.lib.WordArray.random(bs);
            var iv = CryptoJS.lib.WordArray.random(bs);
Daniel Hofmann's avatar
Daniel Hofmann committed
32

33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
            var opts = {iv: iv, keySize: bs, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7};
            var enc = CryptoJS.AES.encrypt(plaintext, key, opts);

            console.log('ciphertext: ' + enc.ciphertext.toString(CryptoJS.enc.Hex));
            console.log('key: ' + enc.key.toString(CryptoJS.enc.Hex));
            console.log('iv: ' + enc.iv.toString(CryptoJS.enc.Hex));

            /* note:
                - no need for urlencode, hex is perfectly fine for urls
                - decoding: unhex 'out', first 16 bytes are iv, rest is ciphertext
                - or: split 'out', unhex first 32 bytes for iv, unhex rest for ciphertext
             */
            var out = enc.iv.toString(CryptoJS.enc.Hex) + enc.ciphertext.toString(CryptoJS.enc.Hex);

            document.getElementById("ciphertext").textContent = 'iv + ciphertext: ' + out;
            document.getElementById("key").textContent = 'key: ' + enc.key.toString(CryptoJS.enc.Hex);
          }
        }
Daniel Hofmann's avatar
Daniel Hofmann committed
51
52
53
    </script>
</html>
<!-- vim: set tabstop=4 shiftwidth=4 expandtab: --!>