在C#中验证Java签名

时间:2018-08-31 23:44:49

标签: java c# cryptography

我已经按照以下代码在Java中创建了签名

KeyFactory keyFactory = KeyFactory.getInstance("RSA");
EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
signature = (Signature) rsaSha256.getCipher();

signature.initSign(privateKey);
signature.update(binaryData);
signatureBytes = signature.sign();

通过在C#中验证签名,即时消息总是错误的。以下代码使用BouncyCastle库

ISigner signer = SignerUtilities.GetSigner("SHA256withRSA");

using (TextReader sr = new StringReader(publicKey))
    {
       PemReader pr = new PemReader(sr);
       RsaKeyParameters keys = (RsaKeyParameters)pr.ReadObject();

       signer.Init(false, keys);
       signer.BlockUpdate(value, 0, value.Length);
       bool isValid = signer.VerifySignature(signature);

       return isValid;
    }

以下代码也返回false

private static bool VerifyWithPublicKey(byte[] data, byte[] sig, string publicKey)
    {
        RSACryptoServiceProvider rsa;

        using (var keyreader = new StringReader(publicKey))
        {
            var pemReader = new PemReader(keyreader);
            var y = (RsaKeyParameters)pemReader.ReadObject();
            RSAParameters p1 = DotNetUtilities.ToRSAParameters(y);
            rsa = new RSACryptoServiceProvider();

            rsa.ImportParameters(p1);
        }


        byte[] hash;
        using (var sha256 = SHA256.Create())
        {
            hash = sha256.ComputeHash(data);
        }

        RSAPKCS1SignatureDeformatter RSADeformatter = new RSAPKCS1SignatureDeformatter(rsa);
        RSADeformatter.SetHashAlgorithm("SHA256");
        //Verify the hash and display the results to the console. 
        if (RSADeformatter.VerifySignature(hash, sig))
        {
            Console.WriteLine("The signature was verified.");
        }
        else
        {
            Console.WriteLine("The signature was NOT verified.");
        }

        // This always returns false
        return rsa.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA256"), sig);
    }

我没有主意。有人做过类似的事情吗?如果是这样,请您分享您的代码

1 个答案:

答案 0 :(得分:0)

这对我有用,我发现在使用.GetSigner(“ SHA256withRSA”)的地方有所不同,但是我使用的是“ SHA-256withRSA”

    public static bool VerifySignature(byte[] hashBytes, byte[] signatureBytes)
    {
        PemReader pemReader = new PemReader(new StreamReader("PublicKey.pem"));
        RsaKeyParameters parameters = (RsaKeyParameters)pemReader.ReadObject();

        RsaDigestSigner signer = (RsaDigestSigner)SignerUtilities.GetSigner("SHA-256withRSA");
        signer.Init(false, parameters);

        signer.BlockUpdate(hashBytes, 0, hashBytes.Length);
        bool isValid = signer.VerifySignature(signatureBytes);

        return isValid;
    }