公司在做移动端iOS/Android,服务器提供接口使用的.net,用到加密解密这一块,也在网上找了一些方法,有些是.net加密了Android解密不了,或者反之。下面的是三个平台都可以加密解密的方法。加密解密中用到的key="1234578";在调取方法时传值即可。
C#代码
#region 跨平台加解密(c#)
/// <summary>
/// 对字符串进行DES加密
/// </summary>
/// <param>待加密的字符串</param>
/// <returns>加密后的BASE64编码的字符串</returns>
public string Encrypt(string sourceString, string sKey)
{
byte[] btKey = Encoding.UTF8.GetBytes(sKey);
byte[] btIV = Encoding.UTF8.GetBytes(sKey);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
using (MemoryStream ms = new MemoryStream())
{
byte[] inData = Encoding.UTF8.GetBytes(sourceString);
try
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write))
{
cs.Write(inData, 0, inData.Length);
cs.FlushFinalBlock();
}
return Convert.ToBase64String(ms.ToArray());
}
catch
{
throw;
}
}
}
/// <summary>
/// 解密
/// </summary>
/// <param>要解密的以Base64</param>
/// <param>密钥,且必须为8位</param>
/// <returns>已解密的字符串</returns>
public string Decrypt(string pToDecrypt, string sKey)
{
//转义特殊字符
pToDecrypt = pToDecrypt.Replace("-", "+");
pToDecrypt = pToDecrypt.Replace("_", "/");
pToDecrypt = pToDecrypt.Replace("~", "=");
byte[] inputByteArray = Convert.FromBase64String(pToDecrypt);
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
{
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
cs.Close();
}
string str = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return str;
}
}
#endregion
IOS代码