JAVA DES加密(DES/ECB/PKCS5Padding)和C#加密对应设置

  最近在项目中需要做java中DES加密和C#DES的对应设置,java代码如下所示:

  

public static String encryptDES(String paramString1, String paramString2)
      throws Exception
    {
      
      SecretKeySpec localSecretKeySpec = new SecretKeySpec(paramString2.getBytes(), "DES");
      Cipher localCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
      localCipher.init(1, localSecretKeySpec);
      return Base64.encode(localCipher.doFinal(paramString1.getBytes()));
    }

 

  网上搜到的C#对应都是如下所示:

  

 public static string Encrypt(string pToEncrypt, string sKey)
        {
            using (DESCryptoServiceProvider des =
            new DESCryptoServiceProvider())
            {
               
                byte[] inputByteArray = Encoding.UTF8.GetBytes(pToEncrypt);
                
                des.Key = Encoding.UTF8.GetBytes(sKey);
                des.IV = Encoding.UTF8.GetBytes(sKey);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                using (CryptoStream cs = new CryptoStream(ms,
                des.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }
              
                string base64 = Convert.ToBase64String(ms.ToArray());
                ms.Close();
                return base64 ;
            }
        }

  折腾了大半天,修改编码格式,研究了下C#Encoding.UTF8.GetBytes()和java 的getBytes()差别,加密的值都对不上;

  好好看了下java的代码相关,注意到下面这句代码:

  Cipher.getInstance("DES/ECB/PKCS5Padding");

  搜索相关,java的PKCS5Padding 对应C#的des.Padding = PaddingMode.PKCS7;但是结果还是对应不上。

  一直没注意到ECB 还需要设置C#的des.Mode = CipherMode.ECB;

  被这种小问题折腾半天,记录一下;

posted @ 2014-07-21 16:20  半边书生9527  阅读(9966)  评论(4编辑  收藏  举报