Skip to content

Commit b68e394

Browse files
committed
Interop/Javascript: add demo for AES-128-CBC
1 parent b54d8fd commit b68e394

1 file changed

Lines changed: 54 additions & 0 deletions

File tree

docs/javascript.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,60 @@ id: javascript
33
title: JavaScript
44
---
55

6+
## AES-128-CBC Decryption
7+
8+
Encrypting a string using AES-128-CBC with phpseclib:
9+
10+
```php
11+
use phpseclib3\Crypt\AES;
12+
13+
$cipher = new AES('cbc');
14+
$cipher->setKey(str_repeat('a', 16));
15+
$cipher->setIV(str_repeat('b', 16));
16+
17+
echo bin2hex($cipher->encrypt('test'));
18+
```
19+
20+
Decryption with JavaScript using [Web Cryptography API](https://en.wikipedia.org/wiki/Web_Cryptography_API):
21+
22+
```javascript
23+
var key = 'aaaaaaaaaaaaaaaa'
24+
var iv = 'bbbbbbbbbbbbbbbb';
25+
var ciphertext = '10f42fd95857ed2775cfbc4b471bc213';
26+
27+
function hex2ab(hex){
28+
return new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {return parseInt(h, 16)}));
29+
}
30+
31+
key = new TextEncoder().encode(key);
32+
iv = new TextEncoder().encode(iv);
33+
ciphertext = hex2ab(ciphertext);
34+
35+
window.crypto.subtle.importKey(
36+
'raw',
37+
key,
38+
{
39+
name: 'AES-CBC'
40+
},
41+
true, // can the key be extracted using SubtleCrypto.exportKey() / SubtleCrypto.wrapKey()?
42+
['decrypt'] // keyUsages
43+
).then(function(key) {
44+
window.crypto.subtle.decrypt(
45+
{
46+
name: "AES-CBC",
47+
iv: iv
48+
},
49+
key,
50+
ciphertext
51+
).then(function(plaintext) {
52+
console.log(new TextDecoder().decode(plaintext));
53+
})
54+
});
55+
```
56+
Note that although the specifications [do provide for AES-192-CBC](https://www.w3.org/TR/WebCryptoAPI/#aes-cbc-operations), Google Chrome [only supports AES-128-CBC and AES-256-CBC](https://sites.google.com/a/chromium.org/dev/blink/webcrypto#TOC-AES-support).
57+
58+
See it in action at https://jsfiddle.net/ewaysj3b/
59+
660
## RSA Decryption with Web Crypto API
761

862
Encryption with PHP:

0 commit comments

Comments
 (0)