using System;
|
using System.Collections;
|
using System.Collections.Generic;
|
using System.IO;
|
using System.Linq;
|
using System.Net;
|
using System.Security.Cryptography;
|
using System.Text;
|
using System.Threading.Tasks;
|
using System.Xml;
|
|
namespace Api.MessageReceive.Service
|
{
|
internal class Cryptography
|
{
|
|
public static UInt32 HostToNetworkOrder(UInt32 inval)
|
{
|
UInt32 outval = 0;
|
for (int i = 0; i < 4; i++)
|
outval = (outval << 8) + ((inval >> (i * 8)) & 255);
|
return outval;
|
}
|
|
public static Int32 HostToNetworkOrder(Int32 inval)
|
{
|
Int32 outval = 0;
|
for (int i = 0; i < 4; i++)
|
outval = (outval << 8) + ((inval >> (i * 8)) & 255);
|
return outval;
|
}
|
|
/// <summary>
|
///
|
/// </summary>
|
/// <param name="input"></param>
|
/// <param name="encodingAESKey"></param>
|
/// <param name="corpid"></param>
|
/// <returns></returns>
|
public static string AES_decrypt(String input, string encodingAESKey, ref string corpid)
|
{
|
byte[] key;
|
key = Convert.FromBase64String(encodingAESKey + "=");
|
byte[] iv = new byte[16];
|
Array.Copy(key, iv, 16);
|
byte[] btmpMsg = AES_decrypt(input, iv, key);
|
|
int len = BitConverter.ToInt32(btmpMsg, 16);
|
len = IPAddress.NetworkToHostOrder(len);
|
|
byte[] bMsg = new byte[len];
|
byte[] bCorpid = new byte[btmpMsg.Length - 20 - len];
|
Array.Copy(btmpMsg, 20, bMsg, 0, len);
|
Array.Copy(btmpMsg, 20 + len, bCorpid, 0, btmpMsg.Length - 20 - len);
|
string oriMsg = Encoding.UTF8.GetString(bMsg);
|
corpid = Encoding.UTF8.GetString(bCorpid);
|
|
return oriMsg;
|
}
|
|
public static String AES_encrypt(String input, string encodingAESKey, string corpid)
|
{
|
byte[] key;
|
key = Convert.FromBase64String(encodingAESKey + "=");
|
byte[] iv = new byte[16];
|
Array.Copy(key, iv, 16);
|
string randcode = CreateRandCode(16);
|
byte[] bRand = Encoding.UTF8.GetBytes(randcode);
|
byte[] bCorpid = Encoding.UTF8.GetBytes(corpid);
|
byte[] btmpMsg = Encoding.UTF8.GetBytes(input);
|
byte[] bMsgLen = BitConverter.GetBytes(HostToNetworkOrder(btmpMsg.Length));
|
byte[] bMsg = new byte[bRand.Length + bMsgLen.Length + bCorpid.Length + btmpMsg.Length];
|
|
Array.Copy(bRand, bMsg, bRand.Length);
|
Array.Copy(bMsgLen, 0, bMsg, bRand.Length, bMsgLen.Length);
|
Array.Copy(btmpMsg, 0, bMsg, bRand.Length + bMsgLen.Length, btmpMsg.Length);
|
Array.Copy(bCorpid, 0, bMsg, bRand.Length + bMsgLen.Length + btmpMsg.Length, bCorpid.Length);
|
|
return AES_encrypt(bMsg, iv, key);
|
}
|
|
private static string CreateRandCode(int codeLen)
|
{
|
string codeSerial = "2,3,4,5,6,7,a,c,d,e,f,h,i,j,k,m,n,p,r,s,t,A,C,D,E,F,G,H,J,K,M,N,P,Q,R,S,U,V,W,X,Y,Z";
|
if (codeLen == 0)
|
{
|
codeLen = 16;
|
}
|
string[] arr = codeSerial.Split(',');
|
string code = "";
|
int randValue = -1;
|
Random rand = new Random(unchecked((int)DateTime.Now.Ticks));
|
for (int i = 0; i < codeLen; i++)
|
{
|
randValue = rand.Next(0, arr.Length - 1);
|
code += arr[randValue];
|
}
|
return code;
|
}
|
|
private static String AES_encrypt(String input, byte[] iv, byte[] key)
|
{
|
var aes = new RijndaelManaged();
|
//秘钥的大小,以位为单位
|
aes.KeySize = 256;
|
//支持的块大小
|
aes.BlockSize = 128;
|
//填充模式
|
aes.Padding = PaddingMode.PKCS7;
|
aes.Mode = CipherMode.CBC;
|
aes.Key = key;
|
aes.IV = iv;
|
var encrypt = aes.CreateEncryptor(aes.Key, aes.IV);
|
byte[] xBuff = null;
|
|
using (var ms = new MemoryStream())
|
{
|
using (var cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write))
|
{
|
byte[] xXml = Encoding.UTF8.GetBytes(input);
|
cs.Write(xXml, 0, xXml.Length);
|
}
|
xBuff = ms.ToArray();
|
}
|
String output = Convert.ToBase64String(xBuff);
|
return output;
|
}
|
|
private static String AES_encrypt(byte[] input, byte[] iv, byte[] key)
|
{
|
var aes = new RijndaelManaged();
|
//秘钥的大小,以位为单位
|
aes.KeySize = 256;
|
//支持的块大小
|
aes.BlockSize = 128;
|
//填充模式
|
//aes.Padding = PaddingMode.PKCS7;
|
aes.Padding = PaddingMode.None;
|
aes.Mode = CipherMode.CBC;
|
aes.Key = key;
|
aes.IV = iv;
|
var encrypt = aes.CreateEncryptor(aes.Key, aes.IV);
|
byte[] xBuff = null;
|
|
#region 自己进行PKCS7补位,用系统自己带的不行
|
|
byte[] msg = new byte[input.Length + 32 - input.Length % 32];
|
Array.Copy(input, msg, input.Length);
|
byte[] pad = KCS7Encoder(input.Length);
|
Array.Copy(pad, 0, msg, input.Length, pad.Length);
|
|
#endregion 自己进行PKCS7补位,用系统自己带的不行
|
|
#region 注释的也是一种方法,效果一样
|
|
//ICryptoTransform transform = aes.CreateEncryptor();
|
//byte[] xBuff = transform.TransformFinalBlock(msg, 0, msg.Length);
|
|
#endregion 注释的也是一种方法,效果一样
|
|
using (var ms = new MemoryStream())
|
{
|
using (var cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write))
|
{
|
cs.Write(msg, 0, msg.Length);
|
}
|
xBuff = ms.ToArray();
|
}
|
|
String output = Convert.ToBase64String(xBuff);
|
return output;
|
}
|
|
private static byte[] KCS7Encoder(int text_length)
|
{
|
int block_size = 32;
|
// 计算需要填充的位数
|
int amount_to_pad = block_size - (text_length % block_size);
|
if (amount_to_pad == 0)
|
{
|
amount_to_pad = block_size;
|
}
|
// 获得补位所用的字符
|
char pad_chr = Chr(amount_to_pad);
|
string tmp = "";
|
for (int index = 0; index < amount_to_pad; index++)
|
{
|
tmp += pad_chr;
|
}
|
return Encoding.UTF8.GetBytes(tmp);
|
}
|
|
/**
|
* 将数字转化成ASCII码对应的字符,用于对明文进行补码
|
*
|
* @param a 需要转化的数字
|
* @return 转化得到的字符
|
*/
|
|
private static char Chr(int a)
|
{
|
byte target = (byte)(a & 0xFF);
|
return (char)target;
|
}
|
|
private static byte[] AES_decrypt(String input, byte[] iv, byte[] key)
|
{
|
RijndaelManaged aes = new RijndaelManaged();
|
aes.KeySize = 256;
|
aes.BlockSize = 128;
|
aes.Mode = CipherMode.CBC;
|
aes.Padding = PaddingMode.None;
|
aes.Key = key;
|
aes.IV = iv;
|
var decrypt = aes.CreateDecryptor(aes.Key, aes.IV);
|
byte[] xBuff = null;
|
using (var ms = new MemoryStream())
|
{
|
using (var cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write))
|
{
|
byte[] xXml = Convert.FromBase64String(input);
|
byte[] msg = new byte[xXml.Length + 32 - xXml.Length % 32];
|
Array.Copy(xXml, msg, xXml.Length);
|
cs.Write(xXml, 0, xXml.Length);
|
}
|
xBuff = Decode2(ms.ToArray());
|
}
|
return xBuff;
|
}
|
|
private static byte[] Decode2(byte[] decrypted)
|
{
|
int pad = (int)decrypted[decrypted.Length - 1];
|
if (pad < 1 || pad > 32)
|
{
|
pad = 0;
|
}
|
byte[] res = new byte[decrypted.Length - pad];
|
Array.Copy(decrypted, 0, res, 0, decrypted.Length - pad);
|
return res;
|
}
|
}
|
|
/// <summary>
|
///
|
/// </summary>
|
public class WXBizMsgCrypt
|
{
|
private string _sToken;
|
private string _sEncodingAESKey;
|
private string _m_sAppID;
|
|
private enum WXBizMsgCryptErrorCode
|
{
|
WXBizMsgCrypt_OK = 0,
|
WXBizMsgCrypt_ValidateSignature_Error = -40001,
|
WXBizMsgCrypt_ParseXml_Error = -40002,
|
WXBizMsgCrypt_ComputeSignature_Error = -40003,
|
WXBizMsgCrypt_IllegalAesKey = -40004,
|
WXBizMsgCrypt_ValidateCorpid_Error = -40005,
|
WXBizMsgCrypt_EncryptAES_Error = -40006,
|
WXBizMsgCrypt_DecryptAES_Error = -40007,
|
WXBizMsgCrypt_IllegalBuffer = -40008,
|
WXBizMsgCrypt_EncodeBase64_Error = -40009,
|
WXBizMsgCrypt_DecodeBase64_Error = -40010
|
};
|
|
/// <summary>
|
/// //构造函数
|
/// @param sToken: 企业微信后台,开发者设置的Token
|
/// @param sEncodingAESKey: 企业微信后台,开发者设置的EncodingAESKey
|
/// @param sReceiveId: 不同场景含义不同,详见文档说明
|
/// </summary>
|
/// <param name="sToken"></param>
|
/// <param name="sEncodingAESKey"></param>
|
/// <param name="sReceiveId"></param>
|
public WXBizMsgCrypt(string sToken, string sEncodingAESKey, string m_sAppID)
|
{
|
_sToken = sToken;
|
_m_sAppID = m_sAppID;
|
_sEncodingAESKey = sEncodingAESKey;
|
}
|
|
/// <summary>
|
/// //验证URL
|
/// @param sMsgSignature: 签名串,对应URL参数的msg_signature
|
/// @param sTimeStamp: 时间戳,对应URL参数的timestamp
|
/// @param sNonce: 随机串,对应URL参数的nonce
|
/// @param sEchoStr: 随机串,对应URL参数的echostr
|
/// @param sReplyEchoStr: 解密之后的echostr,当return返回0时有效
|
/// @return:成功0,失败返回对应的错误码
|
/// </summary>
|
/// <param name="sMsgSignature"></param>
|
/// <param name="sTimeStamp"></param>
|
/// <param name="sNonce"></param>
|
/// <param name="sEchoStr"></param>
|
/// <param name="sReplyEchoStr"></param>
|
/// <returns></returns>
|
public int VerifyURL(string sMsgSignature, string sTimeStamp, string sNonce, string sEchoStr, ref string sReplyEchoStr)
|
{
|
try
|
{
|
|
int ret = 0;
|
if (_sEncodingAESKey.Length != 43)
|
{
|
return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_IllegalAesKey;
|
}
|
ret = VerifySignature(_sToken, sTimeStamp, sNonce, sEchoStr, sMsgSignature);
|
if (0 != ret)
|
{
|
return ret;
|
}
|
sReplyEchoStr = "";
|
string cpid = "";
|
try
|
{
|
sReplyEchoStr = Cryptography.AES_decrypt(sEchoStr, _sEncodingAESKey, ref cpid); //m_sReceiveId);
|
}
|
catch (Exception)
|
{
|
sReplyEchoStr = "";
|
return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_DecryptAES_Error;
|
}
|
}
|
catch (Exception)
|
{
|
|
return -1;
|
}
|
|
return 0;
|
}
|
|
/// <summary>
|
/// // 检验消息的真实性,并且获取解密后的明文
|
/// @param sMsgSignature: 签名串,对应URL参数的msg_signature
|
/// @param sTimeStamp: 时间戳,对应URL参数的timestamp
|
/// @param sNonce: 随机串,对应URL参数的nonce
|
/// @param sPostData: 密文,对应POST请求的数据
|
/// @param sMsg: 解密后的原文,当return返回0时有效
|
/// @return: 成功0,失败返回对应的错误码
|
/// </summary>
|
/// <param name="sMsgSignature"></param>
|
/// <param name="sTimeStamp"></param>
|
/// <param name="sNonce"></param>
|
/// <param name="sPostData"></param>
|
/// <param name="sMsg"></param>
|
/// <returns></returns>
|
public int DecryptMsg(string sMsgSignature, string sTimeStamp, string sNonce, string sPostData, ref string sMsg)
|
{
|
if (_sEncodingAESKey.Length != 43)
|
{
|
return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_IllegalAesKey;
|
}
|
XmlDocument doc = new XmlDocument();
|
XmlNode root;
|
string sEncryptMsg;
|
try
|
{
|
doc.LoadXml(sPostData);
|
root = doc.FirstChild;
|
sEncryptMsg = root["Encrypt"].InnerText;
|
}
|
catch (Exception)
|
{
|
return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ParseXml_Error;
|
}
|
//verify signature
|
int ret = 0;
|
ret = VerifySignature(_sToken, sTimeStamp, sNonce, sEncryptMsg, sMsgSignature);
|
if (ret != 0)
|
return ret;
|
//decrypt
|
string cpid = "";
|
try
|
{
|
sMsg = Cryptography.AES_decrypt(sEncryptMsg, _sEncodingAESKey, ref cpid);
|
}
|
catch (FormatException)
|
{
|
sMsg = "";
|
return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_DecodeBase64_Error;
|
}
|
catch (Exception)
|
{
|
sMsg = "";
|
return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_DecryptAES_Error;
|
}
|
//if (cpid != _sReceiveId)
|
// return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ValidateCorpid_Error;
|
return 0;
|
}
|
|
/// <summary>
|
/// //将企业号回复用户的消息加密打包
|
/// @param sReplyMsg: 企业号待回复用户的消息,xml格式的字符串
|
/// @param sTimeStamp: 时间戳,可以自己生成,也可以用URL参数的timestamp
|
/// @param sNonce: 随机串,可以自己生成,也可以用URL参数的nonce
|
/// @param sEncryptMsg: 加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串,
|
/// 当return返回0时有效
|
/// return:成功0,失败返回对应的错误码
|
/// </summary>
|
/// <param name="sReplyMsg"></param>
|
/// <param name="sTimeStamp"></param>
|
/// <param name="sNonce"></param>
|
/// <param name="sEncryptMsg"></param>
|
/// <returns></returns>
|
public int EncryptMsg(string sReplyMsg, string sTimeStamp, string sNonce, ref string sEncryptMsg)
|
{
|
if (_sEncodingAESKey.Length != 43)
|
{
|
return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_IllegalAesKey;
|
}
|
string raw = "";
|
try
|
{
|
raw = Cryptography.AES_encrypt(sReplyMsg, _sEncodingAESKey, _m_sAppID);
|
}
|
catch (Exception)
|
{
|
return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_EncryptAES_Error;
|
}
|
string msgSigature = "";
|
int ret = 0;
|
ret = GenarateSinature(_sToken, sTimeStamp, sNonce, raw, ref msgSigature);
|
if (0 != ret)
|
return ret;
|
sEncryptMsg = "";
|
|
string encryptLabelHead = "<Encrypt><![CDATA[";
|
string encryptLabelTail = "]]></Encrypt>";
|
string msgSigLabelHead = "<MsgSignature><![CDATA[";
|
string msgSigLabelTail = "]]></MsgSignature>";
|
string timeStampLabelHead = "<TimeStamp><![CDATA[";
|
string timeStampLabelTail = "]]></TimeStamp>";
|
string nonceLabelHead = "<Nonce><![CDATA[";
|
string nonceLabelTail = "]]></Nonce>";
|
sEncryptMsg = sEncryptMsg + "<xml>" + encryptLabelHead + raw + encryptLabelTail;
|
sEncryptMsg = sEncryptMsg + msgSigLabelHead + msgSigature + msgSigLabelTail;
|
sEncryptMsg = sEncryptMsg + timeStampLabelHead + sTimeStamp + timeStampLabelTail;
|
sEncryptMsg = sEncryptMsg + nonceLabelHead + sNonce + nonceLabelTail;
|
sEncryptMsg += "</xml>";
|
return 0;
|
}
|
|
/// <summary>
|
///
|
/// </summary>
|
public class DictionarySort : System.Collections.IComparer
|
{
|
|
/// <summary>
|
///
|
/// </summary>
|
/// <param name="oLeft"></param>
|
/// <param name="oRight"></param>
|
/// <returns></returns>
|
public int Compare(object oLeft, object oRight)
|
{
|
string sLeft = oLeft as string;
|
string sRight = oRight as string;
|
int iLeftLength = sLeft.Length;
|
int iRightLength = sRight.Length;
|
int index = 0;
|
while (index < iLeftLength && index < iRightLength)
|
{
|
if (sLeft[index] < sRight[index])
|
return -1;
|
else if (sLeft[index] > sRight[index])
|
return 1;
|
else
|
index++;
|
}
|
return iLeftLength - iRightLength;
|
}
|
}
|
|
//Verify Signature
|
private static int VerifySignature(string sToken, string sTimeStamp, string sNonce, string sMsgEncrypt, string sSigture)
|
{
|
string hash = "";
|
int ret = 0;
|
ret = GenarateSinature(sToken, sTimeStamp, sNonce, sMsgEncrypt, ref hash);
|
if (ret != 0)
|
return ret;
|
if (hash == sSigture)
|
return 0;
|
else
|
{
|
return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ValidateSignature_Error;
|
}
|
}
|
|
/// <summary>
|
///
|
/// </summary>
|
/// <param name="sToken"></param>
|
/// <param name="sTimeStamp"></param>
|
/// <param name="sNonce"></param>
|
/// <param name="sMsgEncrypt"></param>
|
/// <param name="sMsgSignature"></param>
|
/// <returns></returns>
|
public static int GenarateSinature(string sToken, string sTimeStamp, string sNonce, string sMsgEncrypt, ref string sMsgSignature)
|
{
|
ArrayList aL = new ArrayList();
|
aL.Add(sToken);
|
aL.Add(sTimeStamp);
|
aL.Add(sNonce);
|
aL.Add(sMsgEncrypt);
|
aL.Sort(new DictionarySort());
|
string raw = "";
|
for (int i = 0; i < aL.Count; ++i)
|
{
|
raw += aL[i];
|
}
|
|
SHA1 sha;
|
ASCIIEncoding enc;
|
string hash = "";
|
try
|
{
|
sha = new SHA1CryptoServiceProvider();
|
enc = new ASCIIEncoding();
|
byte[] dataToHash = enc.GetBytes(raw);
|
byte[] dataHashed = sha.ComputeHash(dataToHash);
|
hash = BitConverter.ToString(dataHashed).Replace("-", "");
|
hash = hash.ToLower();
|
}
|
catch (Exception)
|
{
|
return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ComputeSignature_Error;
|
}
|
sMsgSignature = hash;
|
return 0;
|
}
|
}
|
}
|