Java DES шифруется, C # DES расшифровывается - PullRequest
0 голосов
/ 10 ноября 2018

Я получил зашифрованную строку с Java и вижу зашифрованный исходный код Java. Я написал код расшифровки в C #. Но всегда сообщайте об ошибке в «FlushFinalBlock». Сообщение об ошибке: «System.Security.Cryptography.CryptographicException. Дополнительная информация: неверные данные.»

Может ли кто-нибудь указать, где проблема в моем коде C #?

это код Java:

private static byte[] coderByDES(byte[] plainText, String key, int mode)
            throws InvalidKeyException, InvalidKeySpecException,
            NoSuchAlgorithmException, NoSuchPaddingException,
            BadPaddingException, IllegalBlockSizeException,
            UnsupportedEncodingException {
        SecureRandom sr = new SecureRandom();
        byte[] resultKey = makeKey(key);
        DESKeySpec desSpec = new DESKeySpec(resultKey);
        SecretKey secretKey = SecretKeyFactory.getInstance("DES").generateSecret(desSpec);
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(mode, secretKey, sr);
        return cipher.doFinal(plainText);
    }

private static byte[] makeKey(String key)
            throws UnsupportedEncodingException {
        byte[] keyByte = new byte[8];
        byte[] keyResult = key.getBytes("UTF-8");
        for (int i = 0; i < keyResult.length && i < keyByte.length; i++) {
            keyByte[i] = keyResult[i];
        }
        return keyByte;
    }


private static String byteArr2HexStr(byte[] arrB) {
        int iLen = arrB.length;

        StringBuilder sb = new StringBuilder(iLen * 2);
        for (int i = 0; i < iLen; i++) {
            int intTmp = arrB[i];

            while (intTmp < 0) {
                intTmp = intTmp + 256;
            }

            if (intTmp < 16) {
                sb.append("0");
            }
            sb.append(Integer.toString(intTmp, 16));
        }
        return sb.toString();
    }

это код C #:

public static string DecryptForDES(string input, string key)
    {
        byte[] inputByteArray = HexStr2ByteArr(input);
        byte[] buffArray = null;
        using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
        {
            des.Key =  Encoding.UTF8.GetBytes(key); 
            des.IV =  Encoding.UTF8.GetBytes(key); 
            des.Mode = System.Security.Cryptography.CipherMode.ECB;
            des.Padding = PaddingMode.PKCS7;
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
            {
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();//
                cs.Close();
            }
            buffArray = ms.ToArray();

            ms.Close();    
        }

        string str = string.Empty;
        if (buffArray != null)
        {
            str = Encoding.UTF8.GetString(buffArray);
        }
        return str;
    }



public static byte[] HexStr2ByteArr(string strIn)
    {
        byte[] arrB = Encoding.UTF8.GetBytes(strIn);
        int iLen = arrB.Length;

        byte[] arrOut = new byte[iLen / 2];
        byte[] arrTmp = new byte[2];
        for (int i = 0; i < iLen; i = i + 2)
        {
            string strTmp = Encoding.UTF8.GetString(arrB, i, 2);
            arrOut[i / 2] = (byte)Convert.ToInt32(strTmp, 16);
        }
        return arrOut;
    }

1 Ответ

0 голосов
/ 11 ноября 2018

Как часть шифрования Java, так и часть расшифровки C # работают на моем компьютере, если пароли совпадают. В противном случае выдается System.Security.Cryptography.CryptographicException: « Bad Data». Для получения совпадения пароля замените в методе C # DecryptForDES

 des.Key = Encoding.UTF8.GetBytes(key); 

с

 des.Key = MakeKey(key);

с C # -методом:

 private static byte[] MakeKey(String key)
 {
     byte[] keyByte = new byte[8];
     byte[] keyResult = Encoding.UTF8.GetBytes(key); 
     for (int i = 0; i<keyResult.Length && i<keyByte.Length; i++) {
         keyByte[i] = keyResult[i];
     }
     return keyByte;
 }

соответствует Java-методу makeKey (ключ String). Более того, удалите в C # -метод DecryptForDES

 des.IV = Encoding.UTF8.GetBytes(key);

, поскольку в режиме ECB не используется IV.

В следующем тесте

 coderByDES("This is a plain text that needs to be encrypted...", "This is the key used for encryption...", Cipher.ENCRYPT_MODE);

возвращает байтовый массив

 a47b1b2c90fb3b7a0ab1f51f328ff55aae3c1eb7789c31c28346696a8b1f27c7413c14e68fe977d3235b5a6f63c07d7a95d912ff22f17ad6

и

 DecryptForDES("a47b1b2c90fb3b7a0ab1f51f328ff55aae3c1eb7789c31c28346696a8b1f27c7413c14e68fe977d3235b5a6f63c07d7a95d912ff22f17ad6", "This is the key used for encryption...");                

возвращает правильный простой текст.

Кстати: как уже говорилось в Flydog57, DES небезопасен (https://en.wikipedia.org/wiki/Data_Encryption_Standard)., а также режим ECB небезопасен (https://crypto.stackexchange.com/questions/20941/why-shouldnt-i-use-ecb-encryption). Лучше выбрать AES (https://en.wikipedia.org/wiki/Advanced_Encryption_Standard) в режиме CBC или GCM (https://crypto.stackexchange.com/questions/2310/what-is-the-difference-between-cbc-and-gcm-mode).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...