0

помогите пожалуйста что я нет так делаю ?

String[] arg = new String[] { "0051FEAC52DB40394261", "FBD84AE57499E4400414E2831CF98D1E" };

if (arg.length == 0) {
    System.out.println ("ERROR 0x01 ARGS");
    System.in.read();
    return;
}

String hex_str = String.valueOf(arg [0]);
byte[] snDEC = hex_string_to_byte_array (hex_str.substring (0, 4));
byte[] snHEX = Helper.toPrimitives(dec_string_to_byte_array(hex_str.substring(0, 4)));
binary_hex = Helper.toObjects(hex_string_to_byte_array (hex_str.substring (4, hex_str.length()-4)));
byte [] key16 = hex_string_to_byte_array (String.valueOf(arg [1]));

    System.out.println(key16);
// Расшифровываем
TDES_ECB _tdes = new TDES_ECB();
byte[] dec_result = _tdes.TripleDesDecryptOneBlock (Helper.toPrimitives(binary_hex), key16);


//foreach (byte b in dec_result)
//{
//    Console.Write("{0:X2}", b);
//}
//Console.WriteLine();

short sn1 = (short) Integer.parseInt(hex_str.substring (0, 4));//BitConverter.ToInt16 (snDEC);
short sn2 = (short) BitConverter.toInt16 (Helper.toPrimitives(swap_bytes(dec_result)),0);

//Console.WriteLine("SN1: {0:X2}", sn1);
//Console.WriteLine("SN1: {0:X2}", sn2);



// Сверка серийных номеров
    if (String.valueOf(sn1) != String.valueOf(sn2))
{
    System.out.println("ERROR 0x02 SN");
    System.in.read();
    return;
}

// Проверяем контрольную сумму
    if (!compare_crc16(Helper.toObjects(dec_result)))
{
    System.out.println("ERROR 0x03 CRC16");
    System.in.read();
    return;
}

// Получаем дату - тут надо подумать.
Calendar dt = Calendar.getInstance();
    dt.add(Calendar.YEAR, 1);
SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd0000");
//Console.WriteLine ("new date: "+dt.ToString("yy MM dd hh mm"));

int current_time = Integer.parseInt(sdf.format(dt));
    System.out.println("a1:" + current_time);

int current_time2 = Integer.parseInt(sdf.format(dt));
    System.out.println("a2:" + current_time2);


// добавляем серйиник
ArrayList<Byte> l = new ArrayList<> ();
    l.add (snHEX[0]);
    l.add (snHEX[1]);

byte[] time_arr = Helper.toPrimitives(BitConverter.GetBytes (current_time2));
ArrayList<Byte> tmp = new ArrayList<Byte>(Arrays.asList(Helper.toObjects(time_arr)));
    Collections.reverse(tmp);

// добавляем дату
    for (byte b : tmp)
        l.add(b);

// считаем контрольную сумму с новыми данными
ArrayList<Byte> last_pack = calc_crc16 (l.toArray(new Byte[0]));

byte[] en_result = _tdes.TripleDesEncryptOneBlock(Helper.toPrimitives(last_pack.toArray(new Byte[0])), key16);

    System.out.println(hex_str.substring (0, 4));

    for (byte b: en_result)
        System.out.println("{0:X2} " + b);

    System.in.read();
}

private static Byte [] swap_bytes(byte [] bb)
{
    List<Byte> res = new ArrayList<> ();
    res.add (bb [1]);
    res.add (bb [0]);
    return res.toArray(new Byte[0]);
}

private static ArrayList<Byte> calc_crc16(Byte[] byteIn)
{
    int crc = 0x0000;
    crc = calc_cycle(byteIn);
    ArrayList<Byte> l = new ArrayList<Byte>(Arrays.asList(byteIn));

    l.add((byte) (crc >> 8));
    l.add((byte) (crc&255));
    return l;
}

private static Boolean compare_crc16(Byte[] byteIn)
{
    int crc = calc_cycle(byteIn);
    int crc2 = (int) (byteIn [7] | (int)(byteIn [6] << 8));
    return (crc == crc2) ? true : false;
}

private static int calc_cycle(Byte[] byteIn)
{
    int crc = 0xFFFF;

    for (int i=0; i<6; i++)
    {
        byte tmp = byteIn[i];
        tmp ^= (byte)(crc & 0xFF);
        tmp ^= (byte)(tmp << 4);

        crc = (int)((int)(tmp << 8) | ((crc >> 8) & 255));
        crc ^= (byte)(tmp >> 4);
        crc ^= (int)((int)tmp << 3);
    }
    return crc;
}

private static Byte[] dec_string_to_byte_array(String str)
{
    ArrayList<Byte> lb = new ArrayList<Byte>(Arrays.asList(BitConverter.GetBytes(Integer.parseInt(str))));
    Collections.reverse(lb);
    return lb.toArray(new Byte[0]);
}

private static byte[] hex_string_to_byte_array(String str) throws Exception
{
    if (str.length() % 2 == 1)
        throw new Exception("he binary key cannot have an odd number of digits");

    byte[] arr = new byte[str.length() >> 1];

    for (int i=0; i< str.length() >>1; i++)
    {
        arr[i] = (byte)((GetHexVal(str.charAt(i << 1)) << 4) + (GetHexVal(str.charAt((i << 1) + 1))));
    }

    return arr;
}

private static int GetHexVal(char hex) {
    int val = (int)hex;
    return val - (val < 58 ?48 : 55);
}
static class TDES_ECB
{

    private KeyGenerator keyGenerator;

    //Encriptor
    public byte[] TripleDesEncryptOneBlock(byte[] plainText, byte [] key16) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException,
            BadPaddingException, IllegalBlockSizeException

    {


        Security.addProvider(new BouncyCastlePQCProvider());
        final Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key16, "DESede"));

        byte[] encrypted = cipher.doFinal(plainText);

        return encrypted;
    }

    //Decrryptor
    public byte[] TripleDesDecryptOneBlock(byte[] data, byte[]key16) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException,
            IllegalBlockSizeException

    {


        Security.addProvider(new BouncyCastlePQCProvider());
        final Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key16, "DESede"));

        byte[] decrypted = cipher.doFinal(data);

        return decrypted;
    }
}

static class BitConverter
{
    public static Byte[] GetBytes(int value)
    {
        ByteBuffer buffer = ByteBuffer.allocate(4).order(ByteOrder.nativeOrder());
        buffer.putInt(value);
        return Helper.toObjects(buffer.array());
    }

    public static short toInt16(byte[] bytes, int index) //throws Exception
    {
        return (short)((bytes[index + 1] & 0xFF) | ((bytes[index] & 0xFF) << 0));
        //return (short)(
        //        (0xff & bytes[index]) << 8 |
        //                (0xff & bytes[index + 1]) << 0
        //);
    }
}

static class Helper
{
    public static byte[] toPrimitives(Byte[] oBytes)
    {
        byte[] bytes = new byte[oBytes.length];

        for(int i = 0; i < oBytes.length; i++) {
            bytes[i] = oBytes[i];
        }

        return bytes;
    }

    public static Byte[] toObjects(byte[] bytesPrim) {
        Byte[] bytes = new Byte[bytesPrim.length];

        int i = 0;
        for (byte b : bytesPrim) bytes[i++] = b; // Autoboxing

        return bytes;
    }
}

Получаю

Exception in thread "main" java.security.InvalidKeyException: Wrong key size
at com.sun.crypto.provider.DESedeCrypt.init(DESedeCrypt.java:69)
at com.sun.crypto.provider.ElectronicCodeBook.init(ElectronicCodeBook.java:94)
at com.sun.crypto.provider.CipherCore.init(CipherCore.java:591)
at com.sun.crypto.provider.CipherCore.init(CipherCore.java:467)
at com.sun.crypto.provider.DESedeCipher.engineInit(DESedeCipher.java:166)
at javax.crypto.Cipher.implInit(Cipher.java:801)
at javax.crypto.Cipher.chooseProvider(Cipher.java:863)
at javax.crypto.Cipher.init(Cipher.java:1248)
at javax.crypto.Cipher.init(Cipher.java:1185)
at MainClass$TDES_ECB.TripleDesDecryptOneBlock(MainClass.java:246)
at MainClass.main(MainClass.java:75)
4
  • Оставьте только самую важную часть кода.
    – Zergatul
    16 дек 2019 в 10:36
  • Проблема в том что я точно не могу сказать почему у меня ключ не правильной длины, поскольку я новичок в программирование, я выложил весь код чтоб было понятней. 16 дек 2019 в 10:40
  • Нужно больше информации, как шифруете, что шифруете (какой текст), чем шифруете. В этом темном лесу никто не хочет терять время, чтобы разобраться, что у вас там происходит! Либо вопрос стоит закрыть - так как отладкой кода тут не занимаются.
    – And
    16 дек 2019 в 11:13

1 ответ 1

3

Длина материала ключа (в вашем случае key16) - должна быть 192 бит, то есть 24 байта.

P.S. Научитесь в конце-концов читать диагностику сообщений:

java.security.InvalidKeyException: Wrong key size

Неверная длина ключа...

Update

Я обычно не занимаюсь рефлексированием, почему именно 192 бита, а не 112 или 168. Оставляю это на усмотрение узких специалистов:

So sometimes the (triple) DES key lengths are referred to as 56 bit, 112 bit or 168 bits instead of 64, 128 or 192 bits respectively. Usually cryptographic API's still require you to enter 8, 16 or 24 bytes despite of this.

Полагаюсь на рабочую длину и все. Работает и ладно.

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.