第一步:到钉钉开放平台创建应用,我这里创建的是H5微应用
根据页面提示填写相关内容,然后创建
注意:设置的回调地址必须是可访问的回调地址,可访问的意思就是后台代码已经编写,并且没问题,要不然设置会失败。同样在设置回调地址的时候需要验证回调地址的有效性,只有在验证有效后才能保存。
验证过程:
你在填写地址之后,钉钉服务器会以POST方式调用你的回调地址
例如:你的回调地址为 https://dingdingCallBack.cn/dingtalk/callback
钉钉服务器在请求的时候会在你的回调地址后面添加 signature、timestamp、nonce参数,这个时候请求的地址变为
https://dingdingCallBack.cn/dingtalk/callback?signature=signature×tamp=timestamp&nonce=nonce
请求的参数体为:
{
"encrypt":"数据加密字符串"//需要使用解密方法解密 解密方法钉钉有解密文档,后面会贴出相关代码
}
我这边后台回调方法是创建实体类来接收的:
public class DingTalkModel{
public string encrypt{get;set;}
}
因为是post方式,所以我使用实体类接收,同样也可以使用别的方法
但是我们在解密过程中需要用到Url后面附带的参数,这个参数该怎么获取呢?
我这边使用的方法(同样如果你有更好的方法也可以),直接贴代码:
string para=HttpContext.Request.QueryString.Value;
这句代码会获取Url后面的所有参数 ?signature=signature×tamp=timestamp&nonce=nonce 这部分,我这边使用字符串拆分完成,然后使用解密方法解密,具体代码(这里我直接贴了整个类的代码,方便使用) 加密解密方法都有,这里有两个类,一定要看清楚,同样你可以去钉钉官方文档获取C# 版本的解密加密demo 具体地址:https://ding-doc.dingtalk.com/doc#/faquestions/ltr370/7c45555c
类1:
public class DingTalkCrypt
{
private readonly string m_sEncodingAESKey;
private readonly string m_sToken;
private readonly string m_sSuiteKey;
/**ask getPaddingBytes key固定长度**/
private static readonly int AES_ENCODE_KEY_LENGTH = 43;
enum DingTalkCryptErrorCode
{
/**成功**/
SUCCESS = 0,
/**加密明文文本非法**/
ENCRYPTION_PLAINTEXT_ILLEGAL = 900001,
/**加密时间戳参数非法**/
ENCRYPTION_TIMESTAMP_ILLEGAL = 900002,
/**加密随机字符串参数非法**/
ENCRYPTION_NONCE_ILLEGAL = 900003,
/**不合法的aeskey**/
AES_KEY_ILLEGAL = 900004,
/**签名不匹配**/
SIGNATURE_NOT_MATCH = 900005,
/**计算签名错误**/
COMPUTE_SIGNATURE_ERROR = 900006,
/**计算加密文字错误**/
COMPUTE_ENCRYPT_TEXT_ERROR = 900007,
/**计算解密文字错误**/
COMPUTE_DECRYPT_TEXT_ERROR = 900008,
/**计算解密文字长度不匹配**/
COMPUTE_DECRYPT_TEXT_LENGTH_ERROR = 900009,
/**计算解密文字suiteKey不匹配**/
COMPUTE_DECRYPT_TEXT_SuiteKey_ERROR = 900010,
};
/// <summary>
/// 构造函数
/// </summary>
/// <param name="token">钉钉开放平台上,开发者设置的token</param>
/// <param name="encodingAesKey">钉钉开放台上,开发者设置的EncodingAESKey</param>
/// <param name="suiteKey">钉钉开放平台上,开发者设置的suiteKey</param>
public DingTalkCrypt(string token, string encodingAesKey, string suiteKey)
{
m_sToken = token;
m_sSuiteKey = suiteKey;
m_sEncodingAESKey = encodingAesKey;
}
/// <summary>
/// 将消息加密,返回加密后字符串
/// </summary>
/// <param name="sReplyMsg">传递的消息体明文</param>
/// <param name="sTimeStamp">时间戳</param>
/// <param name="sNonce">随机字符串</param>
/// <param name="sEncryptMsg">加密后的消息信息</param>
/// <returns>成功0,失败返回对应的错误码</returns>
public int EncryptMsg(string sReplyMsg, string sTimeStamp, string sNonce, ref string sEncryptMsg, ref string signature)
{
if (string.IsNullOrEmpty(sReplyMsg))
return (int)DingTalkCryptErrorCode.ENCRYPTION_PLAINTEXT_ILLEGAL;
if (string.IsNullOrEmpty(sTimeStamp))
return (int)DingTalkCryptErrorCode.ENCRYPTION_TIMESTAMP_ILLEGAL;
if (string.IsNullOrEmpty(sNonce))
return (int)DingTalkCryptErrorCode.ENCRYPTION_NONCE_ILLEGAL;
if (m_sEncodingAESKey.Length != AES_ENCODE_KEY_LENGTH)
return (int)DingTalkCryptErrorCode.AES_KEY_ILLEGAL;
string raw;
try
{
raw = Cryptography.AES_encrypt(sReplyMsg, m_sEncodingAESKey, m_sSuiteKey);
}
catch (Exception)
{
return (int)DingTalkCryptErrorCode.AES_KEY_ILLEGAL;
}
string msgSigature = "";
int ret = GenerateSignature(m_sToken, sTimeStamp, sNonce, raw, ref msgSigature);
sEncryptMsg = raw;
signature = msgSigature;
return ret;
}
/// <summary>
/// 密文解密
/// </summary>
/// <param name="sMsgSignature">签名串</param>
/// <param name="sTimeStamp">时间戳</param>
/// <param name="sNonce">随机串</param>
/// <param name="sPostData">密文</param>
/// <param name="sMsg">解密后的原文,当return返回0时有效</param>
/// <returns>成功0,失败返回对应的错误码</returns>
public int DecryptMsg(string sMsgSignature, string sTimeStamp, string sNonce, string sPostData, ref string sMsg)
{
if (m_sEncodingAESKey.Length != AES_ENCODE_KEY_LENGTH)
return (int)DingTalkCryptErrorCode.AES_KEY_ILLEGAL;
string sEncryptMsg = sPostData;
int ret = VerifySignature(m_sToken, sTimeStamp, sNonce, sEncryptMsg, sMsgSignature);
string cpid = "";
try
{
sMsg = Cryptography.AES_decrypt(sEncryptMsg, m_sEncodingAESKey, ref cpid);
}
catch (FormatException)
{
sMsg = "";
return (int)DingTalkCryptErrorCode.COMPUTE_DECRYPT_TEXT_SuiteKey_ERROR;
}
if (cpid != m_sSuiteKey)
return (int)DingTalkCryptErrorCode.COMPUTE_DECRYPT_TEXT_SuiteKey_ERROR;
return ret;
}
/// <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 GenerateSignature(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)DingTalkCryptErrorCode.COMPUTE_SIGNATURE_ERROR;
}
sMsgSignature = hash;
return 0;
}
/// <summary>
/// 验证签名
/// </summary>
/// <param name="sToken"></param>
/// <param name="sTimeStamp"></param>
/// <param name="sNonce"></param>
/// <param name="sMsgEncrypt"></param>
/// <param name="sSigture"></param>
/// <returns></returns>
private static int VerifySignature(string sToken, string sTimeStamp, string sNonce, string sMsgEncrypt, string sSigture)
{
string hash = "";
int ret = 0;
ret = GenerateSignature(sToken, sTimeStamp, sNonce, sMsgEncrypt, ref hash);
if (ret != 0)
return ret;
if (hash == sSigture)
return 0;
else
{
return (int)DingTalkCryptErrorCode.SIGNATURE_NOT_MATCH;
}
}
/// <summary>
/// 验证URL
/// </summary>
/// <param name="sMsgSignature">签名串,对应URL参数的msg_signature</param>
/// <param name="sTimeStamp">时间戳,对应URL参数的timestamp</param>
/// <param name="sNonce">随机串,对应URL参数的nonce</param>
/// <param name="sEchoStr">经过加密的消息体,对应URL参数的encrypt</param>
/// <param name="sReplyEchoStr"></param>
/// <returns></returns>
public int VerifyURL(string sMsgSignature, string sTimeStamp, string sNonce, string sEchoStr, ref string sReplyEchoStr)
{
if (m_sEncodingAESKey.Length != 43)
{
return (int)DingTalkCryptErrorCode.AES_KEY_ILLEGAL;
}
int ret = VerifySignature(m_sToken, sTimeStamp, sNonce, sEchoStr, sMsgSignature);
string cpid = "";
try
{
sReplyEchoStr = Cryptography.AES_decrypt(sEchoStr, m_sEncodingAESKey, ref cpid); //m_sCorpID);
}
catch (Exception)
{
sReplyEchoStr = "";
return (int)DingTalkCryptErrorCode.COMPUTE_SIGNATURE_ERROR;
}
if (cpid != m_sSuiteKey)
{
sReplyEchoStr = "";
return (int)DingTalkCryptErrorCode.COMPUTE_DECRYPT_TEXT_SuiteKey_ERROR;
}
return ret;
}
/// <summary>
/// 字典排序
/// </summary>
public class DictionarySort : System.Collections.IComparer
{
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;
}
}
}
类2:
public 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>
/// <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;
}
/// <summary>
/// 加密方法
/// </summary>
/// <param name="Input"></param>
/// <param name="EncodingAESKey"></param>
/// <param name="corpid"></param>
/// <returns></returns>
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
{
//秘钥的大小,以位为单位
KeySize = 256,
//支持的块大小
BlockSize = 128,
//填充模式
Padding = PaddingMode.PKCS7,
Mode = CipherMode.CBC,
Key = Key,
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
#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 转化得到的字符
*/
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;
}
}
调用方式:
//实例化 token、encodingAesKey、suiteKey都在下面这张图位置获取
DingTalkCrypt dingTalkCrypt = new DingTalkCrypt(token, encodingAesKey, suiteKey);
string msg = string.Empty;
//signature、timestamp、nonce为url后面获取到的参数 encrypt为POST请求体中的参数 msg 为解密后的结果
var result = dingTalkCrypt.DecryptMsg(signature, timestamp, nonce, encrypt, ref msg);
解密完成之后;上面的result=0 代表成功 同样msg里面为解密后的数据 如果result!=0 msg的内容为错误信息
成功实示例:{"Random":"success","EventType":"check_create_suite_url","TestSuiteKey":"suitenhecjhgviu0sa2jx"}该结果为解密后的msg的值
解密完成之后,我们根据EventType来确定请求要执行的操作这个自己定义
接下来我们要返回数据了,钉钉这边需要返回一个success的消息给钉钉服务器,都需要返回那些参数呢?
这里就要用到刚才两个类中的数据加密方法了,代码如下:
res="success"//钉钉官方固定返回消息
timeSpan="" //当前时间戳
nonce="" //随机字符串 这里可以使用上面的
encryptMsg为encrypt
new_sign为msg_signature
var result1 = dingTalkCrypt.EncryptMsg(res, timeSpan, dic["nonce"], ref encryptMsg, ref new_sign);
然后将结果组合成Json字符串直接返回
然后我们将服务部署到对应回调域名的服务器就ok了,然后可以去钉钉开放平台验证,如下图:
到这里,钉钉回调地址设置成功,后台可以根据钉钉服务给到的指令进行不同的逻辑处理