MD5 Encryption Method-mvc

Source: Internet
Author: User
Tags md5 encryption


1. First configure in Config
<appSettings>
<!--club Sparring--
<add key= "SecurityKey" value= "Pl4c5wait6o8tustozulvoq6cukpwqsh"/>
</appSettings>

2. Interface: Receive validation parameters

The order of the encrypted fields on both sides must be consistent

if (Signature = = "")
{
throw new Errexception ("The signature information cannot be empty!") "," 40011 ");
}
if (Signature.tolower ()! = TMPUBLIC.STRTOMD5 ("securitykey=" + getsecuritykey () + "&fchrclubmemberpwd=" + Fchrclubmemberpwd.tostring () + "&fchrclubmemberpwd1=" + fchrclubmemberpwd1.tostring ()))
{
throw new Errexception ("Verify signature failed! "," 40011 ");
}

Public methods:

Secret key
public string Getsecuritykey ()
{
return configurationmanager.appsettings["SecurityKey"]. ToString ();
}


MD5 Calculating strings
public static string StrToMd5 (String str)
{
MD5 MD5 = MD5. Create ();
byte[] Byts = System.Text.Encoding.UTF8.GetBytes (str);
Byts = Md5.computehash (Byts);
StringBuilder builder = new StringBuilder ();
for (int i = 0; i < Byts. Length; i++)
{
Builder. Append (Byts[i]. ToString ("X2"));
}
Return builder. ToString ();
}


public static string strToMd532 (String input)
{
string cl = input;
string pwd = "";
MD5 MD5 = MD5. Create ();//Instantiate a MD5 pair of images
After the encryption is an array of byte type, here should pay attention to the choice of coding utf8/unicode, etc.
Byte[] s = Md5.computehash (Encoding.UTF8.GetBytes (CL));
Converts an array of byte types to a string by using a loop, which is a regular character formatting the resulting
for (int i = 0; i < s.length; i++)
{
The resulting string is formatted using the hexadecimal type. The formatted character is a lowercase letter, and if uppercase (X) is used, the character after the format is uppercase characters

PWD = pwd + s[i]. ToString ("X");

}
return pwd;
}

Complete interface notation:


<summary>
Get User Login
</summary>
<param name= "Context" ></param>
private void Getclublogin (HttpContext context)
{

string json = "[]";
String msg = "Success";
String errcode = "0";
Try
{
String Fchrclubmemberid = Pageutil.request ("Fchrclubmemberid"); Id
String Fchrphoneno = Request ("Fchrphoneno");
String fchrclubmemberpwd = Request ("Fchrclubmemberpwd");

String Signature = Request ("Signature");
if (Signature = = "")
{
throw new Errexception ("The signature information cannot be empty!") "," 40011 ");
}

if (Signature.tolower ()! = TMPUBLIC.STRTOMD5 ("securitykey=" + getsecuritykey () + "&fchrphoneno=" + Fchrphoneno.tostring () + "&fchrclubmemberpwd=" + fchrclubmemberpwd.tostring ()))
{
throw new Errexception ("Verify signature failed! "," 40011 ");
}


String strSQL = @ "Select Fchrphoneno,fchrclubmemberid,fchrclubmemberpwd
FROM dbo. Clubmember
WHERE fchrphoneno= "+ Tmpublic.formatfield (Fchrphoneno) +" and fchrclubmemberpwd= "+ Tmpublic.formatfield ( FCHRCLUBMEMBERPWD);
DataTable dt = dbhelper.gettable (util.connectionstring, strSQL);

if (dt. Rows.Count = = 0)
throw new Errexception ("Phone number or password is wrong! ", apperror.invalidstudent);
Return the found results to the front desk
JSON = Tmpublic.datatable2json (DT);
}
catch (Exception ex)
{
Errcode = Apperror.unknown; Unknown error
msg = ex. Message;
}
JSON = Getjson (Errcode, MSG, JSON);
Context. Response.Write (JSON);
}


Controller:

<summary>
Login
</summary>
<param name= "Fchrphoneno" ></param>
<param name= "Fchrclubmemberpwd" ></param>
<returns></returns>
[ValidateInput (False)]
[Acceptverbs (Httpverbs.post)]
Public ActionResult Checkclublogin (string Fchrphoneno, String fchrclubmemberpwd)
{
Signature encrypted string
String Signature = StrToMd5 ("securitykey=" + getsecuritykey () + "&fchrphoneno=" + fchrphoneno.tostring () + "&AMP;FCHR Clubmemberpwd= "+ fchrclubmemberpwd.tostring ());
Get Login Interface
String postdate = "method=getclublogin&fchrphoneno=" + Fchrphoneno + "&fchrclubmemberpwd=" + fchrClubMemberPwd + "&signature=" + Signature;
string res = Gethttppost (Getapiurl (), postdate);
res = "[" + Res. Replace ("\" "," ' "). Replace ("[", "\" [")]. Replace ("]", "]\" ") +"] ";
DataTable dt = jsonconvert.deserializeobject<datatable> (res);
if (dt. rows[0]["Flag"]. ToString () = = "0")
{
DataTable dt1 = jsonconvert.deserializeobject<datatable> (dt. rows[0]["Data"]. ToString ());
Save the user ID to the session dictionary type ID Fchrphoneno can be
dictionary<string, string> dc = new dictionary<string, string> ();
Write member ID phone number to session
dc. ADD ("Fchrclubmemberid", dt1. rows[0]["Fchrclubmemberid"]. ToString ());
dc. ADD ("Fchrphoneno", dt1. rows[0]["Fchrphoneno"]. ToString ());
Sessino. Addsession (DC);
Determine the location of the failure
if (!string. IsNullOrEmpty (Sessino. Getsessions ("View"). ToString ())//Go back to the last position
{
Return View (Sessino. Getsessions ("View"). ToString ());
}
res = "[" + Res. Replace ("\" "," ' "). Replace ("[", "\" [")]. Replace ("]", "]\" ") +"] ";
DT = jsonconvert.deserializeobject<datatable> (res);
Dt. rows[0]["Data"]. ToString ();
}
Else
{
Prompt error
return new Jsonresult {Data = res};
}
return new Jsonresult {Data = res};
Return View ("Clubmemberadmin"); Jump to Personal Center controller
}


#region MD5 method


//need to be in a. config otherwise Getsecuritykey method cannot use
//<appsettings> key value
//<!--club sparring-->
//<add key= "SecurityKey" value= "Pl4c5wait6o8tustozulvoq6cukpwqsh"/>
//</appsettings>

//Key
public string Getsecuritykey ()
{
return configurationmanager.appsettings["SecurityKey"]. ToString ();
}
//MD5 evaluates the string
public static string StrToMd5 (String str)
{
MD5 MD5 = MD5. Create ();
byte[] Byts = System.Text.Encoding.UTF8.GetBytes (str);
Byts = Md5.computehash (Byts);
StringBuilder builder = new StringBuilder ();
for (int i = 0; i < Byts. Length; i++)
{
Builder. Append (Byts[i]. ToString ("X2"));
}
Return builder. ToString ();
}
//random number
public static string getrandom (int length)
{
Random ran = new random ();
int max = 9;
if (length = = 1)
max = 9;
Else if (length = = 2)
max = A;
else if (length = = 3)
max = 999;
Else I F (length = = 4)
max = 9999;
Else if (length = = 5)
max = 99999;
Else if (length = = 6)
max = 999999;
else if (length = = 7)
max = 9999999;
Else if (length = = 8)
max = 99999999;
Else
max = 999999;

Return ran. Next (1, max). ToString (). PadLeft (length, ' 0 ');
}

Secret key
Private Const string SKey = "QJZGEH6HESZDVJECNFPGUXZAIB7NLQM3";
public static string getrandomstring (int length)
{
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";//75 character (s)
Random r = new Random ();
string result = String. Empty;

Generates a 8-bit long random character that can be changed by its own length
for (int i = 0; i < length; i++)
{
int m = r.next (0, str. LENGTH);//Here the lower bound is 0, the random number can be taken, the upper bound should be 75, because the random number is not the upper bound, that is, the maximum of 74, in line with our test instructions
string s = str. Substring (M, 1);
Result + = s;
}
return result;
}


public static string strToMd532 (String input)
{
string cl = input;
string pwd = "";
MD5 MD5 = MD5. Create ();//Instantiate a MD5 pair of images
After the encryption is an array of byte type, here should pay attention to the choice of coding utf8/unicode, etc.
Byte[] s = Md5.computehash (Encoding.UTF8.GetBytes (CL));
Converts an array of byte types to a string by using a loop, which is a regular character formatting the resulting
for (int i = 0; i < s.length; i++)
{
The resulting string is formatted using the hexadecimal type. The formatted character is a lowercase letter, and if uppercase (X) is used, the character after the format is uppercase characters

PWD = pwd + s[i]. ToString ("X");

}
return pwd;
}
#endregion

MD5 Encryption Method-mvc

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.