Search code examples
javac#x509certificatesha1

Could not verify SHA1 signature with RSA


I am trying to verify a certificate signature in Java, but it is failing. I guess there is a difference between SHA1 and SHA1withRSA, but how do I fix it?

This is code for signing in using C# (certificate is mycer.p12):

static string Sign(string token, string cer_name, string passw)
        {
            try
            {
                if (!File.Exists(cer_name))
                {
                    MessageBox.Show("File not found " + cer_name);
                    return "";
                }
                X509Certificate2 cert = new X509Certificate2(cer_name, passw, X509KeyStorageFlags.Exportable);
                RSACryptoServiceProvider csp = null;
                csp = (RSACryptoServiceProvider)cert.PrivateKey;
                if (csp == null)
                {
                    MessageBox.Show("No valid cert was found");
                    return "";
                }
                Encoding encoding = Encoding.GetEncoding("UTF-8");
                byte[] data = encoding.GetBytes(token);
                RSACryptoServiceProvider rsaClear = new RSACryptoServiceProvider();
                rsaClear.ImportParameters(csp.ExportParameters(true));
                byte[] signature = rsaClear.SignData(data, CryptoConfig.MapNameToOID("SHA1"));
                bool isValid = csp.VerifyData(data, "SHA1", signature);
                if (isValid) return Convert.ToBase64String(signature).Trim(new char[] { '\0', '\n' }).Replace("\n", "");
                else
                {
                    MessageBox.Show("Siganture verification = FALSE");
                    return "";
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
                return "";
            }
        }

I use this command to extract public key

openssl pkcs12 -in mycer.p12 -clcerts -nokeys -out publicKEY.pem

And now this code in Java to verify but it returns false:

 public static boolean verify(String plainText, String signature, String publicKeyFile) {
            try {
CertificateFactory f = CertificateFactory.getInstance("X.509");
        X509Certificate certificate = (X509Certificate)f.generateCertificate(new FileInputStream(publicKeyFile));
                Signature publicSignature = Signature.getInstance("SHA1withRSA");
                publicSignature.initVerify(publicKey);
                publicSignature.update(plainText.getBytes("UTF-8"));
                byte[] signatureBytes = Base64.decode(signature);
                return publicSignature.verify(signatureBytes);
            } catch (InvalidKeyException | NoSuchAlgorithmException | SignatureException | UnsupportedEncodingException e) {
                e.printStackTrace();
                return false;
            }
        }

Solution

  • This post helped me https://stackoverflow.com/a/16980246/1444413

    KeyStore p12 = KeyStore.getInstance("pkcs12");
    p12.load(new FileInputStream("mycer.p12"), "password".toCharArray());
    String alias = (String) p12.aliases().nextElement();
    X509Certificate c = (X509Certificate) p12.getCertificate(alias);
    .... c.getPublicKey() ....
    

    And then method verify().. returned true.