Skip to content

Commit 90a5ed2

Browse files
save file
1 parent 6e52ff7 commit 90a5ed2

1 file changed

Lines changed: 27 additions & 5 deletions

File tree

blog/26-04-26/x509-certificates-in-js---encrypt-decrypt-data/ex/rsa-encrypt-decrypt-browser.js

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11

22

33

4+
var forge;
5+
46
!async function(){
57
console.clear();
68

7-
var {forge} = await import('https://libs.ext-code.com/external/js/node-forge/node-forge.m.js');
9+
var url = 'https://libs.ext-code.com/external/js/node-forge/node-forge.m.js';
10+
({forge} = await import(url));
811

912
var {key,cert} = setup();
1013

@@ -26,7 +29,6 @@
2629
}();
2730

2831

29-
3032
function extract_spki(cert){
3133
// requires node-forge
3234
var cert = forge.pki.certificateFromPem(cert);
@@ -37,7 +39,27 @@
3739

3840
}//extract_spki
3941

40-
42+
async function pub_key(cert) {
43+
// Extract raw SPKI bytes without Node-specific modules
44+
const spki = extract_spki_der(cert);
45+
const buf = spki.buffer;
46+
47+
// Use the environment's global Web Crypto interface.
48+
// Note: We use globalThis.crypto to ensure we aren't accidentally
49+
// accessing a variable bound by a 'require' statement.
50+
const webCrypto = globalThis.crypto?.subtle || globalThis.crypto;
51+
52+
const importedKey = await webCrypto.importKey(
53+
'spki',
54+
buf,
55+
{ name: 'RSA-OAEP', hash: 'SHA-256' },
56+
true,
57+
['encrypt']
58+
);
59+
60+
return importedKey;
61+
}
62+
/*
4163
async function pub_key(cert){
4264
4365
var spki = extract_spki(cert);
@@ -46,8 +68,8 @@
4668
return pub_key;
4769
4870
}//pub_key
49-
50-
71+
*/
72+
5173
async function encrypt(blob,cert){
5274

5375
var publicKey = await pub_key(cert);

0 commit comments

Comments
 (0)