Skip to content

Instantly share code, notes, and snippets.

@hmmhmmhm
Last active June 20, 2021 07:49
Show Gist options
  • Save hmmhmmhm/89e200e3501b4d155901baee3cae0f74 to your computer and use it in GitHub Desktop.
Save hmmhmmhm/89e200e3501b4d155901baee3cae0f74 to your computer and use it in GitHub Desktop.
javascript format preserving
import fe1 from 'node-fe1-fpe'
export interface IFPESetting {
min: number
max: number
privateKey: string
publicKey: string
}
export const encrypt = ({
index,
min,
max,
privateKey,
publicKey,
}: IFPESetting & {
index: number
}): number => {
// Algorithm can be applied only when the difference
// between the min and max values is at least 4.
if (max - min < 3) return index
// Algorithms can only be applied when the
// range difference between min and max is prime number.
// Therefore, when the range difference is not prime number,
// the algorithm is applied while leaving the last index intact.
// if ((max - min) % 2 === 0) {
// if (index === max) return index
// --max
// }
if ((max - min) % 2 === 0) {
// console.log('enc yes')
const middle = Math.ceil(min + (max - min) / 2)
// console.log('encrypted middle', middle)
if (index === middle) return max
if (index === max) index = middle
--max
}
// Algorithm does not apply to index
// values that are not in the range.
if (index < min || index > max) return index
return fe1.encrypt(max - min + 1, index - min, privateKey, publicKey) + min
}
export const decrypt = ({
index,
min,
max,
privateKey,
publicKey,
}: IFPESetting & {
index: number
}): number => {
// Algorithm can be applied only when the difference
// between the min and max values is at least 4.
if (max - min < 3) return index
// Algorithms can only be applied when the
// range difference between min and max is prime number.
// Therefore, when the range difference is not prime number,
// the algorithm is applied while leaving the last index intact.
const isNonPrime = (max - min) % 2 === 0
if (isNonPrime) {
if (index > max - 1) {
return Math.ceil(min + (max - min) / 2)
}
--max
}
// Algorithm does not apply to index
// values that are not in the range.
if (index < min || index > max) return index
if (isNonPrime) {
if (
index ===
encrypt({
index: Math.ceil(min + (max - min) / 2),
max,
min,
privateKey,
publicKey,
})
)
return max + 1
}
return fe1.decrypt(max - min + 1, index - min, privateKey, publicKey) + min
}
const settings: IFPESetting = {
min: -5,
max: 100,
privateKey: 'some private string',
publicKey: 'some public string',
}
for (let i = -8; i <= 102; i++) {
const encrypted = encrypt({
index: i,
...settings,
})
const decrypted = decrypt({
index: encrypted,
...settings,
})
console.log(i, encrypted, decrypted)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment