接入GoogelAdmob C#服务器端验证 (SSV) 回调

记一次接入谷歌广告验证
官方文档:https://developers.google.cn/admob/android/rewarded-video-ssv
需要httpserver进行验证,项目里有httpserver,因此通过将服务端ip端口绑定域名的方法进行验证回调。
验证回调:在官网添加应用了可以添加回调网址进行验证

加密使用的是ECDSA,c#解决方案参考:https://stackoverflow.com/questions/61659891/c-sharp-signature-verification-using-ecdsa-with-sha256-certificate

获取公钥网址:http://www.gstatic.com/admob/reward/verifier-keys.json
获得的json格式如下:{"keys":[{"keyId":3335741209,"pem":"-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE+nzvoGqvDeB9+SzE6igTl7TyK4JB\nbglwir9oTcQta8NuG26ZpZFxt+F2NDk7asTE6/2Yc8i1ATcGIqtuS5hv0Q==\n-----END PUBLIC KEY-----","base64":"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE+nzvoGqvDeB9+SzE6igTl7TyK4JBbglwir9oTcQta8NuG26ZpZFxt+F2NDk7asTE6/2Yc8i1ATcGIqtuS5hv0Q=="}]}
pem和base64都可以进行验证,但需要转化成统一格式

验证过程:
            var pubkeyString =
@"-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE+nzvoGqvDeB9+SzE6igTl7TyK4JBbglwir9oTcQta8NuG26ZpZFxt+F2NDk7asTE6/2Yc8i1ATcGIqtuS5hv0Q==
-----END PUBLIC KEY-----";
            var pemreader = new PemReader(new StringReader(pubkeyString));
            var pubkey = (AsymmetricKeyParameter)pemreader.ReadObject();

            var data = "ad_network=5450213213286189855&ad_unit=1234567890&custom_data=106&reward_amount=1&reward_item=Reward&timestamp=1621586055036&transaction_id=123456789&user_id=11111";
            StringBuilder signature = new StringBuilder();
            signature.Append("MEYCIQCaRAEhqLlOBwSHrlNcZyunYROD3xIMROOD+zAamwlFDwIhANDRk9qXfAZg/BCLslzmqy2PFXk3fr3tQjaEqqSdaRyP");
            //对base64格式化,替换和补位
            signature = signature.Replace('-', '+').Replace('_', '/');
            int remainder = signature.Length % 4;
            if(remainder > 0)
            {
                signature.Append('=', 4 - remainder);
            }
            var signatureBytes = Convert.FromBase64String(signature.ToString());

            // Verify using the public key
            var signer = SignerUtilities.GetSigner("SHA-256withECDSA");
            signer.Init(false, pubkey);
            signer.BlockUpdate(Encoding.UTF8.GetBytes(data), 0, data.Length);
            var success = signer.VerifySignature(signatureBytes);

            if (success)
            {
                Console.WriteLine("Signature verified successfully using public key");
            }
            else
            {
                Console.WriteLine("Failed to verify signature using public key");
            }
 附上可验收上述代码的,可以根据算法在线生成公钥私钥、加密数据、验证签名的网址:https://8gwifi.org/ecsignverify.jsp

 

posted @ 2021-05-24 15:10  darkif  阅读(715)  评论(0编辑  收藏  举报