rsa-oaep-encryption
v1.0.0
Published
Pure JavaScript implementation of encryption using the RSA-OAEP algorithm without relying on the Web Crypto API.
Downloads
34
Maintainers
Readme
RSA OAEP Encryption
The purpose of this project is to provide a pure JavaScript implementation of RSA
encryption in an environment that does not support the Web Crypto API.
Thanks to node-forge, this project was forked from it and the following modifications and changes were made:
- Rewrite using
TypeScript
. - Delete all
nodejs-only
codes. - Only the
encryption
function using theRSA-OAEP
algorithm is retained, and all other codes are deleted. It means thatPKCS1-v1_5
is not supported. - The hash algorithm only supports
SHA1
SHA-256
SHA-384
SHA-512
to be consistent with theWeb Crypto API
. - The return value of the
encrypt
method is changed toArrayBuffer
to be consistent with theWeb Crypto API
. - The code is almost
100%
covered andtree-shake
friendly.
Installation
# via pnpm
pnpm add rsa-oaep-encryption
# or via yarn
yarn add rsa-oaep-encryption
# or just from npm
npm install --save rsa-oaep-encryption
# via JSR
jsr add @happy-js/rsa-oaep-encryption
# for deno
deno add @happy-js/rsa-oaep-encryption
# for bun
bunx jsr add @happy-js/rsa-oaep-encryption
Examples
import { importPublicKey, sha256 } from 'rsa-oaep-encryption';
const PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
xxxxx
-----END PUBLIC KEY-----`;
const encryptedData = importPublicKey(PUBLIC_KEY).encrypt('some data', sha256.create()); // or sha1 sha384 sha512
In an environment that supports the Web Crypto API
, this is equivalent to the following code:
const keyData = base64ToBuffer(PUBLIC_KEY.replace(/(-----(BEGIN|END) PUBLIC KEY-----|\s)/g, '')); // base64ToBuffer needs to be implemented
const publicKey = await crypto.subtle.importKey(
'spki',
keyData,
{
name: 'RSA-OAEP',
hash: 'SHA-256',
},
false,
[
'encrypt',
]
);
const encryptedData = await crypto.subtle.encrypt(
{
name: 'RSA-OAEP',
},
publicKey,
new TextEncoder().encode('some data')
);
Of course, you can also use the exported SHA
methods to perform SHA calculations separately in an environment that does not support the Web Crypto API
.
Like this:
import { sha1 } from 'rsa-oaep-encryption';
const sha1Str = sha1.create().update('some data').digest().toHex();