browserify-hybrid-crypto
Version:
TypeScript implementation Hybrid encryption and signing library built on Web Crypto (AES + RSA + HMAC).
86 lines (72 loc) • 2.2 kB
text/typescript
import { importPublicKey } from "./import-key";
import { HybridEncryption, HybridCryptoOptions } from "./interfaces";
import { getCryptoImpl } from "./utils";
import { getAesParams } from "./aes-params";
export async function hybridEncrypt(
publicKeyPEM: string,
data: string,
options: HybridCryptoOptions = {},
): Promise<HybridEncryption> {
const crypto = getCryptoImpl();
const {
aesAlgorithm = "AES-GCM",
aesKeyLength = 256,
hmacHash = "SHA-256",
} = options;
// Generate AES key for session encryption
const sessionCryptoKey = await crypto.subtle.generateKey(
{ name: aesAlgorithm, length: aesKeyLength },
true,
["encrypt", "decrypt"],
);
// Generate HMAC key for signing
const signingCryptoKey = await crypto.subtle.generateKey(
{
name: "HMAC",
hash: hmacHash,
},
true,
["sign", "verify"],
);
// Get AES params and IV/counter
const { aesParams, ivUsed: iv } = getAesParams(aesAlgorithm, options);
// Encrypt data with session key using AES
const encoder = new TextEncoder();
const encryptedData = await crypto.subtle.encrypt(
aesParams,
sessionCryptoKey,
encoder.encode(data),
);
// Sign the encrypted data with the signing key
const signature = await crypto.subtle.sign(
{ name: "HMAC" },
signingCryptoKey,
encryptedData,
);
// Import public key
const publicKey = await importPublicKey(publicKeyPEM);
// Export the session key to raw format
const sessionKey = await crypto.subtle.exportKey("raw", sessionCryptoKey);
// Encrypt the session key with the public key using RSA-OAEP
const encryptedSessionKey = await crypto.subtle.encrypt(
{ name: "RSA-OAEP" },
publicKey,
sessionKey,
);
// Export the signing key to raw format
const signingKey = await crypto.subtle.exportKey("raw", signingCryptoKey);
// Encrypt the signing key with the public key using RSA-OAEP
const encryptedSigningKey = await crypto.subtle.encrypt(
{ name: "RSA-OAEP" },
publicKey,
signingKey,
);
// Return encrypted data and key
return {
encryptedSessionKey,
encryptedSigningKey,
encryptedData,
signature,
iv,
};
}