http://www.oschina.net/code/snippet_552425_46178
<!doctype html>
<html>
<head>
<meta charset='UTF-8'>
</head>
<body>
<div class='test'></div>
<script type="text/javascript">
function encrypt(data, keyJSON){
var data = new TextEncoder("UTF-8").encode(data);
var randomsKeys = geneRandomHexStr(64); // 128 bit keys
var encryptedKey = hexStringToUint8Array(randomsKeys);
var aesAlgo = {name: 'aes-cbc', iv: hexStringToUint8Array("000102030405060708090a0b0c0d0e0f")};
return crypto.subtle.importKey("jwk", keyJSON, {name: "rsa-oaep", hash: {name: "sha-256"}},true, ['encrypt'])
.then(function(publicKey){
return crypto.subtle.encrypt({name: "rsa-oaep"}, publicKey, encryptedKey);
}).then(function(res){
encryptedKey = bytesToHexString(res)
// use aes to encrypt data
// import aes key
return crypto.subtle.importKey('raw',
hexStringToUint8Array(randomsKeys) , aesAlgo, false, ['encrypt', 'decrypt']);
}).then(function(result){
// use aes to encode
return crypto.subtle.encrypt(aesAlgo,
result, data);
}).then(function(encryptedData){
return Promise.resolve({
'encrypted': bytesToHexString(encryptedData),
'encryptedKey': encryptedKey,
});
});
//console.log(new TextDecoder("UTF-8").decode(data));
// use server public key to encrypt
}
function decrypt(data, keyJSON){
// use local private key to decrypt
var encryptedKey = new hexStringToUint8Array(data.encryptedKey);
var encryptedData = new hexStringToUint8Array(data.encrypted);
var aesAlgo = {name: 'aes-cbc', iv: hexStringToUint8Array("000102030405060708090a0b0c0d0e0f")};
// decrypt key
return crypto.subtle.importKey('jwk', keyJSON, {name: "rsa-oaep", hash: {name: "sha-256"}}, true,
['decrypt']).then(function(privateKey){