加密方法有很多,以下是其中一種簡單的簽名模式
創(chuàng)新互聯(lián)公司-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價比印臺網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式印臺網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋印臺地區(qū)。費用合理售后完善,10年實體公司更值得信賴。1、首先客戶端通過webapi按照IP地址,時間戳,隨機數(shù)生成簽名,并傳遞序列號
private Result_Sign Valid()
{
string ServerIP = "192.168.1.6";// HttpContext.Request.ServerVariables.Get("Local_Addr").ToString(); //地址
string timestamp = DateTimeToStamp(DateTime.Now); //時間戳
string nonce = ST.WEB.App_Start.Common.CreateValidateCode(6);//隨機數(shù)
string SignStr = SignatureString(ServerIP, timestamp, nonce);//生成簽名
string appseq = ConfigurationManager.AppSettings["DPSeq"]; //產(chǎn)品序列號
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) != "錯誤")
{
resJson = JsonConvert.DeserializeObject<Result_Sign>(resStr);
}
return resJson;
}
// DateTime時間格式轉(zhuǎn)換為Unix時間戳格式
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();
}
//生成隨機數(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;
}
//生成隨機數(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);
}
//抽取隨機數(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;
}
/// <summary>
/// 獲取遠程服務(wù)器ATN結(jié)果
/// </summary>
/// <param name="strUrl">指定URL路徑地址</param>
/// <param name="timeout">超時時間設(shè)置</param>
/// <returns>服務(wù)器ATN結(jié)果</returns>
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 = "錯誤:" + exp.Message;
}
return strResult;
}
2、服務(wù)器端獲取數(shù)據(jù)并驗證返回結(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;
}
/// <summary>
/// 檢查應(yīng)用接入的數(shù)據(jù)完整性
/// </summary>
/// <param name="signature">加密簽名內(nèi)容</param>
/// <param name="timestamp">時間戳</param>
/// <param name="nonce">隨機字符串</param>
/// <param name="appseq">序列號</param>
/// <returns></returns>
public static bool ValidateSignature(string signature, string timestamp, string nonce, string appseq)
{
bool result = false;
Register item = Cache.GetBySeq(appseq);//獲取序列號相關(guān)信息
if (item != null)
{
if (DateTime.Parse(item.ExpireDT) < DateTime.Now.Date) //是否過期
{
return result;
}
#region 校驗簽名參數(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))
{ //驗證成功
DateTime dtTime = StampToDateTime(timestamp);
double minutes = DateTime.Now.Subtract(dtTime).TotalMinutes;
if (minutes < 5) //時間不能大于5分鐘
{
result = true;
}
}
#endregion
}
return result;
}
/// <summary>
/// 時間戳轉(zhuǎn)時間
/// </summary>
/// <param name="timeStamp"></param>
/// <returns></returns>
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);
}
/// <summary>
/// 是否為數(shù)字
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
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; }
}
創(chuàng)新互聯(lián)www.cdcxhl.cn,專業(yè)提供香港、美國云服務(wù)器,動態(tài)BGP最優(yōu)骨干路由自動選擇,持續(xù)穩(wěn)定高效的網(wǎng)絡(luò)助力業(yè)務(wù)部署。公司持有工信部辦法的idc、isp許可證, 機房獨有T級流量清洗系統(tǒng)配攻擊溯源,準確進行流量調(diào)度,確保服務(wù)器高可用性。佳節(jié)活動現(xiàn)已開啟,新人活動云服務(wù)器買多久送多久。
網(wǎng)頁題目:.net簽名加密實現(xiàn)的一種簡單方法-創(chuàng)新互聯(lián)
分享路徑:http://aaarwkj.com/article20/cocgjo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供電子商務(wù)、網(wǎng)站內(nèi)鏈、域名注冊、App開發(fā)、Google、用戶體驗
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容