JAVA和C# 3DES加密解密 以及Md5驗籤

一、java  3DES加密與解密方法

1、加密

public static final String encode(String input, String sKey)
{
    byte[] key = sKey.getBytes();
    try{
    SecretKey deskey = new SecretKeySpec(key, "DESede");
          Cipher c1 = Cipher.getInstance("DESede");
        c1.init(1, deskey);

        byte[] cipherByte = c1.doFinal(input.getBytes());
        return Base64.getEncoder().encodeToString(cipherByte);
    }catch(Exception e)
    {
        return null;
    }
}

2、解密

public static final String decode(String input, String sKey)
{
    byte[] key = sKey.getBytes();
    SecretKey deskey = new SecretKeySpec(key, "DESede");
    try {
        Cipher c1 = Cipher.getInstance("DESede");
        c1.init(2, deskey);
        byte[] clearByte = c1.doFinal(Base64.getDecoder().decode(input));
        return new String(clearByte);
    }
    catch (Exception  e) {
        e.printStackTrace();
    }
    return null;
}

二、對應的.net 3DES加密與解密方法

1、加密

  /// <summary>
        /// DES3加密方法
        /// </summary>
        /// <param name="pToEncrypt">加密明文</param>
        /// <param name="sKey">加密密鑰</param>
        /// <param name="encoding">明文轉byte 時的編碼方式 </param>
        /// <returns></returns>
        public static string Des3EncodeECB(string pToEncrypt, string sKey, Encoding encoding)

        {

            try

            {
                // Create a MemoryStream.  
                MemoryStream mStream = new MemoryStream();
                TripleDESCryptoServiceProvider tdsp = new TripleDESCryptoServiceProvider();
                tdsp.Mode = CipherMode.ECB;
                tdsp.Padding = PaddingMode.PKCS7;
                // Create a CryptoStream using the MemoryStream   
                // and the passed key and initialization vector (IV). 
                byte[] key = ASCIIEncoding.ASCII.GetBytes(sKey);
                byte[] iv = ASCIIEncoding.ASCII.GetBytes(sKey);
                CryptoStream cStream = new CryptoStream(mStream,
                tdsp.CreateEncryptor(key, iv),
                CryptoStreamMode.Write);
                // Write the byte array to the crypto stream and flush it. 
                byte[] data = encoding.GetBytes(pToEncrypt);
                cStream.Write(data, 0, data.Length);
                cStream.FlushFinalBlock();
                // Get an array of bytes from the   
                // MemoryStream that holds the   
                // encrypted data.  
                byte[] ret = mStream.ToArray();
                // Close the streams.  
                cStream.Close();
                mStream.Close();
                // Return the encrypted buffer.  
                return Convert.ToBase64String(ret.ToArray());
            }
            catch (CryptographicException e)
            {
                Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
                return null;
            }

        } 

2、解密

   /// <summary>
        /// DES3解密方法
        /// </summary>
        /// <param name="sKey">密鑰</param>
        /// <param name="pToDecode">密文</param>
        /// <param name="encoding">byte 轉爲 string 時的編碼格式</param>
        /// <returns></returns>
        public static string Des3DecodeECB(string sKey, string pToDecode, Encoding encoding)
        {
            try
            {
                // Create a new MemoryStream using the passed   
                // array of encrypted data.
                byte[] data = Convert.FromBase64String(pToDecode);
                MemoryStream msDecrypt = new MemoryStream(data);
                TripleDESCryptoServiceProvider tdsp = new TripleDESCryptoServiceProvider();
                tdsp.Mode = CipherMode.ECB;
                tdsp.Padding = PaddingMode.PKCS7;
                // Create a CryptoStream using the MemoryStream   
                // and the passed key and initialization vector (IV).  
                byte[] key = ASCIIEncoding.ASCII.GetBytes(sKey);
                byte[] iv = ASCIIEncoding.ASCII.GetBytes(sKey);
                CryptoStream csDecrypt = new CryptoStream(msDecrypt, tdsp.CreateDecryptor(key, iv), CryptoStreamMode.Read);
                // Create buffer to hold the decrypted data.  
                byte[] fromEncrypt = new byte[data.Length];
                // Read the decrypted data out of the crypto stream  
                // and place it into the temporary buffer.  
                csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
                //Convert the buffer into a string and return it.  
                string result = encoding.GetString(fromEncrypt);
                return result;
            }
            catch (CryptographicException e)
            {
                Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
                return null;
            }

        }

三、java Md5簽名

public static String getMD5String(String s) {
    byte[] bytes=s.getBytes();
    messagedigest.update(bytes);
    messagedigest.digest();
   int m=0;
   int n=bytes.length;
    StringBuffer stringbuffer = new StringBuffer(2 * n);
    int k = m + n;
    for (int l = m; l < k; ++l) { 
        char c0 = hexDigits[((bytes[l] & 0xF0) >> 4)];
        char c1 = hexDigits[(bytes[l] & 0xF)];
        stringbuffer.append(c0);
        stringbuffer.append(c1);
    }
    return stringbuffer.toString();
}

四、對應 .net Md5簽名

    public static string MD5Small(string strValue, Encoding encoding)
        {
            string md5Str = "0123456789abcdef";
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] buffer = md5.ComputeHash(encoding.GetBytes(strValue));
            StringBuilder strMD5Value =new StringBuilder();
            for (int i = 0; i < buffer.Length; i++)
            {
                int a = 0xf & buffer[i] >> 4;
                int b = buffer[i] & 0xf;
                strMD5Value.Append( md5Str.Substring(0xf & buffer[i] >> 4, 1) + md5Str[buffer[i] & 0xf]);
            }


            return strMD5Value.ToString();

        } 


參考網址:

https://www.cnblogs.com/liluping860122/p/4026015.html

https://blog.csdn.net/handerhuo/article/details/68941813

http://www.jb51.net/article/44617.htm


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章