1.0.0 • Published 10 months ago

@gotocva/crypto v1.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
10 months ago

@gotocva/crypto

@gotocva/crypto is a lightweight Node.js module that provides an easy-to-use API for encrypting and decrypting strings using AES-256-GCM encryption. This is particularly useful for securing sensitive data, such as API keys, passwords, or other private information.

Installation

Install the package using npm or yarn:

npm install @gotocva/crypto

or

yarn add @gotocva/crypto

Usage

Below is a quick guide to using the @gotocva/crypto module:

Encrypt and Decrypt Strings

const Crypto = require('@gotocva/crypto');

// Initialize Crypto with a secret key (you should store the secret key in environment variables)
const crypto = new Crypto(process.env.SECRET_KEY || 'mySecretKey');

// Encrypt a string
const encryptedString = crypto.encrypt('siva');
console.log('Encrypted String:', encryptedString);

// Decrypt the encrypted string
const decryptedString = crypto.decrypt(encryptedString);
console.log('Decrypted String:', decryptedString);

Output Example

Encrypted String: f5cd39890592299745ffa1e09ec76d480463ce69f3e75b17bc4d4f7bc384de878f79fd8a51ac9fd5cab2218ca085d26839fe4336d1bf37a7b58826d9de5eb062a9421d96ccd53dddb5b77fd0d74594e290f7858212638fecfc33922d299d63e0a5ceca08
Decrypted String: siva

API

new Crypto(secretKey, [options])

Creates an instance of the Crypto class.

  • secretKey (required): A non-empty string used as the encryption key. This should be kept secure and private.
  • options (optional): An object to configure the encryption behavior. Options include:
    • encoding: The encoding format for the output (default: hex).
    • saltLength: The length of the random salt (default: 64).
    • pbkdf2Iterations: The number of iterations for key derivation (default: 100000).

encrypt(value)

Encrypts the given value.

  • value (required): The string to encrypt.
  • Returns: An encrypted string.

decrypt(value)

Decrypts the given encrypted value.

  • value (required): The string to decrypt (must be a valid output from the encrypt method).
  • Returns: The original plaintext string.

Best Practices

  1. Use Environment Variables: Always store your secret key in environment variables to prevent accidental exposure in your codebase.

    export SECRET_KEY="your-secure-key"
  2. Keep the Secret Key Safe: Your encryption is only as strong as the secrecy of your key. Ensure it is never hardcoded in your application.

  3. Secure Dependencies: Regularly update the @gotocva/crypto package to get the latest security updates and features.

Testing

You can test the encryption and decryption process with the following script:

const Crypto = require('@gotocva/crypto');
const crypto = new Crypto('testKey');

const encrypted = crypto.encrypt('testValue');
const decrypted = crypto.decrypt(encrypted);

console.assert(decrypted === 'testValue', 'Decryption failed!');
console.log('All tests passed!');