自定义对1到15位长度的密码加解密
示例效果 只是对1到15位长度的密码加解密
将原明文进行ASCII码的增加转换 使其成为一个长度为16的字串 变相实现加密
解密就是根据之前的转换思路 进行相关逆运算 得到原明文
有需要的朋友 可以根据思路进行相关扩充
以使其符合自已的需要
#region 对1-15位明文加密
protected void Button1_Click(object sender, EventArgs e)
{
string strToEncrypt = this.txt_明文.Text.Trim();
this.txt_加密.Text = Encrypt(strToEncrypt);
}
#endregion
#region 解密
protected void Button2_Click(object sender, EventArgs e)
{
string strToDecrypt = this.txt_加密.Text.Trim();
this.txt_解密.Text = Decrypt(strToDecrypt);
}
#endregion
int intA = 11;
int intB = 19;
#region 加密 返回加密后的字串
private string Encrypt(string strToEncrypt)
{
//先对原明文的长度进行相关判断 使其符合1-15这个范围
string strEncrypted = "";
//利用原明文长度 将其做为加密后密码的第1位
strEncrypted += (char)(Convert.ToString(strToEncrypt.Length, 16)[0] - intA);
//
for (int i = 0; i < strToEncrypt.Length; i++)
{
//32-126
int intNewChar = strToEncrypt[i] + intB;
if (intNewChar > 126)
{
intNewChar = intNewChar - 127 + 32;
}
strEncrypted += Convert.ToChar(intNewChar).ToString();
}
if (strEncrypted.Length < 16)
{
string strEncrypted2 = "";
string strTemp = Guid.NewGuid().ToString().Substring(0, (16 - strEncrypted.Length));
//
for (int j = 0; j < strTemp.Length; j++)
{
if (j < strEncrypted.Length)
strEncrypted2 += strEncrypted[j].ToString();
strEncrypted2 += strTemp[j].ToString();
}
if (strTemp.Length < strEncrypted.Length)
strEncrypted2 += strEncrypted.Substring(strTemp.Length);
strEncrypted = strEncrypted2;
}
//返回加密后字串
return strEncrypted;
}
#endregion
#region 解密 返回解密后的字串
private string Decrypt(string strToDecrypt)
{
string strLength = Convert.ToString((char)(strToDecrypt[0] + intA));
int intPwdLength = Convert.ToInt32(strLength, 16);
string strDecrypted = "";
for (int i = 1; i < strToDecrypt.Length; i++)
{
//32-126
int intOldChar = strToDecrypt[i] - intB;
if (intOldChar < 32)
{
intOldChar = intOldChar - 32 + 127;
}
strDecrypted += Convert.ToChar(intOldChar).ToString();
}
string strDecrypted2 = "";
for (int j = 1; j < strDecrypted.Length; j = j + 2)
{
strDecrypted2 += strDecrypted[j].ToString();
}
//
if (intPwdLength < 8)
{
strDecrypted = strDecrypted2.Substring(0, intPwdLength);
}
else
{
strDecrypted = strDecrypted2.Substring(0, 15 - intPwdLength) + strDecrypted.Substring((15 - intPwdLength) * 2);
}
//返回解密后字串
return strDecrypted;
}
#endregion
posted on 2008-08-05 13:14 freeliver54 阅读(732) 评论(1) 编辑 收藏 举报