JD2022-TU1/main/phone_apps/JDCompanionApp/Assets/Scripts/ResourceLoading/HttpImageDownloader.cs

85 lines
2.9 KiB
C#

using Network;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
namespace ResourceLoading
{
public class HttpImageDownloader : ImageDownloader
{
private UnityWebRequest request = null;
private DownloadHandlerTexture downloadHandler = null;
private class ConsoleCertificateHandler : CertificateHandler
{
private X509Certificate2 certificate;
public ConsoleCertificateHandler(ConsoleServer resourceServer)
{
certificate = ImportCertFromBase64(resourceServer.TlsCertificate);
}
protected override bool ValidateCertificate(byte[] certificateData)
{
X509Certificate2 certificateDataX509 = new X509Certificate2(certificateData);
return certificateDataX509.GetPublicKeyString().ToLower().Equals(certificate.GetPublicKeyString().ToLower());
}
public X509Certificate2 ImportCertFromBase64(string certificate)
{
if (string.IsNullOrEmpty(certificate))
return new X509Certificate2();
var certBytes = Encoding.UTF8.GetBytes(certificate);
return new X509Certificate2( certBytes, "XXXXXXXXXXXXXX", X509KeyStorageFlags.Exportable);
}
}
public HttpImageDownloader(string url, ConsoleServer resourceServer)
{
request = UnityWebRequestTexture.GetTexture(url);
// apply certificate pinning for the console certificate, if the url contains the console address
if (resourceServer != null)
{
var splittedUrl= resourceServer.PairingUrl.Split(new char[] { '/',':' }, System.StringSplitOptions.RemoveEmptyEntries);
if(splittedUrl.Length>1)
{
if (url.Contains(splittedUrl[1]))
{
Debug.Log("Console Certificate handled ! ");
request.certificateHandler = new ConsoleCertificateHandler(resourceServer);
}
}
}
request.SendWebRequest();
downloadHandler = (DownloadHandlerTexture)request.downloadHandler;
}
public void Dispose()
{
request.Dispose();
request = null;
downloadHandler = null;
}
#region ImageDownloader interface
public bool IsDone { get { return request.isDone; } }
// texture created from the downloaded image
public Texture2D Texture { get { return downloadHandler.texture; } }
// result of the download process
public string Error { get { return request.error; } }
// raw access to downloaded data
public byte[] Bytes { get { return downloadHandler.data; } }
#endregion
}
}