80 lines
2.0 KiB
C#
80 lines
2.0 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Web;
|
|
using System.Text;
|
|
|
|
namespace Education
|
|
{
|
|
public class EncDec
|
|
{
|
|
/// <summary>
|
|
/// WLIB 新版密碼的加密函數
|
|
/// </summary>
|
|
/// <param name="S">欲加密之密碼字串,最大長度 8 位,僅可包含A-Z、a-z、0-9</param>
|
|
/// <returns>加密後之密碼字串</returns>
|
|
public static string KeyEnc(string S)
|
|
{
|
|
int k1 = 0;
|
|
int k2 = 0;
|
|
int i, j;
|
|
Random rnd = new Random(DateTime.UtcNow.AddHours(8).Millisecond);
|
|
byte[] inBuf = new byte[8];
|
|
byte[] outBuf = new byte[10];
|
|
string tmp;
|
|
|
|
while (true)
|
|
{
|
|
k1 = rnd.Next(31);
|
|
k2 = rnd.Next(31);
|
|
outBuf[0] = (byte)(k1 + 44);
|
|
outBuf[9] = (byte)(k2 + 66);
|
|
|
|
if (S.Length < 8)
|
|
inBuf = Encoding.ASCII.GetBytes(S.PadRight(8));
|
|
else
|
|
inBuf = Encoding.ASCII.GetBytes(S);
|
|
|
|
for (i = 1; i <= 8; i++)
|
|
{
|
|
j = (k1 % 31) + i;
|
|
j = ((k2 + j) % 31) + 1;
|
|
|
|
outBuf[i] = (byte)(inBuf[i - 1] ^ j);
|
|
}
|
|
tmp = Encoding.ASCII.GetString(outBuf);
|
|
if (tmp.IndexOf('\'') < 0 && tmp.IndexOf('"') < 0)
|
|
break;
|
|
}
|
|
return tmp;
|
|
}
|
|
|
|
/// <summary>
|
|
/// WLIB 新版密碼的解密函數
|
|
/// </summary>
|
|
/// <param name="S">欲解密之密碼字串,固定 10 位</param>
|
|
/// <returns>解密後之密碼字串。若參數 S 長度不是 10 位,則傳回".." + S + ".."</returns>
|
|
public static string KeyDec(string S)
|
|
{
|
|
int i, j;
|
|
int Key1, Key2;
|
|
byte[] inBuf;
|
|
byte[] outBuf = new byte[8];
|
|
|
|
if (S.Length != 10)
|
|
return ".." + S + "..";
|
|
|
|
//解密
|
|
inBuf = Encoding.ASCII.GetBytes(S);
|
|
Key1 = inBuf[0] - 44;
|
|
Key2 = inBuf[9] - 66;
|
|
|
|
for (i = 1; i <= 8; i++)
|
|
{
|
|
j = Key1 % 31 + i;
|
|
j = (Key2 + j) % 31 + 1;
|
|
outBuf[i - 1] = (byte)(inBuf[i] ^ j);
|
|
}
|
|
return Encoding.ASCII.GetString(outBuf).Trim();
|
|
}
|
|
}
|
|
} |