Skip to content

Instantly share code, notes, and snippets.

@atahani
Last active November 25, 2020 05:37
Show Gist options
  • Save atahani/95926eb266279ba1ef6c74b22a8c9fa4 to your computer and use it in GitHub Desktop.
Save atahani/95926eb266279ba1ef6c74b22a8c9fa4 to your computer and use it in GitHub Desktop.
import { randomBytes, publicEncrypt, createCipheriv, privateDecrypt, createDecipheriv } from 'crypto'
import { RSA_PKCS1_PADDING } from 'constants'
type EncryptResult = {
sign: string
encryptedRequestData: string
}
export const encryptWithPublicKey = (publicKey: string, requestData: Record<string, any>): EncryptResult => {
const secret = randomBytes(16).toString('hex')
const sign = publicEncrypt({ key: publicKey, padding: RSA_PKCS1_PADDING }, Buffer.from(secret)).toString('base64')
const iv = randomBytes(8).toString('hex')
const cipher = createCipheriv('aes-256-cbc', secret, iv)
let encrypted = cipher.update(JSON.stringify(requestData))
encrypted = Buffer.concat([encrypted, cipher.final()])
return {
sign,
encryptedRequestData: iv + encrypted.toString('base64'),
}
}
export const decryptSecret = (sign: string, privateKey: string): string =>
privateDecrypt({ key: privateKey, padding: RSA_PKCS1_PADDING }, Buffer.from(sign, 'base64')).toString()
export const decryptContent = (secret: string, encryptedText: string): string => {
const iv = encryptedText.substr(0, 16)
const originalData = encryptedText.substr(16)
const decipher = createDecipheriv('aes-256-cbc', Buffer.from(secret), iv)
let decrypted = decipher.update(Buffer.from(originalData, 'base64'))
decrypted = Buffer.concat([decrypted, decipher.final()])
return decrypted.toString()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment