##################
# rsacrack.bdscr #
##################
println("Three public modulus values, 512 bits each...")
n1=0xa9c737dd808d02866fbf1acf05de2eb124137007a4965ec4dcbfa6d02f97e0123a8fd3691e414a1382f38ab39b09975705eceaf1131a283c937b309f1c1417f9
n2=0xb7e9e114a08adff12f762d7f0e1f16202e1eb7a7f2852369bdf44865783d19111e6d61b31de987bcb9775099e220a798d4f99cd3e5f04c64f87a35c0268a83e9
n3=0xc2bdbd4e36ba20d37d5d1e968f09f2fc7b41a97f3052274e4892d50d5fb337c923048aed7d393135ee55711e5c74975867f13d3845bac9588b4be170d08bab57
println("n1=", hex(n1))
println("n2=", hex(n2))
println("n3=", hex(n3))
# Common public exponent
e=3
println("Common public exponent, e=", e)
# Message to be encrypted...
m=0x2ffffffffffffffffffffffffffffffffffffffffff0000deadbeefcafe
println("Message, m=", hex(m))
# Compute three ciphertexts...
c1 = modexp(m, e, n1)
c2 = modexp(m, e, n2)
c3 = modexp(m, e, n3)
println("Three ciphertexts sent to three recipients...")
println("c1=", hex(c1))
println("c2=", hex(c2))
println("c3=", hex(c3))

# Check moduli are pairwise coprime...
println("Check moduli are pairwise coprime...")
g12 = gcd(n1,n2)
g23 = gcd(n2,n3)
g31 = gcd(n3,n1)
println("gcd(n1,n2)=", g12)
println("gcd(n2,n3)=", g23)
println("gcd(n3,n1)=", g31)
assert(g12==1 and g23==1 and g31==1, "Require moduli to be pairwise coprime")

println("Do calculations...")
# Compute N=n1*n2*n3
N = n1*n2*n3
# Compute N1 = N/n1, etc
N1 = N/n1
N2 = N/n2
N3 = N/n3
d1 = modinv(N1,n1)
d2 = modinv(N2,n2)
d3 = modinv(N3,n3) 
# Compute x = c_1 N_1 d_1 + c_2 N_2 d_2 + c_3 N_3 d_3 (mod N)...
# (do in steps, all modulo N)
x1=modmul(modmul(c1,N1,N),d1,N)
x2=modmul(modmul(c2,N2,N),d2,N)
x3=modmul(modmul(c3,N3,N),d3,N)
x = (x1+x2+x3) mod N
println("x=", hex(x))
m1 = cbrt(x)
println("m1=cbrt(x)=", hex(m1))
# Do we have a match?
println("Match? (m == m1) is ", bool(m==m1))
if (m==m1) then println("SUCCESS") else println("FAILED!") fi


# c1=4dadb8068a56e87fda9388b6e6975b0118d9b285e26546d15edbb4ab94265ea49dabe85925ff9
# f6dc3d0d6975f3a84f7db91d23da35152ebeb2c2e94d3467adb
# c2=2113c0493defdaaaece30e43943fa8734e45378d35ee7e1efd917c846d30bf2efb630e3bc0752
# 706df31ac94f7ec20fef1456819eae8e8fbe0d9e747faa259b9
# c3=697e6f45ff2f845976640c73705dfeca79f9ba637931caa32f38fcb68015d5414a357dbea8519
# 0cfa5887196512d6c19407ee4f8430df467dd89b367227658a7
# gcd(n1,n2)=1
# gcd(n2,n3)=1
# gcd(n3,n1)=1
# Computed value of x = c_1 N_1 d_1 + c_2 N_2 d_2 + c_3 N_3 d_3 (mod N)...
# x=1affffffffffffffffffffffffffffffffffffffffe500177c53234a68ca000000000000000000
# 00000008fff057cf6263efd3971f5f0729087423ffffffffff00029c06f7baa23b1dc0c685f44bea
# cf1668948b646783f8
# m'=cuberoot(x)=2ffffffffffffffffffffffffffffffffffffffffff0000deadbeefcafe