简体   繁体   English

如何在Android中生成的.net中验证签名

[英]How to verify a signature in .net generated in Android

The problem is the following: 问题如下:

  • I generate the key in Android (Xamarin.Droid): 我在Android(Xamarin.Droid)中生成密钥:

      public IPublicKey CreateKey(string keyID) { /*KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance( KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore"); keyPairGenerator.initialize( new KeyGenParameterSpec.Builder( "key1", KeyProperties.PURPOSE_SIGN) .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512) .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PSS) .build()); KeyPair keyPair = keyPairGenerator.generateKeyPair(); Signature signature = Signature.getInstance("SHA256withRSA/PSS"); signature.initSign(keyPair.getPrivate()); // The key pair can also be obtained from the Android Keystore any time as follows: KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null); PrivateKey privateKey = (PrivateKey)keyStore.getKey("key1", null); PublicKey publicKey = keyStore.getCertificate("key1").getPublicKey();*/ //App.Current.MainPage.DisplayAlert("Info", "Creating a new key pair", "Ok"); // UTILIZANDO RSA KeyPairGenerator kpg = KeyPairGenerator.GetInstance(KeyProperties.KeyAlgorithmRsa, KEYSTORE_NAME); kpg.Initialize( new KeyGenParameterSpec.Builder(keyID, KeyStorePurpose.Sign) .SetSignaturePaddings(KeyProperties.SignaturePaddingRsaPss) .SetDigests(KeyProperties.DigestSha1) .Build() ); KeyPair keyPair = kpg.GenerateKeyPair(); Log.Debug(TAG, "New key created for fingerprint authentication"); return keyPair.Public; } 
  • Then i generate a signature: 然后我生成一个签名:

      KeyStore.PrivateKeyEntry PKentry = (KeyStore.PrivateKeyEntry)_keystore.GetEntry(keyID, null); IPublicKey pk = (IPublicKey)PKentry.Certificate.PublicKey; //this.pk = pk; privKey = PKentry.PrivateKey; //cipher.Init(Cipher.EncryptMode, privKey); //byte[] output = cipher.DoFinal(Encoding.UTF8.GetBytes(input)); //String s = new string(cipher.DoFinal(input)); // signature Signature sig = Signature.GetInstance("SHA1withRSA/PSS"); sig.InitSign(privKey); byte[] inputDataToSign = Encoding.UTF8.GetBytes(input); sig.Update(inputDataToSign); byte[] signatureBytes = sig.Sign(); 
  • And i send the key and the signature to a ASP.net wep API 2 server. 然后我将密钥和签名发送到ASP.net wep API 2服务器。 Client side response generation: 客户端响应生成:

      RegistrationResponse registrationResponse = new RegistrationResponse(); string fcparams = Utils.Base64Encode(JsonConvert.SerializeObject(finalChallengeParams)); registrationResponse.fcParams = fcparams; byte[] signedData = sign(fcparams, registrationRequest.username, facetID); registrationResponse.signedData = signedData; registrationResponse.Base64key = convertPublicKeyToString(publicKey); ... ... private string convertPublicKeyToString(IPublicKey publicKey) { string publicKeyString = Base64.EncodeToString(publicKey.GetEncoded(), 0); return publicKeyString; } 

I send it using Refit Nugget. 我使用改装金块发送。 And this is the code i use when i receive the HTTPRequest on server side: 这是我在服务器端收到HTTPRequest时使用的代码:

[Route("regResponse/")]
    [HttpPost]
    public IHttpActionResult ProcessClientRegistrationResponse([FromBody] RegistrationResponse registrationResponse) 
    {


        //byte[] publicKeyBytes = Convert.FromBase64String(registrationResponse.Base64key);
        byte[] publicKeyBytes = registrationResponse.Base64key;
        AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(publicKeyBytes);

        RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)asymmetricKeyParameter;

        RSAParameters rsaParameters = new RSAParameters();
        rsaParameters.Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned();
        rsaParameters.Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned();

        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        rsa.ImportParameters(rsaParameters);

        /*****/

        string alg = rsa.SignatureAlgorithm;
        byte[] signedData = registrationResponse.signedData;
        byte[] fcParamsBytes = Encoding.UTF8.GetBytes(registrationResponse.fcParams);

        RSACng rsaCng = new RSACng();
        rsaCng.ImportParameters(rsaParameters);

        SHA1Managed hash = new SHA1Managed();
        byte[] hashedData;
        hashedData = hash.ComputeHash(signedData);


        /*********/

        bool rsaCngDataOk1 = rsaCng.VerifyData(fcParamsBytes, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pss);
        bool rsaCngDataOk2 = rsaCng.VerifyData(fcParamsBytes, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pss);
        bool rsaCngDataOk3 = rsaCng.VerifyData(hashedData, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pss);
        bool rsaCngDataOk4 = rsaCng.VerifyData(hashedData, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pss);

        bool rsaCngHashOk1 = rsaCng.VerifyHash(hashedData, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pss);

        bool dataOK1 = rsa.VerifyData(fcParamsBytes, new SHA1CryptoServiceProvider(), signedData);
        bool dataOk2 = rsa.VerifyData(fcParamsBytes, signedData, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);

        bool hashOk = rsa.VerifyHash(hashedData, CryptoConfig.MapNameToOID("SHA1"), signedData);

        return Ok(true);

    }

EVERY bool is wrong. 每个布尔都是错误的。 I think the problem is clearly on the public key. 我认为问题显然在公钥上。 The questions are, 问题是,

  1. does the method publickey.encode() do what i think? 我的方法publickey.encode()会做什么? I think it converts my public key to a byte[] representation (source: Android developer Key Info ) 我认为它将我的公钥转换为byte []表示形式(来源: Android开发人员Key Info

  2. do i convert the received byte[] representation of the key to a correct RSA key? 如何将收到的密钥的byte []表示形式转换为正确的RSA密钥?

  3. Is there any problem on algorithms? 算法有问题吗? I don't think so but we never know... 我不这么认为,但我们永远不知道...

I don't find the solution. 我找不到解决方案。 I searched for ways to import public keys from strings in .net or c# and for ways to export Android Public key to string or byte[] but there's no much help for this concrete questions... 我搜寻了从.net或c#中的字符串导入公钥的方法,以及将Android公钥导出为string或byte []的方法,但是对于这些具体问题没有太多帮助...

@James K Polk gave me the solution. @James K Polk给了我解决方案。 Apparently C# doesn't work well with PSS padding. 显然,C#不能与PSS填充一起很好地工作。 I just had to change it to PKCS1. 我只需要将其更改为PKCS1。 And i changed to digest algorithm too to SHA512. 我也将摘要算法也更改为SHA512。

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

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