加密方法有很多,以下是其中一種簡單的簽名模式
創(chuàng)新互聯(lián)從2013年開始,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目網(wǎng)站制作、成都網(wǎng)站建設(shè)網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢想脫穎而出為使命,1280元海晏做網(wǎng)站,已為上家服務(wù),為海晏各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話:18982081108
1、首先客戶端通過webapi按照IP地址,時(shí)間戳,隨機(jī)數(shù)生成簽名,并傳遞序列號(hào)
private Result_Sign Valid()
{
string ServerIP = "192.168.1.6";// HttpContext.Request.ServerVariables.Get("Local_Addr").ToString(); //地址
string timestamp = DateTimeToStamp(DateTime.Now); //時(shí)間戳
string nonce = ST.WEB.App_Start.Common.CreateValidateCode(6);//隨機(jī)數(shù)
string SignStr = SignatureString(ServerIP, timestamp, nonce);//生成簽名
string appseq = ConfigurationManager.AppSettings["DPSeq"]; //產(chǎn)品序列號(hào)
string Url = string.Format("http://www.abc.com:89/api/Valid?signature={0}×tamp={1}&nonce={2}&appseq={3}", SignStr, timestamp, nonce, appseq);//POST發(fā)送URL
string resStr = ST.WEB.App_Start.Common.Get_Http(Url, 12000);
Result_Sign resJson = new Result_Sign()
{
code = "-1",
message = ""
};
if (resStr.Substring(0, 2) != "錯(cuò)誤")
{
resJson = JsonConvert.DeserializeObject
}
return resJson;
}
// DateTime時(shí)間格式轉(zhuǎn)換為Unix時(shí)間戳格式
private string DateTimeToStamp(DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
return ((int)(time - startTime).TotalSeconds).ToString();
}
//生成簽名串
private string SignatureString(string appIP, string timestamp, string nonce)
{
string[] ArrTmp = { appIP, timestamp, nonce };
Array.Sort(ArrTmp);
string tmpStr = string.Join("", ArrTmp);
tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
return tmpStr.ToLower();
}
//生成隨機(jī)數(shù)
public static string CreateValidateCode(int length)
{
int[] randMembers = new int[length];
int[] validateNums = new int[length];
string validateNumberStr = "";
//生成起始序列值
int seekSeek = unchecked((int)DateTime.Now.Ticks);
Random seekRand = new Random(seekSeek);
int beginSeek = (int)seekRand.Next(0, Int32.MaxValue - length * 10000);
int[] seeks = new int[length];
for (int i = 0; i < length; i++)
{
beginSeek += 10000;
seeks[i] = beginSeek;
}
//生成隨機(jī)數(shù)字
for (int i = 0; i < length; i++)
{
Random rand = new Random(seeks[i]);
int pownum = 1 * (int)Math.Pow(10, length);
randMembers[i] = rand.Next(pownum, Int32.MaxValue);
}
//抽取隨機(jī)數(shù)字
for (int i = 0; i < length; i++)
{
string numStr = randMembers[i].ToString();
int numLength = numStr.Length;
Random rand = new Random();
int numPosition = rand.Next(0, numLength - 1);
validateNums[i] = Int32.Parse(numStr.Substring(numPosition, 1));
}
for (int i = 0; i < length; i++)
{
validateNumberStr += validateNums[i].ToString();
}
return validateNumberStr;
}
///
/// 獲取遠(yuǎn)程服務(wù)器ATN結(jié)果
///
/// 指定URL路徑地址
/// 超時(shí)時(shí)間設(shè)置
///
public static string Get_Http(string strUrl, int timeout)
{
string strResult;
try
{
HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strUrl);
myReq.Timeout = timeout;
HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
Stream myStream = HttpWResp.GetResponseStream();
StreamReader sr = new StreamReader(myStream, Encoding.Default);
StringBuilder strBuilder = new StringBuilder();
while (-1 != sr.Peek())
{
strBuilder.Append(sr.ReadLine());
}
strResult = strBuilder.ToString();
}
catch (Exception exp)
{
strResult = "錯(cuò)誤:" + exp.Message;
}
return strResult;
}
2、服務(wù)器端獲取數(shù)據(jù)并驗(yàn)證返回結(jié)果
[HttpGet]
public Result_Sign Sign(string signature, string timestamp, string nonce, string appseq)
{
Result_Sign sign = new Result_Sign()
{
code="0",
message="fault"
};
if (Tool.ValidateSignature(signature, timestamp, nonce, appseq))
{
sign.code = "1";
sign.message = "success";
}
return sign;
}
///
/// 檢查應(yīng)用接入的數(shù)據(jù)完整性
///
/// 加密簽名內(nèi)容
/// 時(shí)間戳
/// 隨機(jī)字符串
/// 序列號(hào)
///
public static bool ValidateSignature(string signature, string timestamp, string nonce, string appseq)
{
bool result = false;
Register item = Cache.GetBySeq(appseq);//獲取序列號(hào)相關(guān)信息
if (item != null)
{
if (DateTime.Parse(item.ExpireDT) < DateTime.Now.Date) //是否過期
{
return result;
}
#region 校驗(yàn)簽名參數(shù)的來源是否正確
string[] ArrTmp = { item.IP, timestamp, nonce };
Array.Sort(ArrTmp);
string tmpStr = string.Join("", ArrTmp);
tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
tmpStr = tmpStr.ToLower();
if (tmpStr == signature && isNumberic(timestamp))
{ //驗(yàn)證成功
DateTime dtTime = StampToDateTime(timestamp);
double minutes = DateTime.Now.Subtract(dtTime).TotalMinutes;
if (minutes < 5) //時(shí)間不能大于5分鐘
{
result = true;
}
}
#endregion
}
return result;
}
///
/// 時(shí)間戳轉(zhuǎn)時(shí)間
///
///
///
private static DateTime StampToDateTime(string timeStamp)
{
DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = long.Parse(timeStamp + "0000000");
TimeSpan toNow = new TimeSpan(lTime);
return dateTimeStart.Add(toNow);
}
///
/// 是否為數(shù)字
///
///
///
protected static bool isNumberic(string message)
{
System.Text.RegularExpressions.Regex rex =
new System.Text.RegularExpressions.Regex(@"^\d+$");
if (rex.IsMatch(message))
{
return true;
}
else
return false;
}
public class Result_Sign
{
public string code { set; get; }
public string message { set; get; }
}