0

I have been trying to encrypt with the Cipher class for a while now and I'm still getting issues. I'm having problems with the padding and with the byte array size. I receive this exception "Input length must be multiple of 8 when decrypting with padded cipher" This is the code I wrote:

public CipherClass() {
    try {
        cipher = Cipher.getInstance(CIPHER_ALGO);
        secKey = SecretKeyFactory.getInstance(CIPHER_ALGO).generateSecret(new DESedeKeySpec(new BigInteger(KEY, 16).toByteArray()));
    }
    catch(GeneralSecurityException e){
        e.printStackTrace();
    }
}

private String encrypt(String text){
    try {
        cipher.init(Cipher.ENCRYPT_MODE, secKey);
        Base64 encoder = new Base64();
        return new String(encoder.encode(cipher.doFinal(text.getBytes())));
    }
    catch(GeneralSecurityException e) {
        e.printStackTrace();
    }
    return "";
}

private String decrypt(String text) {
    try {
        cipher.init(Cipher.DECRYPT_MODE, secKey);
        Base64 decoder = new Base64();
        return new String(decoder.decode(cipher.doFinal(text.getBytes())));
    }

    catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

I also tried using Hex instead of Base64 and I'm receiving this exception: "Given final block not properly padded"

please help me out, to find error. thanks in advance.

SSaikia_JtheRocker
  • 5,053
  • 1
  • 22
  • 41
Epi
  • 682
  • 3
  • 10
  • 16
  • Did you look at this: http://stackoverflow.com/questions/8049872/given-final-block-not-properly-padded – Kon Aug 09 '13 at 22:36
  • I did a class to encrypt/decrypt strings last year just as you did. For reasons I don't remember I had to get the text bytes in UTF-8 format. Try modify your last line like `return new String(encoder.encode(cipher.doFinal(text.getBytes(Charset.forName("UTF-8")))));` – dic19 Aug 09 '13 at 22:36
  • 2
    You need to run the base64 decoder before you decrypt. The operations need to mirror each other: `encrypted = encrypt(plaintext) `, `encodedAndEncrypted = encode(encrypted)`; `encrypted = decode(encodedAndEncrypted)`, `plaintext = decrypt(encrypted)` – Zim-Zam O'Pootertoot Aug 09 '13 at 22:37
  • wow Zim-Zam thanks you fixed everything :) – Epi Aug 09 '13 at 22:43
  • @Zim-ZamO'Pootertoot So post it as an answer so it can be accepted. Now you had me read through all this just to find out it has already been answered. – Maarten Bodewes Aug 10 '13 at 11:25

1 Answers1

0

You need to run the base64 decoder before you decrypt. The operations need to mirror each other: encrypted = encrypt(plaintext), encoded = encode(encrypted); encrypted = decode(encoded), plaintext = decrypt(encrypted)

Zim-Zam O'Pootertoot
  • 17,888
  • 4
  • 41
  • 69