Files
web/packages/trpc/lib/utils/encryption.ts
Joakim Jäderberg daf765f3d5 Merged in feature/wrap-logging (pull request #2511)
Feature/wrap logging

* feat: change all logging to go through our own logger function so that we can control log levels

* move packages/trpc to using our own logger

* merge


Approved-by: Linus Flood
2025-07-03 12:37:04 +00:00

56 lines
1.7 KiB
TypeScript

import "server-only"
import crypto from "crypto"
import { createLogger } from "@scandic-hotels/common/logger/createLogger"
import { env } from "../../env/server"
const algorithm = "DES-ECB"
const encryptionKey = env.BOOKING_ENCRYPTION_KEY
const bufferKey = Buffer.from(encryptionKey, "utf8")
const encryptionLogger = createLogger("encryption")
export function encrypt(originalString: string) {
try {
const cipher = crypto.createCipheriv(algorithm, bufferKey, null)
cipher.setAutoPadding(false)
const bufferString = Buffer.from(originalString, "utf8")
const paddingSize =
bufferKey.length - (bufferString.length % bufferKey.length)
const paddedStr = Buffer.concat([
bufferString,
Buffer.alloc(paddingSize, 0),
])
const buffers: Buffer[] = []
buffers.push(cipher.update(paddedStr))
buffers.push(cipher.final())
const result = Buffer.concat(buffers).toString("base64")
return result
} catch (e) {
encryptionLogger.error("encryption error", e)
return ""
}
}
export function decrypt(encryptedString: string) {
try {
const decipher = crypto.createDecipheriv(algorithm, bufferKey, null)
decipher.setAutoPadding(false)
const buffers: Buffer[] = []
buffers.push(decipher.update(encryptedString, "base64"))
buffers.push(decipher.final())
const result = Buffer.concat(buffers)
.toString("utf8")
/*
* Hexadecimal byte (null byte) replace. These occur when decrypting because
* we're disabling the auto padding for historical/compatibility reasons.
*/
.replace(/(\x00)*/g, "")
return result
} catch (e) {
encryptionLogger.error("decryption error", e)
return ""
}
}