Low-level cryptographic functions for key generation, signing, hashing, and verification supporting various algorithms including keccak256, ECDSA, BIP-39 mnemonics, and key derivation functions.
Cryptographic hash functions for data integrity and blockchain operations.
/**
* Compute Keccak-256 hash (Ethereum's primary hashing algorithm)
* @param data - Data to hash
* @returns 32-byte hash as hex string
*/
function keccak256(data: BytesLike): string;
/**
* Compute SHA-256 hash
* @param data - Data to hash
* @returns 32-byte hash as hex string
*/
function sha256(data: BytesLike): string;
/**
* Compute SHA-512 hash
* @param data - Data to hash
* @returns 64-byte hash as hex string
*/
function sha512(data: BytesLike): string;
/**
* Compute RIPEMD-160 hash
* @param data - Data to hash
* @returns 20-byte hash as hex string
*/
function ripemd160(data: BytesLike): string;Usage Examples:
import { keccak256, sha256, toUtf8Bytes } from "ethers";
// Hash a string
const messageHash = keccak256(toUtf8Bytes("Hello, Ethereum!"));
// Hash binary data
const dataHash = sha256("0x1234567890abcdef");
console.log("Keccak256:", messageHash);
console.log("SHA256:", dataHash);Hash-based Message Authentication Code for secure message verification.
/**
* Compute HMAC using specified algorithm
* @param algorithm - Hash algorithm ("sha256", "sha512")
* @param key - Secret key for HMAC
* @param data - Data to authenticate
* @returns HMAC as hex string
*/
function computeHmac(algorithm: "sha256" | "sha512", key: BytesLike, data: BytesLike): string;Usage Example:
import { computeHmac, toUtf8Bytes } from "ethers";
const key = toUtf8Bytes("secret-key");
const message = toUtf8Bytes("important message");
const hmac = computeHmac("sha256", key, message);
console.log("HMAC-SHA256:", hmac);Cryptographically secure random byte generation.
/**
* Generate cryptographically secure random bytes
* @param length - Number of bytes to generate
* @returns Random bytes as Uint8Array
*/
function randomBytes(length: number): Uint8Array;Usage Example:
import { randomBytes, hexlify } from "ethers";
// Generate 32 random bytes
const entropy = randomBytes(32);
console.log("Random bytes:", hexlify(entropy));
// Generate random private key
const privateKey = hexlify(randomBytes(32));Password-based key derivation for secure key generation from passwords.
/**
* PBKDF2 key derivation function
* @param password - Password to derive from
* @param salt - Salt for key derivation
* @param iterations - Number of iterations
* @param keylen - Desired key length in bytes
* @param hashAlgorithm - Hash algorithm to use
* @returns Derived key as hex string
*/
function pbkdf2(
password: BytesLike,
salt: BytesLike,
iterations: number,
keylen: number,
hashAlgorithm: "sha256" | "sha512"
): string;
/**
* Scrypt key derivation function (asynchronous)
* @param password - Password to derive from
* @param salt - Salt for key derivation
* @param N - CPU/memory cost parameter
* @param r - Block size parameter
* @param p - Parallelization parameter
* @param dkLen - Desired key length in bytes
* @param progress - Optional progress callback
* @returns Promise resolving to derived key as hex string
*/
function scrypt(
password: BytesLike,
salt: BytesLike,
N: number,
r: number,
p: number,
dkLen: number,
progress?: ProgressCallback
): Promise<string>;
/**
* Scrypt key derivation function (synchronous)
* @param password - Password to derive from
* @param salt - Salt for key derivation
* @param N - CPU/memory cost parameter
* @param r - Block size parameter
* @param p - Parallelization parameter
* @param dkLen - Desired key length in bytes
* @returns Derived key as hex string
*/
function scryptSync(
password: BytesLike,
salt: BytesLike,
N: number,
r: number,
p: number,
dkLen: number
): string;
type ProgressCallback = (percent: number) => void;Usage Examples:
import { pbkdf2, scrypt, toUtf8Bytes } from "ethers";
const password = toUtf8Bytes("user-password");
const salt = toUtf8Bytes("unique-salt");
// PBKDF2 derivation
const pbkdf2Key = pbkdf2(password, salt, 100000, 32, "sha256");
// Scrypt derivation (async)
const scryptKey = await scrypt(password, salt, 16384, 8, 1, 32, (percent) => {
console.log(`Derivation progress: ${percent}%`);
});
// Scrypt derivation (sync)
const scryptKeySync = scryptSync(password, salt, 16384, 8, 1, 32);ECDSA signature creation and verification using secp256k1 curve.
/**
* ECDSA signature representation
*/
class Signature {
readonly r: string;
readonly s: string;
readonly v: number;
readonly networkV?: bigint;
readonly yParity: 0 | 1;
constructor(guard: any, r: string, s: string, v: number);
// Signature properties
get yParityAndS(): string;
get compactSerialized(): string;
get serialized(): string;
// Static creation methods
static from(sig: SignatureLike): Signature;
// Cloning
clone(): Signature;
toJSON(): any;
// Legacy support
legacyChainId?: number;
}
type SignatureLike = Signature | string | {
r: string;
s: string;
v: number;
yParity?: 0 | 1;
yParityAndS?: string;
} | {
r: string;
yParityAndS: string;
} | {
compactSerialized: string;
} | {
serialized: string;
};ECDSA private key management for transaction and message signing.
/**
* ECDSA signing key for cryptographic operations
*/
class SigningKey {
constructor(privateKey: BytesLike);
readonly privateKey: string;
readonly publicKey: string;
readonly compressedPublicKey: string;
readonly address: string;
// Signing operations
sign(digest: BytesLike): Signature;
// Key computation
computeSharedSecret(otherKey: BytesLike): string;
// Static utilities
static computePublicKey(key: BytesLike, compressed?: boolean): string;
static recoverPublicKey(digest: BytesLike, signature: SignatureLike): string;
static addPoints(p0: BytesLike, p1: BytesLike, compressed?: boolean): string;
}Usage Examples:
import { SigningKey, keccak256, toUtf8Bytes } from "ethers";
// Create signing key from private key
const signingKey = new SigningKey("0x1234567890abcdef...");
console.log("Address:", signingKey.address);
console.log("Public Key:", signingKey.publicKey);
// Sign a message hash
const messageHash = keccak256(toUtf8Bytes("Hello, Ethereum!"));
const signature = signingKey.sign(messageHash);
console.log("Signature:", signature.serialized);
// Recover public key from signature
const recoveredPubKey = SigningKey.recoverPublicKey(messageHash, signature);
console.log("Recovered:", recoveredPubKey === signingKey.publicKey);Security mechanism to prevent modification of cryptographic functions after initialization.
/**
* Lock all cryptographic functions to prevent modification
* Once called, cryptographic primitives cannot be changed via .register hooks
*/
function lock(): void;Usage Example:
import { lock } from "ethers";
// Lock cryptographic functions for security
lock();
// After this point, cryptographic functions cannot be modifiedUtilities for working with Ethereum addresses and cryptographic keys.
/**
* Compute Ethereum address from public key
* @param key - Public key (compressed or uncompressed)
* @returns Ethereum address as checksummed hex string
*/
function computeAddress(key: BytesLike): string;
/**
* Recover Ethereum address from message digest and signature
* @param digest - Message digest (32 bytes)
* @param signature - ECDSA signature
* @returns Ethereum address of the signer
*/
function recoverAddress(digest: BytesLike, signature: SignatureLike): string;Usage Examples:
import { computeAddress, recoverAddress, SigningKey, keccak256, toUtf8Bytes } from "ethers";
// Compute address from public key
const signingKey = new SigningKey("0x1234567890abcdef...");
const address = computeAddress(signingKey.publicKey);
// Recover address from signature
const message = "Hello, Ethereum!";
const messageHash = keccak256(toUtf8Bytes(message));
const signature = signingKey.sign(messageHash);
const recoveredAddress = recoverAddress(messageHash, signature);
console.log("Computed address:", address);
console.log("Recovered address:", recoveredAddress);
console.log("Match:", address === recoveredAddress);High-level utilities for signing and verifying messages with Ethereum's standard message format.
/**
* Hash a message using Ethereum's standard message format
* @param message - Message to hash (string or bytes)
* @returns Message hash ready for signing
*/
function hashMessage(message: string | Uint8Array): string;
/**
* Verify a message signature and recover the signer address
* @param message - Original message
* @param signature - Message signature
* @returns Address of the message signer
*/
function verifyMessage(message: string | Uint8Array, signature: SignatureLike): string;Usage Examples:
import { hashMessage, verifyMessage, Wallet } from "ethers";
const wallet = Wallet.createRandom();
const message = "Please sign this message";
// Sign message (wallet handles hashMessage internally)
const signature = await wallet.signMessage(message);
// Verify signature
const signerAddress = verifyMessage(message, signature);
console.log("Wallet address:", wallet.address);
console.log("Signer address:", signerAddress);
console.log("Valid signature:", wallet.address === signerAddress);
// Manual message hashing
const messageHash = hashMessage(message);
console.log("Message hash:", messageHash);Functions for EIP-3074 authorization support, enabling account abstraction through authorized contract interactions.
/**
* Compute EIP-3074 authorization digest for signing
* @param auth - Authorization request parameters
* @returns Authorization hash to be signed
*/
function hashAuthorization(auth: AuthorizationRequest): string;
/**
* Recover signer address from authorization signature
* @param auth - Authorization request parameters
* @param sig - Signature over the authorization
* @returns Address of the signer
*/
function verifyAuthorization(auth: AuthorizationRequest, sig: SignatureLike): string;
interface AuthorizationRequest {
address: string | Addressable;
nonce?: Numeric;
chainId?: BigNumberish;
}Usage Examples:
import { hashAuthorization, verifyAuthorization, Wallet } from "ethers";
// Create authorization request
const authRequest = {
address: "0x742d35cc6ad4e3b8b0e5e0c2d8b9b7cbf2b5e2e1",
nonce: 42,
chainId: 1
};
// Sign authorization (typically done by wallet)
const wallet = Wallet.createRandom();
const authHash = hashAuthorization(authRequest);
const signature = await wallet.signMessage(authHash);
// Verify authorization signature
const signerAddress = verifyAuthorization(authRequest, signature);
console.log("Authorized by:", signerAddress);
console.log("Valid authorization:", signerAddress === wallet.address);
// Use in smart contract context
const authorizedContractCall = {
auth: authRequest,
signature: signature,
// ... other transaction data
};/**
* Progress callback for long-running operations like key derivation
*/
type ProgressCallback = (percent: number) => void;
/**
* Signature-like values that can be converted to Signature instances
*/
type SignatureLike = Signature | string | {
r: string;
s: string;
v: number;
yParity?: 0 | 1;
yParityAndS?: string;
} | {
r: string;
yParityAndS: string;
} | {
compactSerialized: string;
} | {
serialized: string;
};