Created
September 20, 2024 03:14
-
-
Save hansheng0512/958aa54ce9eb31aa9ec3180783764752 to your computer and use it in GitHub Desktop.
Encrypt and Decrypt string using Typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as crypto from 'crypto'; | |
// Secret key generation (should be stored securely and not hardcoded) | |
const secretKey = crypto.createHash('sha256').update(String('your-secret-key')).digest('base64').substr(0, 32); | |
function encrypt(text: string): string { | |
const iv = crypto.randomBytes(16); // Initialization vector | |
const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(secretKey), iv); | |
const encrypted = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()]); | |
// Return the IV and encrypted data as a combined string | |
return iv.toString('hex') + ':' + encrypted.toString('hex'); | |
} | |
function decrypt(encryptedData: string): string { | |
const textParts = encryptedData.split(':'); | |
const iv = Buffer.from(textParts.shift()!, 'hex'); | |
const encryptedText = Buffer.from(textParts.join(':'), 'hex'); | |
const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(secretKey), iv); | |
const decrypted = Buffer.concat([decipher.update(encryptedText), decipher.final()]); | |
return decrypted.toString('utf8'); | |
} | |
// Usage example | |
const originalText = 'Hello, World!'; | |
const encryptedText = encrypt(originalText); | |
const decryptedText = decrypt(encryptedText); | |
console.log('Original Text:', originalText); | |
console.log('Encrypted Text:', encryptedText); | |
console.log('Decrypted Text:', decryptedText); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment