I found 2 similar questions and tried to run the code given as solution as those said answers are not working out for me so raising the question with snippet of code.
Both’s said answer is not working so please DONT treat this question as DUPLICATE
here is my code.
import com.sun.org.apache.xml.internal.security.utils.Base64;
import java.io.FileInputStream;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import xmlread.ReadXMLFile;
public class CertificateTest {
public static void main(String[] sdd) {
try{
FileInputStream fin = new FileInputStream("pub.arm");
CertificateFactory f = CertificateFactory.getInstance("X.509");
X509Certificate certificate = (X509Certificate) f.generateCertificate(fin);
PublicKey pk = certificate.getPublicKey();
byte[] sign = "Qn/rlJRdZAdlPpu1UmmjE+rup8rv8d6XlS9MngAorzYDXefw0vWEP4eHil3YHoA1JUkoQQOgmw0w0QZFmrQbS33sa2t76iuqXI7EtnAPU798K+hEXP88tsYDWJNJFo9DdhkGltP5dQ02DN030Q1w58aTF+yZFfY1KVOPx2bIoL8=".getBytes();
Signature sig = Signature.getInstance("SHA1withRSA");
sig.initVerify(pk);
sig.update(Base64.decode(ReadXMLFile.getString().getBytes()));
boolean verifies = sig.verify(Base64.decode(ReadXMLFile.getString().getBytes()));
System.out.println("signature verifies: " + verifies);
}catch(Exception ex){}
}
}
Below is the explanation before I knew that
ReadXMLFile.getStringwas not the data whose integrity was being tested but rather the encoded signature itself. See our discussion for the resolution!Your code is wrong — you’re trying to compare the RSA-encrypted SHA1 digest of the base64-decoded
ReadXMLFile.getString()to itself.From the specification for
Signature.update:Then, from
Signature.verify:Now, you’re not actually passing the signature data into
verify! Did you mean to dosig.verify(Base64.decode(sign))instead?If you need further proof, post
pub.armand I can demonstrate working, correct code 🙂