Reputation: 179
I want to verify a signature in C++ , which is a random I have signed in Java.
Here is the Java code I used for signing it:
public byte[] sign(byte[] random, PrivateKey privateKey){
byte[] signedRandom = null;
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(privateKey);
signature.update(random);
signedRandom = signature.sign();
return signedRandom;
}
Now i want to verify the signature in C++, I need C++ code equals the following Java code:
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initVerify(publicKey);
signature.update(originalRandom);
signature.verify(signedRandom);
What I have tried so far:
int verifySignedRandom(unsigned char *signedRandom, unsigned char * originalRandom){
EVP_MD_CTX c;
EVP_MD_CTX_init(&c);
EVP_VerifyInit(&c, EVP_sha256());
EVP_VerifyUpdate(&c, originalRandom, (unsigned int)sizeof(originalRandom));
return EVP_VerifyFinal(&c, signedRandom, (unsigned int)strlen((char *)signedRandom), savedPublicKey);
//savedPublicKey was set somewhere else...
}
This method returns 0, but I´m sure the random was signed with the right key and the method needs to return 1...I think there is something wrong with my C++ code for verifying. Maybe one of you know how to do it right.
--Solution--
int verifySignedRandom(unsigned char *signedRandom, int signedRandomSize, unsigned char * originalRandom, int originalSize){
EVP_MD_CTX *ctx = EVP_MD_CTX_create();
const EVP_MD *md = EVP_get_digestbyname("SHA256");
if(!md){
printf("Error creating md");
}
EVP_VerifyInit_ex(ctx, md, NULL);
EVP_VerifyUpdate(ctx, originalRandom, originalSize);
return EVP_VerifyFinal(ctx, signedRandom, signedRandomSize, savedUserPkey);
}
Upvotes: 3
Views: 5231
Reputation: 23058
EVP_VerifyUpdate(&c, originalRandom, (unsigned int)sizeof(originalRandom));
This line looks buggy. sizeof(originalRandom)
is always sizeof(unsigned char*)
which is usually either 4 or 8. You should pass the correct length instead.
Java arrays has their length embedded, but it is not the case for C++ pointers. You may need to add another parameter to verifySignedRandom()
to explicitly specify the length of originalRandom
.
Upvotes: 1