RSA signing and verification gives unexpected different output - rsa

Following https://wizardforcel.gitbooks.io/practical-cryptography-for-developers-book/content/digital-signatures/rsa-sign-verify-examples.html , I was trying to sign and verify a simple message using my self generated public and private key. However, I unexpected get a different value for signature and hashFromSignature. Any help is much appreciated.
p = <some valid p>
q = <some valid q>
e = 65537
n = p*q
# compute n
n = p * q
# Compute phi(n)
phi = (p - 1) * (q - 1)
# Compute modular inverse of e
d = getModInverse(e, phi)
# Make sure d is computed correctly
print("d: " + str(d))
check = (e*d)%phi
print(check)
privateKey = RSA.construct((n, e, d))
publicKey = RSA.construct((n, e))
msg = b'A message for signing'
hash = int.from_bytes(sha512(msg).digest(), byteorder='big')
signature = pow(hash, d, n)
print("Signature:", hex(signature))
msg = b'A message for signing'
hash = int.from_bytes(sha512(msg).digest(), byteorder='big')
hashFromSignature = pow(signature, e, n)
print(hex(hashFromSignature))
print("Signature valid:", hash == hashFromSignature)

Related

Using the GPU with Lux and NeuralPDE Julia

I am trying to run a model using the GPU, no problem with the CPU. I think somehow using measured boundary conditions is causing the issue but I am not sure. I am following this example: https://docs.sciml.ai/dev/modules/NeuralPDE/tutorials/gpu/. I am following this example for using measured boundary conditions: https://docs.sciml.ai/dev/modules/MethodOfLines/tutorials/icbc_sampled/
using Random
using NeuralPDE, Lux, CUDA, Random
using Optimization
using OptimizationOptimisers
using NNlib
import ModelingToolkit: Interval
using Interpolations
# Measured Boundary Conditions (Arbitrary For Example)
bc1 = 1.0:1:1001.0 .|> Float32
bc2 = 1.0:1:1001.0 .|> Float32
ic1 = zeros(101) .|> Float32
ic2 = zeros(101) .|> Float32;
# Interpolation Functions Registered as Symbolic
itp1 = interpolate(bc1, BSpline(Cubic(Line(OnGrid()))))
up_cond_1_f(t::Float32) = itp1(t)
#register_symbolic up_cond_1_f(t)
itp2 = interpolate(bc2, BSpline(Cubic(Line(OnGrid()))))
up_cond_2_f(t::Float32) = itp2(t)
#register_symbolic up_cond_2_f(t)
itp3 = interpolate(ic1, BSpline(Cubic(Line(OnGrid()))))
init_cond_1_f(x::Float32) = itp3(x)
#register_symbolic init_cond_1_f(x)
itp4 = interpolate(ic2, BSpline(Cubic(Line(OnGrid()))))
init_cond_2_f(x::Float32) = itp4(x)
#register_symbolic init_cond_2_f(x);
# Parameters and differentials
#parameters t, x
#variables u1(..), u2(..)
Dt = Differential(t)
Dx = Differential(x);
# Arbitrary Equations
eqs = [Dt(u1(t, x)) + Dx(u2(t, x)) ~ 0.,
Dt(u1(t, x)) * u1(t,x) + Dx(u2(t, x)) + 9.81 ~ 0.]
# Boundary Conditions with Measured Data
bcs = [
u1(t,1) ~ up_cond_1_f(t),
u2(t,1) ~ up_cond_2_f(t),
u1(1,x) ~ init_cond_1_f(x),
u2(1,x) ~ init_cond_2_f(x)
]
# Space and time domains
domains = [t ∈ Interval(1.0,1001.0),
x ∈ Interval(1.0,101.0)];
# Neural network
input_ = length(domains)
n = 10
chain = Chain(Dense(input_,n,NNlib.tanh_fast),Dense(n,n,NNlib.tanh_fast),Dense(n,4))
strategy = GridTraining(.25)
ps = Lux.setup(Random.default_rng(), chain)[1]
ps = ps |> Lux.ComponentArray |> gpu .|> Float32
discretization = PhysicsInformedNN(chain,
strategy,
init_params=ps)
# Model Setup
#named pdesystem = PDESystem(eqs,bcs,domains,[t,x],[u1(t, x),u2(t, x)])
prob = discretize(pdesystem,discretization);
sym_prob = symbolic_discretize(pdesystem,discretization);
# Losses and Callbacks
pde_inner_loss_functions = sym_prob.loss_functions.pde_loss_functions
bcs_inner_loss_functions = sym_prob.loss_functions.bc_loss_functions
callback = function (p, l)
println("loss: ", l)
println("pde_losses: ", map(l_ -> l_(p), pde_inner_loss_functions))
println("bcs_losses: ", map(l_ -> l_(p), bcs_inner_loss_functions))
return false
end;
# Train Model (Throws Error)
res = Optimization.solve(prob,Adam(0.01); callback = callback, maxiters=5000)
phi = discretization.phi;
I get the following error:
GPU broadcast resulted in non-concrete element type Union{}.
This probably means that the function you are broadcasting contains an error or type instability.
Please Advise.

Are unsigned long types available to LibreOffice Basic?

I'm want to write a simple 32-bit FNV hash function for LibreOffice Calc. However, LibreOffice Basic only supports signed long data types, so you will get an "Inadmissible value or data type. Overflow." error on line 7 with the following code:
Function Hash(strText as String) as Long
Dim h As Long
Dim nextChar As String
Dim temp As Long
h = 2166136261
For i = 1 To Len(strText)
nextChar = Mid(strText, i, 1)
temp = Asc(nextChar)
h = h XOR temp
h = h * 16777619
Next
Hash = h
End Function
Because the h variable is assigned 2166136261 in the code above, it is obviously out of bounds. Is it possible to work with unsigned long (0 to 4294967295) data types in LibreOffice Basic? If so, how?
You could do this:
Sub CallHash
oMasterScriptProviderFactory = createUnoService(_
"com.sun.star.script.provider.MasterScriptProviderFactory")
oScriptProvider = oMasterScriptProviderFactory.createScriptProvider("")
oScript = oScriptProvider.getScript(_
"vnd.sun.star.script:foo.py$hash?language=Python&location=user")
hashString = oScript.invoke(Array("bar"), Array(), Array())
MsgBox hashString
End Sub
foo.py:
def hash(strText):
h = 2166136261
for nextChar in strText:
temp = ord(nextChar)
h = h ^ temp
h = h * 16777619
return str(h)
Or drop Basic and use only Python-UNO.
There are unsigned long values in the UNO API. However, I didn't find any API methods to perform calculations on this object.
Dim o As Object
o = CreateUnoValue("unsigned long", 2166136261)

How do I use numba's "guvectorize" decorator to change two arrays in the same function?

I'm using numba's #guvectorize to change two different arrays. The code is:
#guvectorize([(int64[:], int64[:], int64[:], int64[:])], '(n),(n)->(n),(n)', target= 'parallel')
def g(x, y, res, res_two):
res = x
for i in range(x.shape[0]-1):
var = np.random.poisson((2),1)[0]
res_two[i] = var
res[i+1] = res[i] + res_two[i]
print("res[i+1] is", res[i+1], "for x[i] is", x[i])
q = (np.arange(5)) * 0
q[0] = 5
r = (np.arange(5)) * 0
g(q,r)
print("q is", q)
print("r is", r)
And the results printed out are:
As one can see, q is changing, but r isn't.
What must I do to use guvectorize to input two arrays and change those two arrays?

cula use of culaSgels - wrong argument?

I am trying to use the culaSgels function in order to solve Ax=B.
I modified the systemSolve example of the cula package.
void culaFloatExample()
{
int N=2;
int NRHS = 2;
int i,j;
double cula_time,start_time,end_time;
culaStatus status;
culaFloat* A = NULL;
culaFloat* B = NULL;
culaFloat* X = NULL;
culaFloat one = 1.0f;
culaFloat thresh = 1e-6f;
culaFloat diff;
printf("Allocating Matrices\n");
A = (culaFloat*)malloc(N*N*sizeof(culaFloat));
B = (culaFloat*)malloc(N*N*sizeof(culaFloat));
X = (culaFloat*)malloc(N*N*sizeof(culaFloat));
if(!A || !B )
exit(EXIT_FAILURE);
printf("Initializing CULA\n");
status = culaInitialize();
checkStatus(status);
// Set A
A[0]=1;
A[1]=2;
A[2]=3;
A[3]=4;
// Set B
B[0]=5;
B[1]=6;
B[2]=2;
B[3]=3;
printf("Calling culaSgels\n");
// Run CULA's version
start_time = getHighResolutionTime();
status = culaSgels('N',N,N, NRHS, A, N, A, N);
end_time = getHighResolutionTime();
cula_time = end_time - start_time;
checkStatus(status);
printf("Verifying Result\n");
for(i = 0; i < N; ++i){
for (j=0;j<N;j++)
{
diff = X[i+j*N] - B[i+j*N];
if(diff < 0.0f)
diff = -diff;
if(diff > thresh)
printf("\nResult check failed: X[%d]=%f B[%d]=%f\n", i, X[i+j*N],i, B[i+j*N]);
printf("\nResults:X= %f \t B= %f:\n",X[i+j*N],B[i+j*N]);
}
}
printRuntime(cula_time);
printf("Shutting down CULA\n\n");
culaShutdown();
free(A);
free(B);
}
I am using culaSgels('N',N,N, NRHS, A, N, A, N); to solve the system but :
1) The results show me that every element of X=0 , but B is right.
Also , it shows me the
Result check failed message
2) Studying the reference manual ,it says that one argument before the last argument (the A I have) ,should be the matrix B stored columnwised,but if I use "B" instead of "A" as parameter ,then I am not getting the correct B matrix.
Ok,code needs 3 things to work.
1) Change A to B ,so culaSgels('N',N,N, NRHS, A, N, B, N);
(I misunderstood that at exit B contains the solution)
2) Because CULA uses column major change A,B matrices accordingly.
3) Change to :
B = (culaFloat*)malloc(N*NRHS*sizeof(culaFloat));
X = (culaFloat*)malloc(N*NRHS*sizeof(culaFloat));
(use NHRS and not N which is the same in this example)
Thanks!

How to decrypt RSA text from p, q and d ('data greater than mod len' error)

I'm trying to decrypt some text using the p, q & d RSA parameters. This is my code:
use Crypt::OpenSSL::RSA;
my $cipher_text = '21822641296030233094227313655848509440605583067924377543599838215888039562622129112129822895080408267928468534668157995224253484645729278749085139763130764635317451011719149549123004731102607506049461610797920861018820451965633121194245016524243388070479379308761222809258576639629711274935572812821629596774863705897518352434753834386314245125246066390859225185066330366811073476496684635339997048026729834327425483254569562337608819782060439696539771993138092386150797070320410153423661265108318321693803297014167486821806691214248145774922909225478697375135263295662839076540338821496045675607198591575588621659609';
my ($p, $q, $d) = (
Crypt::OpenSSL::Bignum->new_from_decimal('165531801682935357262784768224825567629908164720968584885888440012850606062817307481747891600670103793664550471500745014914678541225436018211939431390053926336912952441897829541865006123774689488999658248640982182224222754377835611000656130261325362538051966725284846900143448968656908810497538272078057741753'),
Crypt::OpenSSL::Bignum->new_from_decimal('161793529444258956657578160951133315733795687396943555542529109270426552912409876020630999202216058708771830991232800413521618941159308875874915491167328976063871230426911602170436153334762815254160844789590951618176633523800724364347786188020741173210831867848084340389279221308498668063580976312456313708227'),
Crypt::OpenSSL::Bignum->new_from_decimal('4726230781685159301129128926091597612191418774972180765730674153946543720175721375641429858288249804644693058129864174539693448753576337835228363947222471089804797108134073771268482070990981157234925023770851307423738245681533737104667110764794379344770670194385194083716134044195705274587539907463141446593440244816853972305589231700346121402158165643863387848676660192091263041614047764528653983145902131144938355047165291147495652786645127063867131916536922764685613090037417336307735248968661966233168304037079723873034096551522712515691482108402916631034263410195810822874808411813091006049133015592459279891521'),
);
my $n = $p->mul($q, Crypt::OpenSSL::Bignum::CTX->new());
# I use d as e because e is mandatory and I don't have it. Later I'll use public_decrypt instead of decrypt.
my $rsa = Crypt::OpenSSL::RSA->new_key_from_parameters($n, $d, undef, $p, $q);
my $text = $rsa->public_decrypt($cipher_text);
But that gives me:
RSA.xs:202: OpenSSL error: data greater than mod len at test.pl line 14
Which I don't really know what means, data is not greater that d or n.
:-?
EDITED
The following python code works so I far as I know the keys and data are good.
from Crypto.PublicKey import RSA
p = 165531801682935357262784768224825567629908164720968584885888440012850606062817307481747891600670103793664550471500745014914678541225436018211939431390053926336912952441897829541865006123774689488999658248640982182224222754377835611000656130261325362538051966725284846900143448968656908810497538272078057741753
q = 161793529444258956657578160951133315733795687396943555542529109270426552912409876020630999202216058708771830991232800413521618941159308875874915491167328976063871230426911602170436153334762815254160844789590951618176633523800724364347786188020741173210831867848084340389279221308498668063580976312456313708227
d = 4726230781685159301129128926091597612191418774972180765730674153946543720175721375641429858288249804644693058129864174539693448753576337835228363947222471089804797108134073771268482070990981157234925023770851307423738245681533737104667110764794379344770670194385194083716134044195705274587539907463141446593440244816853972305589231700346121402158165643863387848676660192091263041614047764528653983145902131144938355047165291147495652786645127063867131916536922764685613090037417336307735248968661966233168304037079723873034096551522712515691482108402916631034263410195810822874808411813091006049133015592459279891521
n = p * q
cypher_text = 21822641296030233094227313655848509440605583067924377543599838215888039562622129112129822895080408267928468534668157995224253484645729278749085139763130764635317451011719149549123004731102607506049461610797920861018820451965633121194245016524243388070479379308761222809258576639629711274935572812821629596774863705897518352434753834386314245125246066390859225185066330366811073476496684635339997048026729834327425483254569562337608819782060439696539771993138092386150797070320410153423661265108318321693803297014167486821806691214248145774922909225478697375135263295662839076540338821496045675607198591575588621659609
decrypter = RSA.construct((n, 0L, d, p, q))
text = decrypter.key._decrypt(cypher_text)
print(text)
The error signifies that there's a mismatch between the key size and the data.
I'm not a python expert but IIRC it handles big numbers in core, and you've got cipher_text as a text string.
The cipher text looks like a decimal which we want as a binary string, so I think you want:
my $cipher_text = Crypt::OpenSSL::Bignum->new_from_decimal( '21822....' )->to_bin;
This turns out to be 256 bytes which sounds about right.
Now the error is:
RSA.xs:202: OpenSSL error: unknown padding type at rsa.pl line 20
I'm not sure about this, but I have to take the kids out now anyway :)