PHP版:
$key = 335ff‘;
/*
* 加密方法
* @param string $input,待加密的字符串
* @param string $key,加密的密码(只能为8位长)
* @return string,加密之后的文本
* */
public static function encryptForDotNet($input, $key) {
$iv = $key;
$addnum = 8 - ( strlen($input) % 8 );
for ($i = 0; $i < $addnum; $i++) {
$input .= chr($addnum);
}
$output = mcrypt_encrypt(MCRYPT_DES, $key, $input, MCRYPT_MODE_CBC, $iv);
return base64_encode($output);
}
/*
* 解密方法
* @param string $input,待解密的字符串
* @param string $key,解密的密码(只能为8位长)
* @return string,解密之后的文本
* */
public static function decryptForDotNet($input, $key) {
$iv = $key;
$output = base64_decode($input);
$output = mcrypt_decrypt(MCRYPT_DES, $key, $output, MCRYPT_MODE_CBC, $iv);
for ($i = 0; $i <= 8; $i++) {
$output = str_replace(chr($i), "", $output);
}
return $output;
}
C#版:
password = ‘isso_key‘;
/// <summary>
/// 加密方法
/// </summary>
/// <param name="input">待加密的字符串</param>
/// <param name="password">加密的密码(只能为8位长)</param>
/// <param name="encoding">编码方式</param>
/// <returns>加密之后的文本</returns>
public static string Encrypt(string input, string password, Encoding encoding = null)
{
encoding = encoding ?? Encoding.Default;
//注意iv的长度,必须和key中的密码长度相同
var iv = encoding.GetBytes(password);
var key = encoding.GetBytes(password);
var datas = encoding.GetBytes(input);
var desCryptoServiceProvider = new DESCryptoServiceProvider();
using (var memoryStream = new MemoryStream())
{
using (
var cryptoStream = new CryptoStream(memoryStream, desCryptoServiceProvider.CreateEncryptor(iv, key),
CryptoStreamMode.Write))
{
cryptoStream.Write(datas, 0, datas.Length);
cryptoStream.FlushFinalBlock();
return Convert.ToBase64String(memoryStream.ToArray());
}
}
}
/// <summary>
/// 解密方法
/// </summary>
/// <param name="input">待解密的字符串</param>
/// <param name="password">加密时用的密码(只能为8位长)</param>
/// <param name="encoding">编码方式</param>
/// <returns>解密之后的文本</returns>
public static string Decrypt(string input, string password, Encoding encoding = null)
{
encoding = encoding ?? Encoding.Default;
var iv = encoding.GetBytes(password);
var key = encoding.GetBytes(password);
var datas = Convert.FromBase64String(input);
var desCryptoServiceProvider = new DESCryptoServiceProvider();
using (var memoryStream = new MemoryStream())
{
using (
var cryptoStream = new CryptoStream(memoryStream, desCryptoServiceProvider.CreateDecryptor(iv, key),
CryptoStreamMode.Write))
{
cryptoStream.Write(datas, 0, datas.Length);
cryptoStream.FlushFinalBlock();
return encoding.GetString(memoryStream.ToArray());
}
}
}