In my project, secure communication is used between android client and server so all messages between them are encrypted as DES algorithm. I have used default Java Provider and also SpongyCastle but in first try of decryption, it gives the below exception.
javax.crypto.IllegalBlockSizeException: last block incomplete in decryption
at org.spongycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(BaseBlockCipher.java:815)
at javax.crypto.Cipher.doFinal(Cipher.java:1111)
Encoded String below
SB1DbM9MbtFYY62OtDwkU4+CxlHi7wj9MQIPVMsoktVyPZDoi79V2Hx5pzjLgQvxXKJSLP7BpNYZg4hlbVGzkCE8x4LTmTbdQzwweMjlOGfTbZSNA+iL1sx0ctRYFIVLu7c0ZnsSnJ4Fq2tdL2XS3YQW3/MokoAlyFK6lhBf/4t+VpZ/cy+s9g==
In the second try, it successfully decrypts String. I couldn't find the problem.
Source Code that Encrypt and Decrypt
private Cipher encryptCipher = null;
private Cipher decryptCipher = null;
static {
Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1);
}
public void initialize(SecretKey key) throws Exception {
try {
encryptCipher = Cipher.getInstance("DES/ECB/PKCS5Padding", "SC");
decryptCipher = Cipher.getInstance("DES/ECB/PKCS5Padding", "SC");
} catch (Exception e) {
}
encryptCipher.init(Cipher.ENCRYPT_MODE, key);
decryptCipher.init(Cipher.DECRYPT_MODE, key);
}
public String encryptBase64(String unencryptedString) throws Exception {
byte[] unencryptedByteArray = unencryptedString.getBytes("UTF-8");
byte[] encryptedBytes = encryptCipher.doFinal(unencryptedByteArray);
return new String(Base64.encodeBase64(encryptedBytes), "UTF-8");
}
public String decryptBase64(String encryptedString) throws Exception {
try {
byte[] unencryptedByteArray = decryptCipher.doFinal(Base64.decodeBase64(encryptedString.getBytes("UTF-8")));
String message = new String(unencryptedByteArray, "UTF-8");
return message;
} catch (Exception e) {
}
return null;
}