Usually Unity would handle the certificate automatically and validate it against known root certificates or ignore them completely depending on the platform:
UnityWebRequest.certificateHandler:
Setting this property to null
makes the platform use the default certificate validation. Some platforms will validate certificates against a root certificate authority store. Other platforms will simply bypass certificate validation completely.
Using a self-signed certificate, however, will fail if Unity decides for the first.
So, for https
with a self-signed certificate you might have to implement a CertificateHandler
that implements the method ValidateCertificate
.
You could either simply bypass the certificate by accepting them all (which is easier but ofcourse would make the https
kind of pointless)
public class BypassCertificate : CertificateHandler
{
protected override bool ValidateCertificate(byte[] certificateData)
{
//Simply return true no matter what
return true;
}
}
Or try this example from the docs with your public key
// Based on https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#.Net
class AcceptAllCertificatesSignedWithASpecificPublicKey : CertificateHandler
{
// Encoded RSAPublicKey
private static string PUB_KEY = "30818902818100C4A06B7B52F8D17DC1CCB47362" +
"C64AB799AAE19E245A7559E9CEEC7D8AA4DF07CB0B21FDFD763C63A313A668FE9D764E" +
"D913C51A676788DB62AF624F422C2F112C1316922AA5D37823CD9F43D1FC54513D14B2" +
"9E36991F08A042C42EAAEEE5FE8E2CB10167174A359CEBF6FACC2C9CA933AD403137EE" +
"2C3F4CBED9460129C72B0203010001";
protected override bool ValidateCertificate(byte[] certificateData)
{
X509Certificate2 certificate = new X509Certificate2(certificateData);
string pk = certificate.GetPublicKeyString();
return pk.Equals(PUB_KEY));
}
}
And add it to your request
using(var www = UnityWebRequest.Get("https://example.com"))
{
//www.certificateHandler = new BypassCertificate();
// Or
www.certificateHandler = new AcceptAllCertificatesSignedWithASpecificPublicKey();
yield return www.SendWebRequest();
//...
}
Note: Custom certificate validation is currently only implemented for the following platforms - Android, iOS, tvOS and desktop platforms.
So on Android you should be fine.
The CertificateHandler
is by default automatically disposed together with the UnityWebRequest
so there is no more to do.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…