您的位置:首页 > 理论基础 > 计算机网络

U3D 安卓通过openssl创建的电子证书进行HTTPS 加密访问

2017-06-09 19:03 441 查看

Hello ,I am KitStar

在《 使用Openssl 创建可以被Torando使用的crt证书以及Key密钥 》的最后内容中我们创建了用于U3D使用的
client.p12
文件。那么在这一片文章中。我们将使用这个文件并且基于U3D的安卓版本创建 可以访问
Https://...
的功能。

所用工具:HFS

一 , 由于我们的数字证书是由自己创建的签证取签名的。所以存在一个很大的问题。就是在PC平台我们完全可以通过WWW类来链接服务器而且不需要
client.p12
文件。区别的就是URL格式改为“
Https://...
”,PC是可以直接访问的。但是一到安卓或者苹果系统就没有办法使用“
Https://...
”格式的URL了。错误提示大概就是访问的网站不是权威机构签证认可的网络签证。

所以我们在安卓和苹果系统中将要使用这个
System.Security.Cryptography.X509Certificates
类库来加载
client.p12
。并且通过
System.Net.HttpWebRequest
来进行网页访问。

下来我直接附上代码了:

using UnityEngine;
using System.Collections;
using System.Net;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Xml;
using System.Net.Security;

public class SGMWPETH5 : MonoBehaviour {

string filePath = null;

X509Certificate2 adminClient;
string clientCertPath = "";

//服务器URL
static string baseUrl = "https://192.168.1.69:10010";

// Use this for initialization
void Start () {

filePath = Application.persistentDataPath;

clientCertPath = filePath + "/client.p12";

Debug.Log(clientCertPath);
StartCoroutine(GetCert());

}

// Update is called once per frame
void Update () {

}

//加个按钮调用这个函数就OK了
public void OnButtonClientToServer()
{
StartCoroutine(GetCert());
}

/// <summary>
/// 检查client.p12文件是否存在。大概由于U3D打包压缩什么的。如果在打包的时候连同这个文件一起打包。在运行软件的时候是没法访问到这个文件的。所以不存在还需要先下载一边。
/// </summary>
/// <returns></returns>
private IEnumerator GetCert()
{
if (File.Exists(clientCertPath))
{
//如果文件存在。那么直接跳到高潮吧
MakeRestCall();
}
else
{
//此处由于服务器还没有相应的Get这个文件的请求。所以使用了HFS这个网络文件服务器来下载client.p12文件。
WWW download = new WWW("http://192.168.1.69/client.p12");
yield return download;

if (download.error != null)
{
print("Error downloading: " + download.error);
}
else
{
File.WriteAllBytes(clientCertPath, download.bytes);

}
}
}

public XmlDocument MakeRestCall()
{
try
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);

adminClient = new X509Certificate2(clientCertPath, "123456");

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(baseUrl);

request.AuthenticationLevel = AuthenticationLevel.MutualAuthRequested;

request.ClientCertificates.Add(adminClient);

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Debug.Log(response.StatusDescription);

XmlDocument xmlDoc = new XmlDocument();

return xmlDoc;
}
catch(WebException ex)
{
XmlDocument xmlDoc = new XmlDocument();
return xmlDoc;
}

}

public static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
//TODO Make this more secure
return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: