php和.net 的加密解密

老皆知發表於2015-05-22

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());
}
}
}

相關文章