Topic
  • 2 replies
  • Latest Post - ‏2010-08-22T18:35:08Z by sabre150
genxlogics
genxlogics
1 Post

Pinned topic Decrypted text is different from Original text

‏2010-07-10T00:39:41Z |
Hi All,
I am doing symmetric key encryption/decryption. my key is saved in a keystore.now my problem is my decrypted text is different from plain text.
below is my code:
static String justdecrypt(SecretKey key,String ciphertext) throws Exception{
Cipher cipher=Cipher.getInstance("DESede");
BASE64Encoder encoder=new BASE64Encoder();
BASE64Decoder decoder=new BASE64Decoder();
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] ciphers=decoder.decodeBuffer(ciphertext);
System.out.println("cipher byte in decryption : #"+ciphers);
byte [] plains=cipher.doFinal(ciphers);
System.out.println("plain byte in encryption : #"+plains);
String plaintext=encoder.encode(plains);
System.out.println("plaint text : #####"plaintext"#####");
return plaintext;

}

static String justencrypt(SecretKey key,String plain) throws Exception{
Cipher cipher=Cipher.getInstance("DESede");
BASE64Encoder encoder=new BASE64Encoder();
BASE64Decoder decoder=new BASE64Decoder();
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] plains=decoder.decodeBuffer(plain);
//byte [] plains=plain.getBytes();
System.out.println("plain byte in encryption : #"+plains);
byte[] ciphers=cipher.doFinal(plains);
System.out.println("cipher byte in encryption : #"+ciphers);
String ciphertext=encoder.encode(ciphers);
System.out.println("cipher text : #####"ciphertext"#####");
return ciphertext;
}

when i encrypt "plainttext" and then decrypt the same i am getting the decrypted text as "plaintex"

what is the mistake i am doing?
Updated on 2010-08-22T18:35:08Z at 2010-08-22T18:35:08Z by sabre150
  • saurabhsule82
    saurabhsule82
    12 Posts

    Re: Decrypted text is different from Original text

    ‏2010-07-11T13:42:48Z  
    Check if using this line of code in both the functions works:

    Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
  • sabre150
    sabre150
    1 Post

    Re: Decrypted text is different from Original text

    ‏2010-08-22T18:35:08Z  
    As long as your clear text (that referenced by 'plain') is Base64 encoded then that code should work. It is unusual to have the clear text Base64 encoded so are you sure it is Base64 encoded. Since "plainttext" is not a multiple of 4 characters then it is not valid Base64 encoded text and your statement 'when i encrypt "plainttext" and then decrypt the same i am getting the decrypted text as "plaintex"' implies that is is not.

    I suspect that in the encryption method you need to do

    byte[] ciphers=ciphertext.getBytes("uft-8");

    and in the decryption method you need

    String plaintext= new String(plains, "utf-8");