我正在尝试将一些数据从Unity发送到Node.js express服务器,反之亦然。
这是我在C#中的Unity代码:
public string Encrypt(string toEncrypt, string key, bool useHashing)
{
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
if (useHashing){
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
}
else {
keyArray = UTF8Encoding.UTF8.GetBytes(key);
}
var tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
//tdes.Mode = CipherMode.CBC; // which is default
//tdes.Padding = PaddingMode.PKCS7; // which is default
ICryptoTransform cTransform = tdes.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
Dictionary<string, string> data = new Dictionary<string, string>();
data.Add("Test01", "Tanmoy");
data.Add("Test02", "Mitra");
string json = Json.Serialize(data);
byte[] postData = Encoding.UTF8.GetBytes(Encrypt(json, "12345", true));
StartCoroutine(HttpPost("test", postData, delegate(string requestError, IDictionary rData) {
cb(null,rData);
}));
这是我的Node.js代码:
var alg = 'des-ede3-cbc';
var key = new Buffer('123456789012345678901234', 'utf-8');
var iv = new Buffer(m_strApiPass, 'base64');
var encrypted = new Buffer(reqString, 'base64');
var decipher = crypto.createDecipheriv(alg, key, iv);
var decoded = decipher.update(encrypted, 'binary', 'ascii');
decoded += decipher.final('ascii');
我收到此错误:
TypeError:错误:0606506D:数字包络例程:EVP_DecryptFinal_ex:错误的最终块长度
我注意到,在C#中,我得到了以下字符串,
pySqIdAiJpDOW7XkOQDoblLOtZ382J1G1F1UE16W0Ulg+x5X0Bocjg==
但是当我将此字符串发送到Node.js时,它变为:
pySqIdAiJpDOW7XkOQDoblLOtZ382J1G1F1UE16W0Ulg x5X0Bocjg
问题是什么?
答案 0 :(得分:1)
原因很简单:返回的密文由任意观察者的随机字节组成。这意味着其中有些字节不映射到字符。这些字节中的信息将丢失。
如果在传输过程中需要字符串,则base 64会对您的密文进行编码,然后在接收方再次对其进行解码。