-1

I am using below code to implement Triple DES encoding with ECB and PKSC5 Padding.The secret key which i am using is stored in a file named key in raw folder.I am getting below exception-

java.security.InvalidKeyException: key size must be 128 or 192 bits

Why am i getting this exception and where am i going wrong?

 public byte[] encrypt(String message) throws Exception {

        getResources().getIdentifier("key",
                "raw", getPackageName());
        byte[] bytes = new byte[1024];
        try {
            BufferedInputStream buf = new BufferedInputStream(getResources().openRawResource(
                    getResources().getIdentifier("key",
                            "raw", getPackageName())));
            buf.read(bytes, 0, bytes.length);
            buf.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        final SecretKey key = new SecretKeySpec(bytes, "DESede/ECB/PKCS5Padding");
        final Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE,key);

        final byte[] plainTextBytes = message.getBytes("utf-8");
        final byte[] cipherText = cipher.doFinal(plainTextBytes);

        return cipherText;
    }
Bhuvi
  • 51
  • 2
  • 13
  • 1
    that exception could not possibly be made clearer. – President James K. Polk Nov 20 '16 at 14:02
  • @JamesKPolk I am not able to covert string into cipherText bcoz of above exception..I don't understand exactly wht u mean by "that exception could not possibly be made clearer." – Bhuvi Nov 20 '16 at 14:22
  • @Bhuvi Do not use ECB mode, it is insecure, see [ECB mode](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Electronic_Codebook_.28ECB.29), scroll down to the Penguin. Instead use CBC mode with a random IV, just prefix the encrypted data with the IV for use in decryption. Also 3DES sould not be used in new work. – zaph Nov 21 '16 at 21:43

1 Answers1

0

You passed an array of length 1024 as your key. The key must be either length 16 (128 bits) or 24 (192 bits). 1024 is neither of those numbers.

If you're overallocating for your read, trim the array down to the proper size after reading.

bartonjs
  • 30,352
  • 2
  • 71
  • 111
  • A 16-byte key may work or not depending on the implementation. 3DES keys are 24-bytes, the implementation the OP is using seems to take 16 or 24 bytes with a portion re-used for the 16-byte version. Note, the key sizes are 56-bits, 112-bits ansd 168-bits, the lsb of each byte is ignored, it used to be parity. – zaph Nov 21 '16 at 21:42