以此记录,以备不时之需;

项目中需要跟java对接数据,java那边使用的是des加密方式。所以需要在C#代码中对应实现出来,直接上码:

/// <summary>
        /// DES加密(对应java版)
        /// </summary>
        /// <param name="encryptString"></param>
        /// <param name="sKey"></param>
        /// <returns></returns>
        public static string DesEncrypt(string encryptString, string sKey)
        {

            byte[] keyBytes = Encoding.UTF8.GetBytes(sKey.Substring(0, 8));//只需要前8位即可
            byte[] keyIV = keyBytes;
            byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);

            DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider();

            // java 默认的是ECB模式,PKCS5padding;c#默认的CBC模式,PKCS7padding 所以这里我们默认使用ECB方式
            desProvider.Mode = CipherMode.ECB;
            MemoryStream memStream = new MemoryStream();
            CryptoStream crypStream = new CryptoStream(memStream, desProvider.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write);

            crypStream.Write(inputByteArray, 0, inputByteArray.Length);
            crypStream.FlushFinalBlock();
            return Convert.ToBase64String(memStream.ToArray());
        }

        /// <summary>
        /// DES解密方法
        /// </summary>
        /// <param name="decryptString"></param>
        /// <param name="sKey"></param>
        /// <returns></returns>
       public static string DesDencrypt(string decryptString, string sKey)
        {
            byte[] keyBytes = Encoding.UTF8.GetBytes(sKey.Substring(0, 8));
            byte[] keyIV = keyBytes;
            byte[] inputByteArray = Convert.FromBase64String(decryptString);
  
            DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider();
  
            // java 默认的是ECB模式,PKCS5padding;c#默认的CBC模式,PKCS7padding 所以这里我们默认使用ECB方式
            desProvider.Mode = CipherMode.ECB;
            MemoryStream memStream = new MemoryStream();
            CryptoStream crypStream = new CryptoStream(memStream, desProvider.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write);
  
            crypStream.Write(inputByteArray, 0, inputByteArray.Length);
            crypStream.FlushFinalBlock();
            return Encoding.Default.GetString(memStream.ToArray());
  
        }

C#实现java的des加密解密算法。_c#