DES加密方法在PHP和.NET平台间的无缝连接

作者:caocao(网络隐士),[url]http://www.caocao.name/[/url],[url]http://www.caocao.mobi/[/url]
转载请注明来源:[url]http://www.iteye.com/topic/178321[/url]

有个项目要跨PHP平台和.NET平台进行数据交换,数据还必须是DES加密的,在折腾了一阵后隐士终于摸清楚代码该如何写,加密数据才能够通用于两个平台。

[quote="PHP加密方式"][code]
$key="********";
$iv="********";
$message="kjsdfuihyweflgjerogjreg";
echo base64_encode(mcrypt_encrypt(MCRYPT_DES, $key, $message, MCRYPT_MODE_CBC, $iv));
[/code][/quote]

[quote="C#加密解密方式"]
[code]
///
/// DES加密方法,keyBytes和ivBytes必须为64bit即8位的
///

/// 待加密数组
/// key数组
/// iv数组
/// 加密完的数组
public static byte[] DESEncryptWithCBCZeros(byte[] inBytes, byte[] keyBytes, byte[] ivBytes)
{
using (MemoryStream memoryStream = new MemoryStream())
{
DES desCBC = DES.Create();
desCBC.Mode = CipherMode.CBC;
desCBC.Padding = PaddingMode.Zeros;
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, desCBC.CreateEncryptor(keyBytes, ivBytes), CryptoStreamMode.Write))
{
cryptoStream.Write(inBytes, 0, inBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] bytes = memoryStream.ToArray();
return bytes;
}
}
}

///
/// DES解密方法,keyBytes和ivBytes必须为64bit即8位的
///

/// 待解密数组
/// key数组
/// iv数组
/// 解密完的数组
public static byte[] DESDecryptWithCBCZeros(byte[] inBytes, byte[] keyBytes, byte[] ivBytes)
{
using (MemoryStream memoryStream = new MemoryStream(inBytes))
{
DES desCBC = DES.Create();
desCBC.Mode = CipherMode.CBC;
desCBC.Padding = PaddingMode.Zeros;
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, desCBC.CreateDecryptor(keyBytes, ivBytes), CryptoStreamMode.Read))
{
byte[] outEncrypt = new byte[inBytes.Length];
cryptoStream.Read(outEncrypt, 0, outEncrypt.Length);
return outEncrypt;
}
}
}
[/code]
[/quote]

[quote="C#调用方式"]
[code]
try
{
byte[] inBytes = Encoding.UTF8.GetBytes("kldfgwehfo23905hfkjvbsdcsdc");
byte[] keyBytes = Encoding.ASCII.GetBytes("********");
byte[] ivBytes = Encoding.ASCII.GetBytes("********");
byte[] outBytes = StringEncryptHelper.DESEncryptWithCBCZeros(inBytes, keyBytes, ivBytes);
Console.WriteLine(Convert.ToBase64String(outBytes));

Console.WriteLine(Encoding.UTF8.GetString(StringEncryptHelper.DESDecryptWithCBCZeros(outBytes, keyBytes, ivBytes)));
}
catch (CryptographicException e)
{
Console.WriteLine(e.StackTrace);
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
}
[/code]
[/quote]

你可能感兴趣的:(.NET)