简体   繁体   English

用Java生成的C#验证RSA签名

[英]Verficiation RSA Signature in C# generated in Java

I have a signature string, Base64 encoded, a message string in json and a public key string - assume it is base64 encoded generated in Java and I need to validate it in C#. 我有一个签名字符串,Base64编码,json中的消息字符串和一个公共密钥字符串-假定它是用Java生成的base64编码,我需要在C#中进行验证。

I also have a Java Code which should do the verification correctly, but I just can't get make it run in C#. 我也有一个Java代码,可以正确地进行验证,但是我无法使其在C#中运行。 Any help how to do this please? 有什么帮助吗?

import java.security.spec.X509EncodedKeySpec;

import org.apache.commons.codec.binary.Base64;

public class WebHookSecurityUtil
{
    private static final String KEYPAIR_ALGORITHM = "RSA";  // No I18N
    private static final String SIGNATURE_ALGORITHM = "SHA256withRSA";  // No I18N
    private static final String CHARSETNAME = "UTF-8";  // No I18N

    public static boolean verifySignature(String text, String public_key_str, String signature_str) throws Exception
    {
        PublicKey public_key = getPublicKey(public_key_str);

        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initVerify(public_key);
        signature.update(text.getBytes(CHARSETNAME));

        byte[] signatureBytes = Base64.decodeBase64(signature_str);

        return signature.verify(signatureBytes);
    }

    public static PublicKey getPublicKey(String public_key) throws Exception
    {
        byte[] bytes = Base64.decodeBase64(public_key);

        X509EncodedKeySpec ks = new X509EncodedKeySpec(bytes);
        KeyFactory kf = KeyFactory.getInstance(KEYPAIR_ALGORITHM);
        return kf.generatePublic(ks);
    }
}

what I tried is and it always returns false . 我试过的是,它总是返回false

            RSAParameters pubKey = new RSAParameters();
            // Not sure here...
            pubKey.Modulus =Convert.FromBase64String(publicKey);
            pubKey.Exponent = new byte[] { 1, 0, 1 };

            byte[] buffer = System.Text.UTF8Encoding.UTF8.GetBytes(msg);
            byte[] sig = Convert.FromBase64String(signature);
            RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
            provider.ImportParameters(pubKey);
            bool isValid = provider.VerifyData(buffer, CryptoConfig.MapNameToOID("SHA256"), sig);
            Console.WriteLine("SHA256: " + isValid);

After base 64 encoding you need to perform the code from here starting with DecodeX509PublicKey . 在进行base 64编码之后,您需要从DecodeX509PublicKey开始从此处执行代码。 Mickeysoft doesn't support "SubjectPublicKeyInfo" structures which are used within X.509 certificates and PUBLIC KEY PEM structures because it doesn't support standards, preferring their own formats. Mickeysoft不支持X.509证书和PUBLIC KEY PEM结构中使用的“ SubjectPublicKeyInfo”结构,因为它不支持标准,而是支持其自身的格式。 It's starting to change though, but very slowly. 虽然它开始改变,但是非常缓慢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM