Pseudo Encrypt
Saturday, October 4, 2025
Pseudo Encrypt is a function drawn from the PostgreSQL project.
pseudo_encrypt(int) can be used as a pseudo-random generator of unique values. It produces an integer output that is uniquely associated to its integer input (by a mathematical permutation), but looks random at the same time, with zero collision. This is useful to communicate numbers generated sequentially without revealing their ordinal position in the sequence (for ticket numbers, URLs shorteners, promo codes…)
It’s implementation is defined as:
CREATE OR REPLACE FUNCTION pseudo_encrypt(value int) returns int AS $$
DECLARE
l1 int;
l2 int;
r1 int;
r2 int;
i int:=0;
BEGIN
l1:= (value >> 16) & 65535;
r1:= value & 65535;
WHILE i < 3 LOOP
l2 := r1;
r2 := l1 # ((((1366 * r1 + 150889) % 714025) / 714025.0) * 32767)::int;
l1 := l2;
r1 := r2;
i := i + 1;
END LOOP;
return ((r1 << 16) + l1);
END;
$$ LANGUAGE plpgsql strict immutable;
Let’s implement this in Factor using some of the words from the math.bitwise vocabulary, working with the intermediate results as 32-bit signed integers:
: pseudo-encrypt ( x -- y )
[ -16 shift ] keep [ 16 bits ] bi@ 3 [
[
1366 * 150889 + 714025 rem 714025.0 / 32767 *
round >integer bitxor 32 >signed
] keep swap
] times 16 shift + 32 >signed ;
We can compare our results for [-10..10]
which are helpfully provided on the
original linked page:
IN: scratchpad -10 ..= 10 [ dup pseudo-encrypt "%3d %12d\n" printf ] each
-10 -1270576520
-9 -236348969
-8 -1184061109
-7 -25446276
-6 -1507538963
-5 -518858927
-4 -1458116927
-3 -532482573
-2 -157973154
-1 -1105881908
0 1777613459
1 561465857
2 436885871
3 576481439
4 483424269
5 1905133426
6 971249312
7 1926833684
8 735327624
9 1731020007
10 792482838
Great – it matches!