Overview
The CryptoApi
class provides a set of cryptographic functions that can be used to generate keys, sign data, encrypt/decrypt data, and more. This documentation will guide you through some common use cases, such as generating a private and public key pair, implementing a login flow using signatures, and other cryptographic operations.
Getting Started
To use the CryptoApi
class, you first need to import and instantiate it:
import { Endpoint } from '@simplito/privmx-webendpoint';
const cryptoApi = await Endpoint.createCryptoApi();
Generating Private and Public Key Pair
You can generate a private and public key pair using a login and password. The private key is derived from the password and a salt, while the public key is derived from the private key.
const login = "EXAMPLE_LOGIN";
const password = "EXAMPLE_PASSWORD";
const salt = "EXAMPLE_SALT";
// Derive the private key from the password and salt
const privateKey = await cryptoApi.derivePrivateKey2(password, salt);
// Derive the public key from the private key
const publicKey = await cryptoApi.derivePublicKey(privateKey);
console.log("Private Key:", privateKey);
console.log("Public Key:", publicKey);
Login Flow Using Signature Verification
In a typical login flow, the client signs a challenge (e.g., a random string) using their private key, and the server verifies the signature using the corresponding public key.
// Assume the server sends a challenge to the client
const challenge = Buffer.from("RANDOM_CHALLENGE_STRING");
// Sign the challenge using the private key
const signature = await cryptoApi.signData(challenge, privateKey);
// Send the signature and public key to the server for verification
const loginData = {
publicKey: publicKey,
signature: signature
};
// Send loginData to the server
Encrypting and Decrypting Data
You can use the CryptoApi
to encrypt and decrypt data using symmetric keys.
const data = new TextEncoder().encode("Sensitive data to encrypt");
// Generate a symmetric key
const symmetricKey = await cryptoApi.generateKeySymmetric();
// Encrypt the data
const encryptedData = await cryptoApi.encryptDataSymmetric(data, symmetricKey);
console.log("Encrypted Data:", encryptedData);
Additional Use Cases
Converting PEM Key to WIF Format
If you have a private key in PEM format, you can convert it to WIF format using the convertPEMKeytoWIFKey
method:
const pemKey = "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----";
const wifKey = await cryptoApi.convertPEMKeytoWIFKey(pemKey);
console.log("WIF Key:", wifKey);
Generating a Random Private Key
You can generate a random private key without using a password or salt.
const privateKey = await cryptoApi.generatePrivateKey();
console.log("Random Private Key:", privateKey);