Pergunta

I'm trying to write a simple program to encrypt and decrypt files using the AES algortihm. I haven't problems with encryption, but decryption..

public static void main(String[] args) throws NoSuchAlgorithmException, FileNotFoundException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {

    // Инициализация секретных ключей
    KeyGenerator keyGenS = KeyGenerator.getInstance("AES");
    keyGenS.init(128);
    SecretKey sKey1 = keyGenS.generateKey();
    SecretKey sKey2 = keyGenS.generateKey();
    // Перевод секретных ключей в строку и запись в файл
    String key1 = SecretKeyToString(sKey1);
    String key2 = SecretKeyToString(sKey2);

    spreader.write(fileName1, key1);
    spreader.write(fileName2, key2);
    spreader.write(fileNameS1, key1);
    spreader.write(fileNameS2, key2);


    // Чтение секретных ключей из файла и перевод обратно в тип SecretKey
    key1 = spreader.read(fileName1);
    System.out.println("Секретный ключ 1го пользователя: " +key1);


    SecretKey seansKey1=getKeyInstance(key1);

    key2 = spreader.read(fileName2);
    System.out.println("Секретный ключ 2го пользователя: " +key2);

    SecretKey seansKey2=getKeyInstance(key2);


    //инициализация и зашифрование сеансового ключа с помощью секретных
    Cipher aesCipher = Cipher.getInstance("AES");
    aesCipher.init(Cipher.ENCRYPT_MODE,seansKey1);

    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(128);
    SecretKey secretKey = keyGen.generateKey();

    String stringsecretKey = SecretKeyToString(secretKey);
    byte[] byteKey = stringsecretKey.getBytes();
    byte[] byteCipherKey1 = aesCipher.doFinal(byteKey); 
    String encryptedKey = new BASE64Encoder().encode(byteCipherKey1);
    System.out.println("Зашифрованный сеансовый ключ с помощью секретного ключа 1: " +encryptedKey);





    aesCipher = Cipher.getInstance("AES");
    aesCipher.init(Cipher.ENCRYPT_MODE,SeansKey2);


     byteKey = etringsecretKey.getBytes();
     byte[] byteCipherKey2 = aesCipher.doFinal(byteKey); 
     encryptedKey = new BASE64Encoder().encode(byteCipherKey2);
    System.out.println("Зашифрованный сеансовый ключ с помощью секретного ключа 2: " +encryptedKey);
    spreader.write(fileNameEK2, encryptedKey);

    //Чтение данных из файла
    String text =spreader.read(fileName);
    System.out.println(text);

    // Зашифрование данных


            aesCipher.init(Cipher.ENCRYPT_MODE,secretKey); // константная переменная

            byte[] byteText = text.getBytes();
            byte[] byteCipherText = aesCipher.doFinal(byteText); 
            encryptedText = new BASE64Encoder().encode(byteCipherText);
            System.out.println("Зашифрованный текст: " +encryptedText);

            spreader.write(fileNameOK, encryptedText);





}

Here's the decryption part:

public static void main(String[] args) throws NoSuchAlgorithmException, FileNotFoundException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, UnsupportedEncodingException {

    String encryptedText = user.read(fileNameOK);
    String key1 = user.read(fileName1);
    String key2 = user.read(fileName2);
    String encryptedSeanceKey1 = user.read(fileNameEK1);
    String encryptedSeanceKey2 = user.read(fileNameEK2);




    SecretKey secretKey1=getKeyInstance(key1);
    SecretKey secretKey2=getKeyInstance(key2);



    Cipher aesCipher = Cipher.getInstance("AES");
    aesCipher.init(Cipher.DECRYPT_MODE,secretKey1,aesCipher.getParameters());




    //byte[] byteKey = encryptedSeanceKey1.getBytes();

       byte[] byteDecryptedKey = aesCipher.doFinal(encryptedSeanceKey1.getBytes());
       String decryptedKey1 = new String(byteDecryptedKey);
       System.out.println("Расшифрованный сеансовый ключ с помощью секретного ключа 1: " +decryptedKey1);

    aesCipher.init(Cipher.DECRYPT_MODE,secretKey2,aesCipher.getParameters());




    byte[] byteKey2 = encryptedSeanceKey2.getBytes();
        byteDecryptedKey = aesCipher.doFinal(byteKey2); 
        String decryptedKey2 = new String(byteDecryptedKey);
       System.out.println("Расшифрованный сеансовый ключ с помощью секретного ключа 2: " +decryptedKey2);





        // Расшифрование данных
        aesCipher.init(Cipher.DECRYPT_MODE,getKeyInstance(decryptedKey1),aesCipher.getParameters());

         byte[] byteText = encryptedText.getBytes();

        byte[] byteDecryptedText = aesCipher.doFinal(byteText);
        decryptedText = new String(byteDecryptedText);
        System.out.println(" Расшифрованный текст " +decryptedText);



}

}

Now the problem is the decryption part is: Input length must be multiple of 16 when decrypting with padded cipher

I know that a mistake that I incorrectly keep a session key and bytes are lost. But how I can correctly do it?

Foi útil?

Solução

There is a little bit of confusion in your code, maybe because some method you called are missing, or maybe because you are using your keys to encrypt...your keys(!!!)
Let's try to encrypt and decrypt the easy way, removing all the stuff that is not strictly needed in your code (like encode your key and save it to a file, and then restore the key without decoding it, etc..).

Let's take a look at the following simplified code based on your:

    KeyGenerator keyGenS = KeyGenerator.getInstance("AES");
    keyGenS.init(128);
    SecretKey sKey1 = keyGenS.generateKey();

    Cipher aesCipher = Cipher.getInstance("AES");
    aesCipher.init(Cipher.ENCRYPT_MODE,sKey1);

    byte[] byteText = "Insert here whatever you want to crypt".getBytes();

    byte[] byteCipherText = aesCipher.doFinal(byteText);

We have generated our key with KeyGenerator, and then we have initialized our Cipher instance with that key. At this point we simply call doFinal() passing the plainText we want to encrypt.
That's all for the encryption part. Of course you can save your keys and byteCipherText to a file if you want, but all the other staff is (at least) useless.

The decryption part is easy as the encryption. The logic is the same. If you saved your key on a file, just read it into a byte[], and use it for initialize your cipher instance. Something like this:

    aesCipher.init(Cipher.DECRYPT_MODE, sKey1);
    byte[] plainText = aesCipher.doFinal(byteCipherText);

If you put all the above code into a main() and run it, you should have into plainText the same text as in byteText.
You can verify it with a

    System.out.println(new String(plainText));

Try to start from here, then add all other things you may need.
Hope this helps.
Regards

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top