Алгоритм TripleDES в C # - PullRequest
       27

Алгоритм TripleDES в C #

0 голосов
/ 18 апреля 2019

В настоящее время я работаю над шифрованием TripleDES в C #, для которого я получил пример кода от JAVA.

Я создал функцию шифрования в C # с приведенным ниже примером кода:

Входные данные: ключ / ekay = "15ce89cd1a2a838f4f6d49d60438251915ce89cd1a2a838f"

text / data = "00000000000000

public static string encryptionMethod(string Text, string key)
{
          string encryptedText = string.Empty;
          try
            {                
                MD5CryptoServiceProvider md5Hash = new MD5CryptoServiceProvider();                          
                byte[] md5Bytes = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(key));
                md5Hash.Clear();
                byte[] clearBytes = Encoding.UTF8.GetBytes(Text);  
                TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();  
                des.KeySize = 128;                          
                des.Mode = CipherMode.CBC;    
                des.Padding = PaddingMode.None;  
                des.Key = md5Bytes;   //Passing key in byte array
                //des.BlockSize = 64;
                byte[] ivBytes = new byte[8] {0, 0, 0, 0, 0, 0, 0, 0 };
                des.IV = ivBytes;                      
                ICryptoTransform ct = des.CreateEncryptor();   //Interface with some result
                byte[] resultArray = ct.TransformFinalBlock(clearBytes, 0, clearBytes.Length);               
                encryptedText = ByteArrayToHexString(resultArray);                               
            }
            catch (Exception exception)
            {
                return "";
            }
        return encryptedText;

}

public static string ByteArrayToHexString(byte[] ba)
        {
            StringBuilder hex = new StringBuilder(ba.Length * 2);
            foreach (byte b in ba)
                hex.AppendFormat("{0:x2}", b);
            return hex.ToString();
        }

но после сравнения вывода C # с выводом JAVA я получил другие результаты.

Код JAVA


public  static String encrypt(String data, String ekey) {
        String encrypteddata = null;
   try{            
        String key = ekey;
        byte[] encryptKey = ISOUtil.hex2byte(key);        
        DESedeKeySpec spec = new DESedeKeySpec(encryptKey);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
        SecretKey theKey = keyFactory.generateSecret(spec);        
        Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding");       
        IvParameterSpec IvParameters = new IvParameterSpec( new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });        
        cipher.init(Cipher.ENCRYPT_MODE, theKey, IvParameters);  
        String plain = data;       
        byte[] plaintext = ISOUtil.hex2byte(plain);
        byte[] encrypted = cipher.doFinal(plaintext);        
         encrypteddata= ISOUtil.byte2hex(encrypted);             
    }
    catch(Exception e){        
    }
        return encrypteddata;      
    }   

вывод:

C #: eca27a1e639900f3298a5090cc34dd29

JAVA: c0a946402dd20f5e


Любая помощь будет оценена?

Спасибо.

1 Ответ

0 голосов
/ 21 апреля 2019

Вот модифицированный код, который решил мою проблему.

 public static string encryptionMethod(string Text, string key)
        {
            string encryptedText = string.Empty;
            try
            {
                byte[] clearBytes = StringToByteArray(Text); ;//Encoding.UTF8.GetBytes(Text);
                TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
                des.KeySize = 128;
                des.Mode = CipherMode.CBC;
                des.Padding = PaddingMode.None;
                des.Key = StringToByteArray(key);   //Passing key in byte array
                //des.BlockSize = 64;
                byte[] ivBytes = new byte[8] { 0, 0, 0, 0, 0, 0, 0, 0 };
                des.IV = ivBytes;
                ICryptoTransform ct = des.CreateEncryptor();   //Interface with some result
                byte[] resultArray = ct.TransformFinalBlock(clearBytes, 0, clearBytes.Length);
                encryptedText = ByteArrayToHexString(resultArray);
            }
            catch (Exception exception)
            {
                return "";
            }
            return encryptedText;

        }


  public static byte[] StringToByteArray(string hex)
        {
            return Enumerable.Range(0, hex.Length)
                             .Where(x => x % 2 == 0)
                             .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                             .ToArray();
        }

...