get rid of exceptions
hi all
i am encrypting and decrypting a data
d code goes well but i get the following exceptions
javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.DESCipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
at fileviewerframe$DesTest.<init>(Main.java:154)
at fileviewerframe$fileopen.actionPerformed(Main.java:69)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.AbstractButton.doClick(AbstractButton.java:357)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1216)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:1257)
at java.awt.Component.processMouseEvent(Component.java:6038)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3260)
at java.awt.Component.processEvent(Component.java:5803)
at java.awt.Container.processEvent(Container.java:2058)
at java.awt.Component.dispatchEventImpl(Component.java:4410)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
at java.awt.Container.dispatchEventImpl(Container.java:2102)
at java.awt.Window.dispatchEventImpl(Window.java:2429)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
my code ispublic DesTest(InputStream in,OutputStream out)throws Exception
{
Security.addProvider(new com.sun.crypto.provider.SunJCE());
try{
KeyGenerator kg = KeyGenerator.getInstance("DES");
Key key = kg.generateKey();
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key);
int blockSize = cipher.getBlockSize();
int outputSize = cipher.getOutputSize(blockSize);
byte[] inBytes =newbyte[blockSize];
byte[] outBytes =newbyte[outputSize];
int inLength = 0;;
boolean more =true;
while (more)
{
inLength = in.read(inBytes);
if (inLength == blockSize)
{
int outLength
= cipher.update(inBytes, 0, blockSize, outBytes);
out.write(outBytes, 0, outLength);
System.out.println(outLength);
}
else more =false;
}
if (inLength > 0)
outBytes = cipher.doFinal(inBytes, 0, inLength);
else
{outBytes = cipher.doFinal();
System.out.println(outBytes.length);
out.write(outBytes);
}
i take file choosing from jdialog and then pass them to this function
Have you tried specifying a padding such as PKCS5Padding? Have you put your cipher in a more appropriate mode such as CBC or OFB? http://java.sun.com/j2se/1.4.2/docs/guide/security/jce/JCERefGuide.html#AppA
- Saish
Saisha at 2007-7-29 11:33:18 >

Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
now i hav used this function
result
javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.DESCipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
at fileviewerframe$DesTest.<init>(Main.java:154)
at fileviewerframe$fileopen.actionPerformed(Main.java:69)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.AbstractButton.doClick(AbstractButton.java:357)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1216)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:1257)
at java.awt.Component.processMouseEvent(Component.java:6038)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3260)
at java.awt.Component.processEvent(Component.java:5803)
at java.awt.Container.processEvent(Container.java:2058)
at java.awt.Component.dispatchEventImpl(Component.java:4410)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
at java.awt.Container.dispatchEventImpl(Container.java:2102)
at java.awt.Window.dispatchEventImpl(Window.java:2429)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
that means same exceptions
1 more point i discovered
that dere are no exceptions popping up wen i use the code for encryption only
final class CryptoTest {
private static final String PLAINTEXT =
"This is a test of encrypting and decrypting using padding and CBC.";
static {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
}
private CryptoTest() {
super();
}
public static final void main(final String[] args)
throws Exception {
KeyGenerator kg = KeyGenerator.getInstance("DES");
Key key = kg.generateKey();
InputStream plaintextIn = new ByteArrayInputStream(PLAINTEXT.getBytes());
ByteArrayOutputStream ciphertextOut = new ByteArrayOutputStream();
encryptOrDecrypt(Cipher.ENCRYPT_MODE, key, plaintextIn, ciphertextOut);
System.out.println("Ciphertext: " + new String(ciphertextOut.toByteArray()));
InputStream ciphertextIn = new ByteArrayInputStream(ciphertextOut.toByteArray());
ByteArrayOutputStream plaintextOut = new ByteArrayOutputStream();
encryptOrDecrypt(Cipher.DECRYPT_MODE, key, ciphertextIn, plaintextOut);
System.out.println("Plaintext: " + new String(plaintextOut.toByteArray()));
assert(PLAINTEXT.equals(new String(plaintextOut.toByteArray())));
}
private static void encryptOrDecrypt(final int mode, final Key key,
final InputStream in, final OutputStream out)
throws Exception {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(mode, key);
byte[] buffer = new byte[cipher.getBlockSize()];
int bytesRead = in.read(buffer);
while (bytesRead >= 0) {
byte[] updated = cipher.update(buffer, 0, bytesRead);
if (updated.length > 0) {
out.write(updated);
}
bytesRead = in.read(buffer);
}
byte[] doFinal = cipher.doFinal();
if (doFinal.length > 0) {
out.write(doFinal);
}
out.flush();
}
}
Note: You should really use a CipherInputStream or CipherOutputStream here (a lot less code). There are a number of optimizations that can be made.
Warning: I only wrapped the ciphertext in a string to print as a demonstration. You always want to leave the ciphertext as a byte array.
- Saish
Saisha at 2007-7-29 11:33:18 >

now wat was that reply meant for
i am now sending my whole source code may be this is helpful for someone to suggest me a solutionpublic static class DesTest
{
public DesTest(InputStream in,OutputStream out)throws IOException,GeneralSecurityException, ClassNotFoundException
{
Security.addProvider(new com.sun.crypto.provider.SunJCE());
try {
KeyGenerator kg = KeyGenerator.getInstance("DES");
Key generatekey = kg.generateKey();
System.out.println(generatekey);
File keyfile = new File("C:\\Documents and Settings\\ayush\\Desktop\\key.txt");
ObjectOutputStream out3=new ObjectOutputStream(new FileOutputStream(keyfile));
out3.writeObject(generatekey);
out3.close();
ObjectInputStream keyIn = new ObjectInputStream(
new FileInputStream("C:\\Documents and Settings\\ayush\\Desktop\\key.txt"));
Key key = (Key) keyIn.readObject();
keyIn.close();
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
int blockSize = cipher.getBlockSize();
int outputSize = cipher.getOutputSize(blockSize);
byte[] inBytes = new byte[blockSize];
byte[] outBytes = new byte[outputSize];
int inLength = 0;;
boolean more = true;
while (more)
{
inLength = in.read(inBytes);
if (inLength == blockSize)
{
int outLength
= cipher.update(inBytes, 0, blockSize, outBytes);
out.write(outBytes, 0, outLength);
//System.out.println(outLength);
}
else more = false;
}
if (inLength > 0)
outBytes = cipher.doFinal(inBytes, 0, inLength);
else
{outBytes = cipher.doFinal();
//System.out.println(outBytes.length);
out.write(outBytes);
}
InputStream in2=new FileInputStream("C:\\Documents and Settings\\ayush\\Desktop\\output.txt");
File decryptionfile = new File("C:\\Documents and Settings\\ayush\\Desktop\\decryptedoutput.txt");
OutputStream out2=new FileOutputStream(decryptionfile);
decrypt(in2,out2,key);
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch (NoSuchPaddingException e) {
e.printStackTrace();
}
catch (InvalidKeyException e) {
e.printStackTrace();
}
catch (IllegalStateException e) {
e.printStackTrace();
}
catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
catch (BadPaddingException e) {
e.printStackTrace();
}
}
public static void decrypt(InputStream in2,OutputStream out2,Key key) throws IOException, ShortBufferException
{
Security.addProvider(new com.sun.crypto.provider.SunJCE());
try {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
int blockSize2 = cipher.getBlockSize();
int outputSize2 = cipher.getOutputSize(blockSize2);
byte[] inBytes2 = new byte[blockSize2];
byte[] outBytes2 = new byte[outputSize2];
int inLength2 = 0;;
boolean more2 = true;
while (more2)
{
inLength2 = in2.read(inBytes2);
if (inLength2 == blockSize2)
{
int outLength2
= cipher.update(inBytes2, 0, blockSize2, outBytes2);
out2.write(outBytes2, 0, outLength2);
//System.out.println(outLength2);
}
else more2 = false;
}
if (inLength2 > 0)
outBytes2 = cipher.doFinal(inBytes2, 0, inLength2);
else
{outBytes2 = cipher.doFinal();
//System.out.println(outBytes2.length);
out2.write(outBytes2);
}
in2.close();
out2.close();
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch (NoSuchPaddingException e) {
e.printStackTrace();
}
catch (InvalidKeyException e) {
e.printStackTrace();
}
catch (IllegalStateException e) {
e.printStackTrace();
}
catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
catch (BadPaddingException e) {
e.printStackTrace();
}
}
actually i note that on decrypting i loose some last characters of the file
but iam just not able to catch wat is going wrong in the code
Message was edited by:
noobs_will_rule
> now wat was that reply meant for
It meant that just saying "wasn't helpful" isn't helpful. How can we suggest another solution if you don't tell us what's wrong with the one you've been given? What's not helpful about it?
this is the exception i get now
javax.crypto.IllegalBlockSizeException:Input length must be multiple of 8 when decrypting with padded cipher
and exception only pop up when i read the encrypted data from a file
if i just encrypt data and put it to decryption there is no exception
and i am checkin padding here
if (inLength2 > 0)
outBytes2 = cipher.doFinal(inBytes2, 0, inLength2);
else
{outBytes2 = cipher.doFinal();
//System.out.println(outBytes2.length);
out2.write(outBytes2);
}
can somebody help out
saish i just used your code and now i get no exception
thanks
but now also i have i doubt "what is wrong in my code"
neway cheers
u earned 5 dukes
Thanks. I'm just confused too. But hope it works for you. My guess is your original problem was in how you were reading and writing from byte arrays of different sizes, but that's only a guess.
- Saish
Saisha at 2007-7-29 11:33:18 >

There are several problems, the most obvious being that this code is wrongboolean more = true;
while (more)
{
inLength = in.read(inBytes);
if (inLength == blockSize)
{
int outLength
= cipher.update(inBytes, 0, blockSize, outBytes);
out.write(outBytes, 0, outLength);
//System.out.println(outLength);
}
else more = false;
}
Since it assumes wrongly thatinLength = in.read(inBytes);
reads a whole block if it can. It does not. Check the specification for InputStream.read(byte[]).
You should really be using CipherInputStream and CipherOutputStream and then you would get rid of about 80% of your code.
P.S. Your exception handling is at best very poor.
int read(byte[] b)
Reads some number of bytes from the input stream and stores them into the buffer array b.
ok
thanks for clearing my misconception