Why do i get an "IllegalBlockSizeException"?

I have a piece of code which encrypts a string and stores it into a txt file. But when i come to decrypt the file i get the following error
Exception in thread "main" javax.crypto.IllegalBlockSizeException: Input length
(with padding) not multiple of 8 bytes
at com.sun.crypto.provider.DESCipher.a(DashoA6275)
at com.sun.crypto.provider.DESCipher.engineDoFinal(DashoA6275)
at com.sun.crypto.provider.DESCipher.engineDoFinal(DashoA6275)
at javax.crypto.Cipher.doFinal(DashoA6275)
at javamailerprogram.DES.decrypt(DES.java:110)
at javamailerprogram.DES.main(DES.java:120)
This is my code
package javamailerprogram;
import java.security.*;
import java.security.*;
import javax.crypto.*;
import java.io.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
import javax.crypto.spec.SecretKeySpec;
import java.util.*;
import java.security.interfaces.*;
public class DES {
static SecretKey newKey;
static String ENCRYPTION_TYPE = "DES";
static int KEY_SIZE = 56;
static SecretKeySpec skeySpec;
static SecretKeySpec spec;
static Cipher fileCipher;
public DES(){
Provider sunJce = new com.sun.crypto.provider.SunJCE();
Security.addProvider(sunJce);
try {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
KeyGenerator keyGen = KeyGenerator.getInstance(ENCRYPTION_TYPE);
keyGen.init(KEY_SIZE);
ObjectInputStream in = new ObjectInputStream(new FileInputStream("c:/des.key"));
SecretKey bfSKey = (SecretKey)in.readObject();
byte[] raw = bfSKey.getEncoded();
skeySpec = new SecretKeySpec(raw, ENCRYPTION_TYPE);
} catch (Exception e) {
e.printStackTrace();
public void encrypt(String fileName, String fileNameTo) throws Exception {
byte[] encryptedText;
BufferedReader d
= new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
StringBuffer line = new StringBuffer("");
String lines = "";
while((lines = d.readLine()) !=null){
     line.append(lines);
fileCipher = Cipher.getInstance(ENCRYPTION_TYPE);
fileCipher.init(Cipher.ENCRYPT_MODE, skeySpec);
encryptedText = fileCipher.doFinal(line.toString().getBytes());
FileOutputStream out = new FileOutputStream(fileNameTo);
out.write(encryptedText);
System.out.println("Done");
public String encryptMessage(String textToEncrypt, String fileNameTo) throws Exception {
byte[] encryptedText;
fileCipher = Cipher.getInstance(ENCRYPTION_TYPE);
fileCipher.init(Cipher.ENCRYPT_MODE, skeySpec);
encryptedText = fileCipher.doFinal(textToEncrypt.getBytes());
FileOutputStream out = new FileOutputStream(fileNameTo);
out.write(encryptedText);
System.out.println("Done");
return fileNameTo;
public String encryptMessage(String textToEncrypt) throws Exception {
byte[] encryptedText;
fileCipher = Cipher.getInstance(ENCRYPTION_TYPE);
fileCipher.init(Cipher.ENCRYPT_MODE, skeySpec);
encryptedText = fileCipher.doFinal(textToEncrypt.getBytes());
System.out.println("Done");
return new String(encryptedText);
public String decrypt(String fileName) throws Exception {
byte[] decryptedText;
fileCipher = Cipher.getInstance(ENCRYPTION_TYPE);
BufferedReader d
= new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
StringBuffer line = new StringBuffer("");
String lines = "";
while((lines = d.readLine()) !=null){
     line.append(lines);
System.out.println(line.length());
byte[] theDecryptedText = line.toString().getBytes();
fileCipher.init(Cipher.DECRYPT_MODE, skeySpec);
decryptedText = fileCipher.doFinal(theDecryptedText);
return new String(decryptedText);
public static void main(String[] args) throws Exception {
new DES();
//new DES().encrypt("c:\\encr.txt", "C:\\Encr2.txt");
new DES().encryptMessage("dsgfkdsfdsfudsagifugsadfuigsalidguflasgdfulagsdgfldsagfldsu", "C:\\Encr3.txt");
System.out.println(new DES().decrypt("C:\\Encr3.txt"));
} // end main
} // end SourceViewer2

That's because this byte[] encryptedText;
encryptedText = fileCipher.doFinal(textToEncrypt.getBytes());
return new String(encryptedText); is illegal. You cannot create a String out of any random binary array. Take a look at the API documentation of the String(byte[]) constructor. The only byte arrays you can construct a String out of are ones that conform to a supported encoding scheme, such as ASCII, UTF-8, etc. Cipher.doFinal() returns a byte array that does not conform to any encoding scheme. If you absolutely have to turn your encrypted byte array into a String, then you will need to use Base64 encoding. There is a Base64 encoding package to be found here: http://ostermiller.org/utils/Base64.html .
HTH
- Daniel

Similar Messages

  • Why do i get f4 on field in alv report  ?

    i done general (MM) alv report
    And i display "MATKL" (Material Group) in one of the column.
    I don't know why, but when i stand on the data  , i get f4 option
    , when i asking for f4 i get message, u201CNo input help is availableu201D.
    In the definition, I didnu2019t put the matkl original data element  ,
    I just put char9, i didnu2019t ask/build and double click or
    Event for it.
    so why do i get f4 option in this column  ?
    thanks  .

    Ajay said the correct answer...
    chech this sample code:
    CLEAR  wa_catalog.
      wa_catalog-fieldname = 'BANFN'.
      wa_catalog-ref_table = 'EBAN'.
      APPEND wa_catalog TO catalog.
    Edited by: Sebastian Bustamante on Oct 6, 2008 9:40 PM

  • Why do we get the data from a view to a report.

    hi
    why do we get the data from a view to a report. is it possible to get the data from a view in all the cases?

    hi Jyotssna,
      Suppose you are planning to get the data from multiple tables then you got to specify seveal condtions and make use of joins which results in poor performance in fetching the data . In order to improve the performance we make use of views where the conditions of different tables are defined and the data is fetched accordingly.
    Regards,
    Santosh

  • Why would I get ReferenceError #1065: "Variable title is not defined."

    Well of course it's not defined.  It's a dynamic class, and strict mode compilation is turned off so that I don't have to declare the property to compile it.
    I've created a library item named "Page" with a single TextField instance named "title".
    Page's class is defined in an ActionScript file, and it's assigned to the library item in export for ActionScript.
    Page's ActionScript file defines the class as a "dynamic" class, so I should not be getting this runtime error.  I turned off strict mode compiling, since it seems to be designed to check the presense of property definitions at compile time for dynamic classes like MovieClip.
    public dynamic class Page extends MovieClip
        public function Page()
            super();
            var text:String = title.text; //title can be moused over in the debugger here and shows the correct value, but the flash player throws a runtime error when it tries to access it, but it shouldn't because this is a dynamic class.
    So why am I getting a runtime error for the field "title".  It makes no sense, because if I step to that line in the FlashDevelop debugger and hold the mouse over "title", it shows that it is in fact the instance of the TextField that I'm trying to access.  Yet the player throws an error when I actually try to access it.
    Is it a problem or limitation with the access style (i.e. would it work fine if I accessed it as "this.title" or "this["title"]"?

    Nevermind.  This was apparently a browser caching issue.   The Page base class is defined in the main interface swf, and is externally referenced through its swc in an external "lesson" file that declare a subclass of Page.  It was this custom subclass of Page which was throwing the error (basically the same as the simplified example I wrote for my post, where it simply tried to access "title" as a dynamic property of the Page).  What happened is the browser was caching an old version of the lesson file with the old definition of the class that was not declared as dynamic.  I had received the error before, then updated the class, then I was surprised to see the error persist.  It suddenly dawned on me that the browser was probably caching the old version, so I cleared the cache and it seems to work fine now.
    Actually, it is a problem after all.  I forgot I had updated it to use "this.title" syntax on the page I tested after clearing the cache, but the other pages that try to access title directly as "title" still throw the error.  So it seems to be some sort of quirk in how flash accesses properties of a dynamic class.  If you try to access them direclty, it must do so in a way that requires the property to be defined, but if you access it via "this.title" or this["title"], the it seems to resolve the property value without throwing the error.
    This sucks.  I was really trying to not have to write "this." for every property.  The entire display list is dynamically generated from some custom XML that allows me to call constructors and set complex type-safe properties, and during construction it was copying each item into a Dictionary by name.  This Dictionary was then assigned to the page class as "items", so I was accessing each display object as "item.name".  Then I got the brilliant idea of just making Page and its subclasses "dynamic" so that I could just add the DIctionary values on the Page instance itself.  I thought I would be able to access the dyamic properties just by their name such as "title", but lo and behold, Flash strikes again, and I have to use dot notation anyway.  What do you all think?  Any solutions?

  • Why did I get an email from the fraud dept saying my order is on hold, told to call a number, and then told by dept it's not true?

    I placed an order to upgrade my phone yesterday, and the order went through, I was told the new phone would arrive Thursday. After I got home from work today I saw an email from Verizon that says "Dear Customer:
    Verizon Fraud Prevention Team is currently reviewing the following order on your wireless account. Please call the Verizon Fraud Prevention Team at 888-483-7200 option 3, press 1 to verify this Order."
    I called this number immediately, since I need this phone ASAP, assuming it would just be a recording and I would have to verify an account number or something. But instead, after following the instructions, I was put on hold because I needed to speak to someone in person. After several instances of my call being cut off after being on hold for at least half an hour, I finally got through after three hours and was able to speak to a fraud representative. I gave her my info and told her the problem and she told me I had called the wrong department. Instead of the fraud department, I needed the online order department. She transferred me, and I waited on hold again. When the representative from the online order dept picked up, she first told me if it was a fraud issue I'd need to speak with the fraud dept - who had JUST transferred me to her. After this, she said that my order is not on hold, because it hasn't even been processed yet or had the credit check done. When I asked if this meant I hadn't needed to call at all, she said yes. Is this actually true or is there a chance that there's an issue with my order I don't know about? If there is no issue, these emails really shouldn't be sent out, they're incredibly misleading, and I've wasted a whole lot of time and experienced an incredible amount of anxiety for no reason.

    Hi.  I checked on the order and it says the order is currently being processed and I should check back tomorrow. I'm mostly just concerned because I got an email saying the order was on hold, and I want to make sure it actually does go through and I'm not just waiting for a delivery that's not going to come. I'm still confused as to why I'd get an email saying I had to call the fraud department only to be told I shouldn't have called the fraud department.

  • My iMac locks up constantly in email. I click on one or two emails. Then when I click on another email, I get the spinning wheel and have to relaunch. Why does it get confused and lock up?

    My iMac locks up constantly in email. I click on one or two emails. Then when I click on another email, I get the spinning wheel and have to relaunch. Why does it get confused and lock up? Seems like it is stuck.

    10.6.8 here, MacBook Pro. Comcast. Mail  freeze ups. Occasional warnings to use "Log Out" under the Apple icon.
    Disk Repair run several times. Shows lots of Java  "remote" issues.
    I run Disk Repair several times, shows a lot of Java, "remote" issues.
    Restart don't know if it helps, I do it all the time. What's with quitting Mail but it doesn't quit, and why a separate maneuver to "Log Out".
    i

  • TS1702 "The feature you are trying to use is on a network resource that is unabailable" Why am I getting this message when I try to updaate itunes or quicktime?

    The feature you are trying to use is on a network resource that is unabailable" Why am I getting this message when I try to updaate itunes or quicktime?

    Before trying the update again, use Microsoft's Fix it solution at http://support.microsoft.com/mats/Program_Install_and_Uninstall. Use it to uninstall iTunes and Quicktime. It bypasses this not uncommon problem. When the solution finishes, the selected program will be uninstalled. It can take several minutes and I have seen as much as half an hour.
    After iTunes & Quicktime are uninstalled, try the update again.

  • Why do I get the "iwork discontinued" message when I click on the share feature in pages?

    Why do I get the "iwork discontinued" message when I click on the share feature in pages?

    If you are using an older version of iWorks, the sharing was, I understand discontinued in July 2012.
    New versions of the iWorks suite, Pages etc now have the sharing option, introduced earlier this year.

  • Why do I get a black screen when i click on a PDF in a web page?

    why do I get a black screen when i click on a PDF in a web page? Firefox works as is should.

    Hi,
    From your Safari menu bar click Safari / Preferences then select the Extensions tab. If you have any installed, turn that off, then relaunch Safari. Try a PDF file.
    If it's not Extensions, open a Finder window. Select MacintoshHD in the Sidebar on the left. Now open the Library folder then the Internet Plug-Ins folder. If you see any files such as this:
    AdobePDF Browser or Viewer Plug-in
    Move it to the Trash, relaunch Safari.
    Carolyn :-)

  • Why do I get a warning triangle error alert on my project in the time frame area. And how do I remove it

    Why do I get a yellow triangle looks like warning or alert symbol in my timeframe area. And what do I need to do to delete it?

    What is the "Timeframe" area?
    A clip in an Event, or a whole Event has lost track of it's originals.
    Did you delete anything in an Event that you were using in a Timeilne?

  • Why do I get shadows in the corners of pictures taken on my mini iPad?

    Why do I get shadows in the corners of pictures taken on my mini iPad.  It seems the conditions have to be perfect to get a decent picture.  Why?

    Sounds like vignetting, but you need to ask that on an iPad forum not the iPhoto for Mac one.

  • WHY DO I GET A STATUS REPORT ON EVERY EMAIL RECEIVED

    Why do I get this text on every email I receive which always appears before a message, even if i send a test to myself? can I turn it off? it's only just started to happen.
              From:   Phil Norris <[email protected]>
      Subject:  
              Date:   12 April 2012 21:43:48 GMT+01:00
              To:   Phil Norris <[email protected]>
              Return-Path:   <[email protected]>
              Received:   from nk11p00mm-asmtp005.mac.com ([17.158.161.4]) by ms01534.mac.com (Oracle Communications Messaging Server 7u4-24.01 (7.0.4.24.0) 64bit (built Jan  3 2012)) with ESMTP id <[email protected]> for [email protected]; Thu, 12 Apr 2012 20:43:52 +0000 (GMT)
              Received:   from unknown-58-55-ca-ec-b7-67.home ([109.148.68.123]) by nk11p00mm-asmtp005.mac.com (Oracle Communications Messaging Server 7u4-23.01(7.0.4.23.0) 64bit (built Aug 10 2011)) with ESMTPSA id <[email protected]> for [email protected] (ORCPT [email protected]); Thu, 12 Apr 2012 20:43:51 +0000 (GMT)
              Original-Recipient:   rfc822;[email protected]
              X-Proofpoint-Virus-Version:   vendor=fsecure engine=2.50.10432:5.6.7498,1.0.260,0.0.0000 definitions=2012-04-12_05:2012-04-12,2012-04-12,1970-01-01 signatures=0
              X-Proofpoint-Spam-Details:   rule=notspam policy=default score=0 spamscore=0 ipscore=0 suspectscore=0 phishscore=0 bulkscore=0 adultscore=0 classifier=spam adjust=0 reason=mlx scancount=1 engine=6.0.2-1012030000 definitions=main-1204120250
              Content-Type:   multipart/alternative; boundary=Apple-Mail-1--526056840
              Message-Id:   <[email protected]>
              Mime-Version:   1.0 (Apple Message framework v1084)
              X-Mailer:   Apple Mail (2.1084)
    Thanks

    Those are standard mail headers, but they are normally hidden. Shift-command-H should turn them off or on for the current message. I don't know how that setting got stuck on for you, though.

  • HT3228 Please let me know how to avoid receiving the spam into my email accounts on the iPad.  It is very annoying! My server puts it in the spam folder...why do I get it on the iPad?    Is it avoidable and how?

    Please let me know how to avoid receiving the spam (from the spam folder on the server) into my email accounts on the iPad.  It is very annoying!
    My server puts it in a spam folder and I do not receive it in the Ms Outlook on my desk computer...why do I get it on the iPad?    Is it avoidable and how?b

    You actually cannot do anything to your ipad when its locked but look at pictures the time and date, you need to restore it, and if it dosent let you restore, good luck chuck Heres how to restore it: Okay, i only know the itunes way soz, lol. Try to connect your ipad to itunes, if it does let you then you should be able to select the device you have in the corner somewhere, once you do that you should see a screen that looks sort of like your ipads setting, you should have a button that says "Restore" click that and your ipad should be restored. If that dosent work you should try going to your regular office depot or something. Good Luck!

  • Why do I get the movies only in english?

    As a new Apple TV user this might be a stupid question for pros on Apple TV. Nevertheless, why do I get the movies which I wanted to receive in the German version only in the English version. I make my choice in the German iTunes-Store, I watch the trailers in German, but when I order the movie, I get it only in English. Am I stupid or what?
    Thanks for your help.
    Hartwin

    Hartwin, that's odd. Does this happen with every movie you've rented?
    And do you perhaps have a US iTunes account that you're using to order from?
    Other than that, I really can't think of an answer.

  • Why do I get "Evaluation Expired" message in MAX with Switch Executive

    Why do I get �Evaluation Expired� message in MAX with Switch Executive on a PXI rack, which has a �Ghosted� image from and identical PXI rack(no problem with this PXI rack), when logged in as USER in Windows2000, but not when logged in as a Local Administrator. When logged in as Administrator in Windows2000 running a TestStand sequence, using a �C� code action step calling the nise.dll is ok, but not when logged in as local user. The alias switch name is unknown.

    1.0.4.109 is a dll version number where as 1.0.2 is a NISE version number. The dll version number does not always line up with the product version number.
    NISE 1.0 has a dll version of 1.0.1.109
    NISE 1.0.1 has a dll version of 1.1.4.1
    NISE 1.0.2 has a dll version of 1.2.4.7
    NISE 2.0 has a dll version of 2.0.0.45154
    The best way to find the product number is to launch the application and click on Help and About. You NISE version is probably 1.0 and NISE 1.0.2 will fix your licensing problem.

Maybe you are looking for

  • Faces Performance vrs Struts

    In evaluating JSF's, I put together a simple customer maintenance application of about 10 screens, first using Struts and then again using JSF's, matching the UI exactly. To measure relative performance between these two technologies, I isolated 3 re

  • Space around children in FormItem

    Can anyone help me or point me in the right direction? Inside a Form, I have FormItems with children, for example, RadioButtons (see below). For the life of me, I cannot figure out what property controls the "extra space" that FormItem seems to put t

  • Vendor Transfer ALE failing - Process Code issue?

    we're transferring vendors from our ECC 6 client to a new GTS client using ALE. The distribution model looks good - we're using /SAPSLL/CREMAS_SLL to transfer the vendors. The data is being sent from the feeder just fine. but it's erroring on the rec

  • 10.1.3.5 - unable to find ws-addressing.xsd during SOA startup

    I see the following messages in my logs during server startup any clue how to fix this ? the file seems to be there under bpel/system/xmllib <2010-01-07 17:02:13,718> <DEBUG> <collaxa> <ProcessJob::execute> Attempt (2/30) ... testing http access to s

  • AMFPHP and Flex 2 B3

    I'm trying to do the AMFPHP tutorial in the Labs wiki and am running into errors. Any ideas what is happening? Here's the tutorial Link to Wiki I'm getting an error on this line: public var gateway : RemotingConnection; And the error is: Type was not