import Jose from 'jose-jwe/dist/jose-commonjs';
const cryptographer = new Jose.Jose.WebCryptographer();
cryptographer.setContentEncryptionAlgorithm('A128CBC-HS256');
function createKeypair() {
if (!window.crypto || !window.crypto.subtle) {
return Promise.reject(new Error('crypto.subtle not available'));
}
const options = {
name: 'RSA-OAEP',
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]),
hash: {name: 'SHA-1'}
};
return window.crypto.subtle.generateKey(options, true, ['encrypt', 'decrypt'])
.then((keypair) => Promise.all([
window.crypto.subtle.exportKey('jwk', keypair.publicKey),
window.crypto.subtle.exportKey('jwk', keypair.privateKey)
]))
.then((keypair) => ({
publicKey: keypair[0],
privateKey: keypair[1]
}));
}
function encrypt(jwk, str) {
const cryptoKeyPromise = Jose.Jose.Utils.importRsaPublicKey(jwk, 'RSA-OAEP');
const encrypter = new Jose.JoseJWE.Encrypter(cryptographer, cryptoKeyPromise);
return encrypter.encrypt(str);
}
function decrypt(jwk, str) {
const cryptoKeyPromise = Jose.Jose.Utils.importRsaPrivateKey(jwk, 'RSA-OAEP');
const decrypter = new Jose.JoseJWE.Decrypter(cryptographer, cryptoKeyPromise);
return decrypter.decrypt(str);
}
createKeypair()
.then((keypair) => {
return encrypt(keypair.publicKey, 'this is a test')
.then((encrypted) => decrypt(keypair.privateKey, encrypted));
})
.then((decrypted) => console.log(decrypted))
.catch((err) => {
console.error(err);
});