UNPKG

@synotech/crypto

Version:

Comprehensive cryptography library with Web3 integration, supporting symmetric/asymmetric encryption, digital signatures, JWT tokens, blockchain address generation, and secure key management

567 lines (564 loc) 20.2 kB
import * as jwt from 'jsonwebtoken'; type Generic<T = any> = T | string; interface CryptographyOptions { encryptKey?: string; encryptKeySingle?: string; } interface ApiKeyOptions { prefix?: string; length?: number; } interface OTPEnrolOptions { identifier: string; issuer?: string; label?: string; algorithm?: 'SHA1' | 'SHA256' | 'SHA512'; digits?: number; period?: number; } interface OTPIssueOptions { secret: string; timestamp?: number; } interface OTPVerifyOptions { secret: string; token: string; window?: number; timestamp?: number; } interface RandomOptions { length?: number; useLowerCase?: boolean; useUpperCase?: boolean; useNumbers?: boolean; useSpecial?: boolean; useHex?: boolean; } type KeyStrength = 'decent_pw' | 'strong_pw' | 'ft_knox_pw' | 'ci_key' | '160_wpa' | '504_wpa' | '64_wep' | '128_wep' | '152_wep' | '256_wep'; /** * The Cryptography class provides methods for encryption, decryption, signing, and verification of data using various cryptographic algorithms. * * @class Cryptography * * @example * const cryptography = new Cryptography({ * encryptKey: '', * encryptKeySingle: '', * }) * * const encryptedData = cryptography.encrypt('Hello, World!') * const decryptedData = cryptography.decrypt(encryptedData) * * const signature = cryptography.signature() * const isVerified = cryptography.signatureVerify(signature) * * // creates a Web3 Token Address per our standards * const address = cryptography.address() * * const encodedData = cryptography.base64Encode('Hello, World!') * const decodedData = cryptography.base64Decode(encodedData) * const isEncodedOrNot = cryptography.isBase64Encoded(encodedData) * * const slug = cryptography.slug() * const customSlug = cryptography.slug({ separator: '_', length: 5 }) * * const apiKey = cryptography.apiKey({ prefix: 'SYN', length: 32 }) * const isValidApiKey = cryptography.apiKeyVerify(apiKey) * * // OTP (One-Time Password) functionality * const otpEnrollment = cryptography.otpEnrol({ identifier: 'user@example.com', issuer: 'MyApp' }) * const otpCode = cryptography.otpIssue({ secret: otpEnrollment.secret }) * const isValidOTP = cryptography.otpVerify({ secret: otpEnrollment.secret, token: otpCode }) * * cryptography.get('strong_pw') // returns i=SQ_qa3W[<RxoM * cryptography.random({ length: 20, useLowerCase: true, useUpperCase: true, useNumbers: true, useSpecial: true, useHex: false }) // returns *ajz:74,*ak0 * */ declare class Cryptography { ALG: Generic; KEYS: { encryptKey: string; encryptKeySingle: string; }; keys: string[]; private entropyPool; private lowerCase; private upperCase; private numbers; private special; private hex; /** * Initializes a new instance of the Cryptography class. */ constructor(options?: CryptographyOptions); private randomizer; /** * @method random * The Random module class provides methods for generating random strings. * * @example * cryptography.random({ length: 20, useLowerCase: true, useUpperCase: true, useNumbers: true, useSpecial: true, useHex: false }) // returns *ajz:74,*ak0 * * // Decent Passwords - Good for nothing really, public accounts and other non-critical things. * cryptography.get('decent_pw') // returns rXjdx36oro * * // Strong Passwords - Robust enough to keep your web hosting account secure. * cryptography.get('strong_pw') // returns i=SQ_qa3W[<RxoM * * // Fort Knox Passwords - Secure enough for almost anything, like root or administrator passwords. * cryptography.get('ft_knox_pw') // returns P}U%H\OOYAYb;wc"3hgI,3Lz[gd-z] * * // Encryption Keys - Can be used for any other 256-bit key requirement. * cryptography.get('ci_key') // returns CeXHpM3nDgzdv0o3AkMCs3OuxzepLGW8 * * // 160-bit WPA Key * cryptography.get('160_wpa') // returns oHI#gR8z#h7BS>cZ!zH( * * // 504-bit WPA Key * cryptography.get('504_wpa') // returns <os[g`s}u06jqt"Ea]t11,HsI[UipHD)%F";:9RhJ@kTU8GknLpMAXtoCzsJjT` * * // 64-bit WEP Keys * cryptography.get('64_wep') // returns 8911B * * // 128-bit WEP Keys * cryptography.get('128_wep') // returns 9F4E4F933BCCC * * // 152-bit WEP Keys * cryptography.get('152_wep') // returns 695E1EE96E483961 * * // 256-bit WEP Keys * cryptography.get('256_wep') // returns AC7E866246BA6B71BF5D88A6861AB * */ random(options: RandomOptions): string; /** * * @method get * @param strength - The strength of the key to generate. decent_pw|strong_pw|ft_knox_pw|ci_key|160_wpa|504_wpa|64_wep|128_wep|152_wep|256_wep */ get(strength: KeyStrength): string; /** * @method salt * Generates a random salt value. * @returns The generated salt value as a hexadecimal string. * * @example * const salt = cryptography.salt() * console.log(salt) * // Output: * // 5eb63bbbe01eeed093cb22bb8f5acdc3 */ salt(): string; /** * @method iv * Generates a random initialization vector (IV). * @returns The generated IV as a Buffer. */ iv(): Buffer<ArrayBufferLike>; /** * @method signature * Generates a signature using the encryption keys. * @returns The generated signature as a string. * * @example * const signature = cryptography.signature() * console.log(signature) * // Output: * // 6a3a4b5c6d7e8f9a */ signature(): string; /** * @method signatureVerify * Verifies a signature against the encryption keys. * @param signature - The signature to verify. * @returns True if the signature is valid, false otherwise. * @throws An error if the signature contains unknown identifiers. * * @example * const signature = '6a3a4b5c6d7e8f9a' * const isValid = cryptography.signatureVerify(signature) * console.log(isValid) * // Output: * // true */ signatureVerify(signature: string): boolean; /** * @method address * Generates a random crypto address. * @returns The generated address as a string. * @throws An error if an error occurs during address generation. * * @example * const address = cryptography.address() * console.log(address) * // Output: * // KGRHCVlAmmEnnlKh6wVX9TiJ6YGI7FCl */ address(prefix?: string): string; /** * @method getKeys * Generates random keys from the provided key array. * @param count - The number of keys to generate. Defaults to 12. * @returns An array of randomly generated keys. */ getKeys: (count?: number) => any[]; /** * @method encryptSingle * Encrypts data one way using an encryption key. * @param data - The data to encrypt. * @returns The encrypted data as a base64-encoded string. * * @example * const crypto = new Cryptography(['key1', 'key2', 'key3'], 'encryptKey', 'encryptKeySingle') * const data = 'Hello, World!' * const encryptedData = cryptography.encryptSingle(data) * console.log(encryptedData) * // Output: * // 5eb63bbbe01eeed093cb22bb8f5acdc3 */ encryptSingle(data: Generic): string; /** * @method encrypt * Encrypts text two way using the encryption keys. * @param text - The text to encrypt. * @returns The encrypted text as a string. * @throws An error if an error occurs during encryption. * * @example * const text = 'Hello, World!' * const encryptedText = cryptography.encrypt(text) * console.log(encryptedText) * // Output: * // 6a3a4b5c6d7e8f9a:6a3a4b5c6d7e8f9a:6a3a4b5c6d7e8f9a */ encrypt(text: Generic): string; /** * @method decrypt * Decrypts encrypted text using the encryption keys. * @param encryptedText - The encrypted text to decrypt. * @returns The decrypted text as a string. * @throws An error if an error occurs during decryption. * * @example * const encryptedText = '6a3a4b5c6d7e8f9a:6a3a4b5c6d7e8f9a:6a3a4b5c6d7e8f9a' * const decryptedText = cryptography.decrypt(encryptedText) * console.log(decryptedText) * // Output: * // Hello, World! */ decrypt(encryptedText: Generic): string; /** * @method password * Generates a password hash using the provided password and salt. * @param password - The password to hash. * @param salt - The salt value to use for hashing. * @returns The hashed password as a hexadecimal string. * @throws An error if an error occurs during password hashing. * * @example * const password = 'myPassword' * const salt = cryptography.salt() * const hashedPassword = cryptography.password(password, salt) * console.log(hashedPassword) * // Output: * // 5ebe2294ecd0e0f08eab7690d2a6ee69 */ password(password: string, salt: string): string; /** * @method jwtIssue * Issues a JSON Web Token (JWT) with the provided payload and expiry. * @param payload - The payload to include in the JWT. * @param expiry - The expiry time for the JWT. * @returns The issued JWT as a string. * @throws An error if an error occurs during JWT issuance. * * @example * const payload = { * sub: '1234567890', * name: 'John Doe', * iat: 1516239022 * } * * const expiry = '1h' * const token = cryptography.jwtIssue(payload, expiry) * console.log(token) * // Output: * // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c */ jwtIssue(payload: Generic | undefined, expiry: string): never; /** * @method jwtVerify * Verifies a JSON Web Token (JWT) and returns the decoded payload. * @param token - The JWT to verify. * @returns The decoded payload if the JWT is valid. * @throws An error if the JWT is invalid or an error occurs during verification. * * @example * const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c' * const payload = cryptography.jwtVerify(token) * console.log(payload) * // Output: * // { * // sub: '1234567890', * // name: 'John Doe', * // iat: 1516239022 * // } */ jwtVerify(token: string): string | jwt.JwtPayload; /** * @method publicKey * Generates a private key for asymmetric encryption. * @returns The generated private key as a PEM-encoded string. * @throws An error if an error occurs during private key generation. * * @example * const privateKey = cryptography.privateKey() * console.log(privateKey) * // Output: * // -----BEGIN PRIVATE KEY----- * // MIHuAgEAMBAGByqGSM49AgEGBSuBBAAjBIHWMIHTAgEBBEIBA4GCAWqjggFMMIIB * // ... * // -----END PRIVATE KEY----- */ privateKey(): string | Buffer<ArrayBufferLike>; /** * @method publicKey * * Generates a public key from the provided private key. * @param privateKey - The private key to generate the public key from. * @returns The generated public key as a PEM-encoded string. * * @example * const privateKey = `-----BEGIN PRIVATE KEY----- * MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDZ1Ck6vJQK0J5T * ... * -----END PRIVATE KEY-----` * * const publicKey = cryptography.publicKey(privateKey) * console.log(publicKey) * // Output: * // -----BEGIN PUBLIC KEY----- * // MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2dQpOryUCtCeUz8vZ6zB * // ... * // -----END PUBLIC KEY----- */ publicKey(privateKey: string): string | Buffer<ArrayBufferLike>; /** * @method publicKeyVerify * Verifies the authenticity of a public key using the provided private and public keys. * @param privateKey - The private key used to sign the data. * @param publicKey - The public key used to verify the signature. * @returns True if the public key is authentic, false otherwise. * @throws An error if the public key fails to authenticate. * * @example * const privateKey = `-----BEGIN PRIVATE KEY----- * MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDZ1Ck6vJQK0J5T * ... * -----END PRIVATE KEY-----` * const publicKey = `-----BEGIN PUBLIC KEY----- * MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2dQpOryUCtCeUz8vZ6zB * ... * -----END PUBLIC KEY-----` * const isAuthentic = cryptography.publicKeyVerify({ privateKey, publicKey }) * console.log(isAuthentic) * // Output: * // true */ publicKeyVerify({ privateKey, publicKey }: { privateKey: string; publicKey: string; }): boolean; /** * @method isBase64Encoded * Checks if a string is base64 encoded. * @param string - The string to check. * @returns True if the string is base64 encoded, false otherwise. * * @example * const encodedString = 'SGVsbG8sIFdvcmxkIQ==' * const isEncoded = cryptography.isBase64Encoded(encodedString) * console.log(isEncoded) * // Output: * // true */ isBase64Encoded(string: string): boolean; /** * @method base64Encode * Encodes data as base64. * @param data - The data to encode. * @returns The base64-encoded string. * * @example * const data = 'Hello, World!' * const encodedData = cryptography.base64Encode(data) * console.log(encodedData) * // Output: * // SGVsbG8sIFdvcmxkIQ== */ base64Encode(data: string): string; /** * @method base64Decode * Decodes a base64-encoded string. * @param encodedString - The base64-encoded string to decode. * @returns The decoded string. * * @example * const encodedString = 'SGVsbG8sIFdvcmxkIQ==' * const decodedString = cryptography.base64Decode(encodedString) * console.log(decodedString) * // Output: * // Hello, World! */ base64Decode(encodedString: string): string; /** * @method apiKey * Generates a secure API key with HMAC-based authentication. * @param options - Configuration options for API key generation. * @param options.prefix - The 3-letter prefix for the API key. Defaults to 'SYN'. * @param options.length - The length of the key portion (excluding prefix and separator). Defaults to 48. * @returns The generated API key in format: prefix_keyHash * * @example * const apiKey = cryptography.apiKey() * console.log(apiKey) * // Output: * // SYN_a1b2c3d4e5f6... * * const customApiKey = cryptography.apiKey({ prefix: 'DEV', length: 32 }) * console.log(customApiKey) * // Output: * // SYN_x1y2z3a4b5c6... */ apiKey(options?: ApiKeyOptions): string; /** * @method apiKeyVerify * Verifies the authenticity of an API key using HMAC validation. * @param apiKey - The API key to verify. * @param options - Optional configuration for verification. * @param options.prefix - Expected prefix to validate against. If not provided, extracts from the key. * @returns True if the API key is valid, false otherwise. * * @example * const apiKey = cryptography.apiKey({ prefix: 'SYN' }) * const isValid = cryptography.apiKeyVerify(apiKey) * console.log(isValid) * // Output: * // true * * const isValidWithPrefix = cryptography.apiKeyVerify(apiKey, { prefix: 'SYN' }) * console.log(isValidWithPrefix) * // Output: * // true */ apiKeyVerify(apiKey: string, options?: { prefix?: string; }): boolean; /** * @method otpEnrol * Enrolls a user for OTP by generating a secret and returning OTP configuration. * @param options - Configuration options for OTP enrollment. * @param options.identifier - Unique identifier for the user (email, username, etc.). * @param options.issuer - The issuer name (app/service name). Defaults to 'Synotech Ai'. * @param options.label - Label for the OTP entry. Defaults to identifier. * @param options.algorithm - HMAC algorithm to use. Defaults to 'SHA1'. * @param options.digits - Number of digits in OTP code. Defaults to 5. * @param options.period - Time period for TOTP in seconds. Defaults to 120. * @returns Object containing secret, QR code URI, and manual entry key. * * @example * const enrollment = cryptography.otpEnrol({ * identifier: 'user@example.com', * issuer: 'MyApp', * algorithm: 'SHA256', * digits: 5, * period: 120 * }) * console.log(enrollment) * // Output: * // { * // secret: 'JBSWY3DPEHPK3PXP', * // uri: 'otpauth://totp/MyApp:user@example.com?secret=JBSWY3DPEHPK3PXP&issuer=MyApp', * // qr: 'otpauth://totp/MyApp:user@example.com?secret=JBSWY3DPEHPK3PXP&issuer=MyApp' * // } */ otpEnrol(options: OTPEnrolOptions): { secret: string; uri: string; qr: string; }; /** * @method otpIssue * Generates a time-based OTP code using the provided secret. * @param options - Configuration options for OTP generation. * @param options.secret - The base32 encoded secret key. * @param options.timestamp - Optional timestamp for code generation. Defaults to current time. * @returns The generated OTP code as a string. * * @example * const code = cryptography.otpIssue({ * secret: 'JBSWY3DPEHPK3PXP' * }) * console.log(code) * // Output: '12345' * * const historicalCode = cryptography.otpIssue({ * secret: 'JBSWY3DPEHPK3PXP', * timestamp: 1640995200000 * }) * console.log(historicalCode) * // Output: '78901' */ otpIssue(options: OTPIssueOptions): string; /** * @method otpVerify * Verifies a time-based OTP code against the provided secret. * @param options - Configuration options for OTP verification. * @param options.secret - The base32 encoded secret key. * @param options.token - The OTP code to verify. * @param options.window - Time window for verification (number of periods). Defaults to 1. * @param options.timestamp - Optional timestamp for verification. Defaults to current time. * @returns Boolean indicating whether the token is valid. * * @example * const isValid = cryptography.otpVerify({ * secret: 'JBSWY3DPEHPK3PXP', * token: '12345' * }) * console.log(isValid) * // Output: true or false * * const isValidWithWindow = cryptography.otpVerify({ * secret: 'JBSWY3DPEHPK3PXP', * token: '12345', * window: 2 * }) * console.log(isValidWithWindow) * // Output: true or false */ otpVerify(options: OTPVerifyOptions): boolean; /** * @method slug * Generates a unique slug using adjectives, colors, animals, names, languages, starWars, and countries. * @param options - Configuration options for slug generation. * @param options.separator - The separator to use between words. Defaults to '-'. * @param options.length - The number of words in the slug. Defaults to 3. * @returns A unique slug string. * * @example * const slug = cryptography.slug() * console.log(slug) * // Output: * // happy-blue-elephant * * const customSlug = cryptography.slug({ separator: '_', length: 5 }) * console.log(customSlug) * // Output: * // brave_red_tiger_john_french */ slug(options?: { separator?: string; length?: number; }): string; } export { Cryptography, Cryptography as default };