C sharp¶
/// <summary>
/// 解密类
/// </summary>
public class RC4
{
public byte[] Encrypt(byte[] pwd, byte[] data)
{
int a, i, j, k, tmp;
int[] key, box;
byte[] cipher;
key = new int[256];
box = new int[256];
cipher = new byte[data.Length];
for (i = 0; i < 256; i++)
{
key[i] = pwd[i % pwd.Length];
box[i] = i;
}
for (j = i = 0; i < 256; i++)
{
j = (j + box[i] + key[i]) % 256;
tmp = box[i];
box[i] = box[j];
box[j] = tmp;
}
for (a = j = i = 0; i < data.Length; i++)
{
a++;
a %= 256;
j += box[a];
j %= 256;
tmp = box[a];
box[a] = box[j];
box[j] = tmp;
k = box[((box[a] + box[j]) % 256)];
cipher[i] = (byte)(data[i] ^ k);
}
return cipher;
}
public byte[] Decrypt(byte[] pwd, byte[] data)
{
return Encrypt(pwd, data);
}
}
[Serializable]
[JsonObject(MemberSerialization.OptIn)]
public class SmartPhoneResult
{
/// <summary>
/// 结果码
/// </summary>
[JsonProperty(PropertyName = "errcode")]
public string ErrCode { get; set; }
/// <summary>
/// 返回信息
/// </summary>
[JsonProperty(PropertyName = "errmsg")]
public string ErrMsg { get; set; }
/// <summary>
/// 实际数据
/// </summary>
[JsonProperty(PropertyName = "data")]
public object Data { get; set; }
}
public class EhrRC4Case
{
/// <summary>
/// 解密方法
/// </summary>
/// <returns></returns>
public string Decrypt()
{
try
{
string corpSecret = "{你的企业的corp_secret}";
string accessToken = "{你的企业的access_token}";
string url = string.Format("https://openapi.2haohr.com/api/departments/?access_token={0}", accessToken);
string result = Get(url);
//接口数据反序列化
SmartPhoneResult smartPhoneResult = JsonConvert.DeserializeObject<SmartPhoneResult>(result);
//解密
//取data数据转换二进制
byte[] bytes = Convert.FromBase64String(smartPhoneResult.Data.ToString());
RC4 rc = new RC4();
byte[] pasText = rc.Decrypt(Encoding.UTF8.GetBytes(corpSecret), bytes);
string dataReal = Base64StringToString(Convert.ToBase64String(pasText));
return dataReal;
}
catch (Exception ex)
{
return ex.ToString();
}
}
public static string Base64StringToString(string base64)
{
if (base64 != "")
{
char[] charBuffer = base64.ToCharArray();
byte[] bytes = Convert.FromBase64CharArray(charBuffer, 0, charBuffer.Length);
string returnstr = Encoding.UTF8.GetString(bytes);
return returnstr;
}
else
{
return "";
}
}
public string Get(string url)
{
//取接口数据
System.Net.HttpWebRequest request = System.Net.WebRequest.Create(url) as System.Net.HttpWebRequest;
request.Method = "GET";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Ssl3;
System.Net.HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse;
System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
string result = sr.ReadToEnd();
sr.Close();
return result;
}
}