ITeye博客

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

caocao · 2008-04-01 11:07 · .NET · Markdown

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

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

PHP加密方式 writes:

[code] $key=""; $iv=""; $message="kjsdfuihyweflgjerogjreg"; echo base64_encode(mcrypt_encrypt(MCRYPT_DES, $key, $message, MCRYPT_MODE_CBC, $iv)); [/code]

C#加密解密方式 writes:

[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; } } }

    /// <summary>
    /// DES解密方法,keyBytes和ivBytes必须为64bit即8位的
    /// </summary>
    /// <param name="inBytes">待解密数组</param>
    /// <param name="keyBytes">key数组</param>
    /// <param name="ivBytes">iv数组</param>
    /// <returns>解密完的数组</returns>
    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]

C#调用方式 writes:

[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]

评论(1)

  1. #1 楼 · suntongo · 2009-02-28 05:38

    直接用SSL,.net和java都完美支持,加密/解密过程完全透明,而且安全性最高。

评论功能维护中,当前仅展示历史评论。