Can't decrypt with JCE

Hi all,
I've written a very simple encrypter/decrypter using JCE and the sun provider. It seems to encrypt fine, but it doesn't decrypt at all. The code is below:
import java.io.*;
import java.net.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import com.sun.crypto.provider.*;
public class Crypt {
     private Cipher encipher;
     private Cipher decipher;
     /** Creates new Crypt */
               public Crypt() {
                    try {
                         //add the provider
                         java.security.Security.addProvider(new com.sun.crypto.provider.SunJCE());
                         //initialize everything
                         KeySpec keySpec = new PBEKeySpec(new String("test key").toCharArray());
                         SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
                         encipher = Cipher.getInstance(key.getAlgorithm());
                         decipher = Cipher.getInstance(key.getAlgorithm());
                         AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
                         encipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
                         decipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
                         String toEncrypt = "this is a test";
                         String encrypted = encrypt(toEncrypt);
                         String unEncrypted = decrypt(encrypted);
                         System.out.println("Original string: " + toEncrypt);
                         System.out.println("Encrypted string: " + encrypted);
                         System.out.println("Decrypted string: " + unEncrypted);
                    } catch (Exception ex) {
                         ex.printStackTrace();
     public String encrypt(String payload) {
               try {
                    //encode the string into bytes using UTF-8
                    byte[] b = payload.getBytes("UTF8");
                    //Encrypt
                    byte[] enc = encipher.doFinal();
                    //return new String(enc);
                    return new sun.misc.BASE64Encoder().encode(enc);
               } catch (Exception ex) {
                    ex.printStackTrace();
               return null;
          public String decrypt(String payload) {
               try {
                    //decode base64 to get bytes
                    byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(payload);
                    System.out.println("Size: " + dec.length);
                    //decrypt
                    byte[] utf8 = decipher.doFinal(dec);
                    System.out.println("Size: " + utf8.length);
                    for (int i = 0; i < utf8.length; i++) {
                         System.out.println(utf8);
                    //Decrypt
                    return new String(utf8, "UTF8");
               } catch (Exception ex) {
                    ex.printStackTrace();
               return null;
          public static void main(String[] args) {
               Crypt c = new Crypt();
The output for
                         System.out.println("Decrypted string: " + unEncrypted);
is
Decrypted string:
so something is going wrong. Any ideas?

Cut and past can always come back to bite you.Heh. He who lives by the cut-buffer, dies by the cut-buffer. If I had a dime for every time I've bitten myself with a cut-n-paste error, I'd be...significantly richer than I am ;).
ThanksNo prob - it's always the simple stuff that we overlook.
Grant

Similar Messages

  • I can't decrypt a text encrypted(useing RSA) with publickey on mobile

    hi all, I got some problem with my code,
    when I wanna use the JSR177 of J2ME to do something about Decryption
    here is some of my code as following:
    KeyFactory kf = KeyFactory.getInstance("RSA");
    byte[] publickeyEncode
    x509EncodedKeySpec keyspec = new X509EncodedKeySpec(publickeyEncode)
    PublicKey pubkey = kf.generatePublic(Keyspec) as using that, we can renew our publickey which is from the server.
    but there are Exception when I use the publickey to do decryption.
    java.security.InvalidKeyException
    at com.sun.satsa.crypto.RSACipher.init(+31)
    at javax.crypto.Cipher.init(+30)
    at javax.crypto.Cipher.init(+7)
    at KEYback.startApp(+210)
    at javax.microedition.midlet.MIDletProxy.startApp(+7)
    at com.sun.midp.midlet.Scheduler.schedule(+270)
    at com.sun.midp.main.Main.runLocalClass(+28)
    at com.sun.midp.main.Main.main(+116) however, the problem is solved when I change the DECRYPTO_MODE into ENCRYPTO_MODE
    so, is it impossible to do decryption with publickey on the mobile???

    because in the JSR177 apis,there is not "PrivateKey" this class so we only can use the "PublicKey" to do Decryption on the Mobile and do Encryption on Server with the PrivateKey..Sorry, I forgot that you are working in the J2ME context.
    as the result of our test , when the cipher_mode is "Encrypto", the code is run well, but when we turn is to "Decrytpo", the Exception is appear.Did you check that the encryption does return a valid result? Because while reading the JSR177 javadoc I got the feeling that the PublicKey only exists for verifying signatures.
    May be you should consider switching to the J2ME Bouncycastle implementation completly (or only for decryption). AFAIK it works idependent of JSR177.
    Jan

  • Can't decrypt

    hi!
    I'm using BouncyCastle OpenPGP 1.37 to encrypt files with IDEA algorithm. The problem is that I can't decrypt these files with PGP 5.5 desktop ("An error has ocurred: encryption session key is bad"). PGP 5.5 accepts IDEA algorithm... I can't use other PGP version. I'm using BouncyCastle's provider, may I use other provider (SunJCE?) so as to encrypt files with other IDEA implementation?
    Help me please!
    Thanks.

    I would love to know why it doesn't recognize it in Normal boot mode.
    Maybe because you installed the unnecessary WD software. If you did, remove it and see whether there's an improvement.

  • Can multiple iphones with multiple itunes accounts be synced to one mac keeping apps seperate over the air?

    We have about 20 iPhone's in our environment and syncing and updating them has become a real chore lately.  Everyone has their own iTunes account and apps that they use. Is there a way that they can be synced, backed up and updated over the air (not iCloud) to the same MAC?  Because we are in the financial sector we will not be able to use iCloud. Should we look into some sort of private cloud and if so; any suggestions on how to accomplish it would be greatly appreciated.
    Thank you in advance,
    J

    We have several macs, several ipods, a couple of iphones, several itunes store accounts. So far no problem. You might have to share passwords if you want to share content. I think iStore accounts can only be used on up to 5 computers. We have 7, so have to be a little careful about that. I don't think there is a limit on how many iDevices can be used with one account. I also don't think there is a limit on how many accounts can be used on a single computer (might be wrong about that). You have to be logged into the iStore to download content, and your computer has to be registered with the account to use the content, but once it is on, and registered, syncing to an iPod is not a problem (you do not have to login in again for each account the content was purchased from). I'm just glad I only have two kids, and one wife - things could get trickier in a big family with . . .

  • How can I deal with negative marking in a quiz marking scheme?

    I wonder if anyone can help me with a problem I have in developing the 'code' for a marking scheme for an exam in Captivate 8. I would be very grateful for pointers towards a viable solution. At the moment I am just thrashing around.
    My background is in C++ and I think part of my problem is in trying to find analogues of functions I would use in that environment. My experience with Captivate is limited to developing fairly simple training courses but now I need to put an existing exam on line, maintaining its relatively complicated marking scheme, which is as follows:
    The paper is multiple choice, each question having four statements, one (or at the most two) of which is true. A completely correct answer gets 4 marks so where there are two correct statements each gets 2 marks. So far, so easy.
    The difficulty arises from an element of negative marking. If 3 or more statements are selected, the score is 0 marks. If there is a single correct statement and it and an incorrect statement are selected, the score is 2 marks. If there are 2 correct statements and one of them is selected, the score is 2 marks. If an incorrect statement is selected as well, the score is 1 mark.
    I had assumed I could use conditional logic and user variables on a slide-by-slide basis to provide a score value and then assign it to the appropriate system quiz variable, but it seems I can't assign values to variables in a quiz slide. That would have been too easy...
    So, can anybody advise me on an approach that keeps the advantages of using the quiz framework, including the use of the Review function?
    Any help very gratefully received.

    If you use SCORM 1.2 for reporting, negative scores will be converted to zero, because it doesn't allow negative score.
    If you want to keep to Review functionality, you need to stay with the default question slides. There are some tweaking possibilities but changing the score is not one of them.
    Question Question Slides in Captivate - Captivate blog
    Question Question Slides - Part 2 - Captivate blog
    I think the only possible way is to use JS, but then you'll not be able to keep the functionality of the Question slides, you are in custom question slides. Plenty of examples of custom questions can be found on my blog as well.

  • HT202667 Hi - My daughter was using her Apple TV until recently when she got a Smart TV.  Now the Apple TV is not needed so she passed it on to me.  How do I get it transferred over from her Home Sharing account to mine so that I can use it with my PC?

    Hi - My daughter was using her Apple TV until recently when she got a Smart TV.  Now the Apple TV is not needed so she passed it on to me.  How do I get her Home Sharing account transferred over to mine so that I can use it with my PC? Thanks!

    As  Winston Churchill wrote, however you might want to do a factory reset on the Apple TV.
    This way all information pertaining to your daughter will be removed from the device. Specifically if see was sign into any of the streaming service, Netflix, Hulu, etc. her credentials will still be associated with this Apple TV, doing  a factory reset will remove all that and make it as if you purchased the device and just plugged it in.
    regards

  • How many devices can you register with a personal dev account

    can anyone tell me how many udids can i register with a personal account as i have a team of testers i would like to add , would i need a company dev account for this thanks or will my personal one be ok for this

    Still the same. Maximum 100 per year for testing. Individual Developer Account, person or company.
    Enterprise Account is for distribution to employees, not via the App Store.

  • How can I print with the black and white cartridge only?

    I am trying to print using the black and white cartridge only because magenta is out of ink but I'm getting the following error message in HP Photosmart C7200 series print dialog:
    The printer is out of ink.
    The following ink cartridges are empty: Magenta. Replace these ink cartridges to resume printing.
    How can I print with the black and white cartridge only?
    Mac OSX 10.7.3
    HP Photosmart C7280 (7200 series)
    This question was solved.
    View Solution.

    I am absolutely disgusted by this; clearly a scam from HP to make more money by selling extra ink cartridges!!  I will make sure to never buy any products from the shoddy rip off merchants at HP ever again!!
    You should be ashamed!!

  • In ical I just added new calendars to a pre-existing calendar group, I can make events with these calendars, but not reminders, any suggestions?

    in ical I just added new calendars to a pre-existing calendar group, I can make events with these calendars, but not reminders, any suggestions?

    Hi,
    Lion has changed the way reminders (todos as was) work. They now seem to need to be in a seperate calendar.
    In iCal open the File menu and select New Reminder List... and select where to put it.
    Best wishes
    John M

  • Can some help with CR2 files ,Ican`t see CR2 files in adobe bridge

    can some help with CR2 files ,I can`t see CR2 files in adobe bridge when I open Adobe Photoshop cs5- help- about plugins- no camera raw plugins. When i go Edit- preference and click on camera raw  shows message that Adobe camera raw plugin cannot be found

    That's strage. Seems that the Camera Raw.8bi file has been moved to different location or has gone corrupt. By any chance did you try to move the camera raw plugin to a custom location?
    Go To "C:\Program Files (x86)\Common Files\Adobe\Plug-Ins\CS5\File Formats" and look for Camera Raw.8bi file.
    If you have that file there, try to download the updated camera raw plugin from the below location.
    http://www.adobe.com/support/downloads/thankyou.jsp?ftpID=5371&fileID=5001
    In case  you ae not able to locate the Camera Raw.8bi file on the above location, then i think you need to re-install PS CS5.
    [Moving the discussion to Photoshop General Discussions Forum]

  • Slave instance can not synchronized with the master for a long time

    Hi,
    Slave instance can not synchronized with the master for a long time, and the gap of LSNs between slave and master are more and more larger. The transfer bytes per second between master and slave is 118MB/s , upper limit to the ethernet card. Why???
    ENVIRONMENT:
    1. A network program which we called mcdb is based on BDB 4.8.30. It is used to accept get/set requests and then query data from bdb or save data to bdb.
    2. mcdb implements replication with bdb replication manager api. The default start replication policy is DB_REP_ELECTION, rep ack policy is DB_REPMGR_ACKS_ONE_PEER and rep priority is 100.
    3. The bdb data files, bdb log files, region files and rep files are all in the same home directory.
    4. There are two instances of the mcdb are separately on two standalone servers which has no other programs. These two instances are in one replication group which can elect a master automatically.
    5. The master instance is online, which has lots of requests (get, set, delete).
    ACTIONS:
    1. Start two mcdb instances on two servers and the two instance make a replication group. Slave has already synchronized with the master.
    2. Stop the slave for a long time (more than 20 hours).
    3. Start the slave instance to synchronize data with master.
    RESULT:
    1. the gap of LSNs between slave and master are more and more larger.
    2. db_stat of master and slave:
    master db_stat:
    467170     Number of PERM messages not acknowledged
    9245     Number of messages queued due to network delay
    172415     Number of messages discarded due to queue length
    25880     Number of existing connections dropped
    3407     Number of failed new connection attempts
    =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    DB_REPMGR site information:
    10.67.15.146 (eid: 0, port: 30011)
    Environment configured as a replication master
    331726/3574994     Next LSN to be used
    0/0     Not waiting for any missed log records
    328872/466092     Maximum permanent LSN
    0     Next page number expected
    0     Not waiting for any missed pages
    0     Number of duplicate master conditions originally detected at this site
    2147M     Current environment ID (2147483647)
    100     Current environment priority
    49     Current generation number
    50     Election generation number for the current or next election
    2323     Number of duplicate log records received
    0     Number of log records currently queued
    6768     Maximum number of log records ever queued at once
    55284     Total number of log records queued
    120M     Number of log records received and appended to the log (120475988)
    111     Number of log records missed and requested
    2147M     Current master ID (2147483647)
    2     Number of times the master has changed
    0     Number of messages received with a bad generation number
    8505306     Number of messages received and processed
    12     Number of messages ignored due to pending recovery
    471869     Number of failed message sends
    12M     Number of messages sent (12959945)
    0     Number of new site messages received
    1     Number of environments believed to be in the replication group
    990543     Transmission limited
    0     Number of outdated conditions detected
    0     Number of duplicate page records received
    0     Number of page records received and added to databases
    0     Number of page records missed and requested
    Startup complete
    6244678     Number of transactions applied
    0     Number of startsync messages delayed
    1     Number of elections held
    1     Number of elections won
    No election in progress
    0.057097     Duration of last election (seconds)
    8944103     Number of bulk buffer sends triggered by full buffer
    0     Number of single records exceeding bulk buffer size
    5273M     Number of records added to a bulk buffer (5273592170)
    10M     Number of bulk buffers sent (10490865)
    0     Number of re-request messages received
    0     Number of request messages this client failed to process
    0     Number of request messages received by this client
    slave db_stat:
    0     Number of PERM messages not acknowledged
    0     Number of messages queued due to network delay
    0     Number of messages discarded due to queue length
    1454     Number of existing connections dropped
    0     Number of failed new connection attempts
    =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    DB_REPMGR site information:
    10.67.15.147 (eid: 0, port: 30011)
    Environment configured as a replication client
    329544/2916048     Next LSN expected
    330433/2013808     LSN of first log record we have after missed log records
    329543/5500501     Maximum permanent LSN
    0     Next page number expected
    0     Not waiting for any missed pages
    0     Number of duplicate master conditions originally detected at this site
    2147M     Current environment ID (2147483647)
    100     Current environment priority
    49     Current generation number
    50     Election generation number for the current or next election
    5256M     Number of duplicate log records received (5256599432)
    3925284     Number of log records currently queued
    3925285     Maximum number of log records ever queued at once
    4880561     Total number of log records queued
    3578038     Number of log records received and appended to the log
    1912297     Number of log records missed and requested
    0     Current master ID
    1     Number of times the master has changed
    0     Number of messages received with a bad generation number
    12M     Number of messages received and processed (12980442)
    2     Number of messages ignored due to pending recovery
    0     Number of failed message sends
    1912307     Number of messages sent
    0     Number of new site messages received
    0     Number of environments believed to be in the replication group
    0     Transmission limited
    0     Number of outdated conditions detected
    0     Number of duplicate page records received
    0     Number of page records received and added to databases
    0     Number of page records missed and requested
    Startup incomplete
    110568     Number of transactions applied
    80     Number of startsync messages delayed
    0     Number of elections held
    0     Number of elections won
    No election in progress
    0     Number of bulk buffer sends triggered by full buffer
    0     Number of single records exceeding bulk buffer size
    0     Number of records added to a bulk buffer
    0     Number of bulk buffers sent
    0     Number of re-request messages received
    0     Number of request messages this client failed to process
    0     Number of request messages received by this client
    Edited by: 899585 on 2013-1-4 下午10:54
    Edited by: 899585 on 2013-1-4 下午10:55

    Hi,
    Unfortunately, this issue is beyond the level of what is supported over the forum. Performance related issues are extremely complex and require an in-depth understanding of your environment and dedicated support. In a generic sense, you can look at this as a basic queueing problem. You have a server that went down and work is still coming in. When the server gets started it is possible that it may never catch up depending on new work coming in and the rate at processing the old work.
    So what would you do in this case --- one thing would be to reduce the new work coming in. In HA terms this would be slowing the master down and you can increase DB_REP_ACK_TIMEOUT for this. Another thing you could do is add fresh servers to help reduce the workload. In HA terms, this would be the equivalent of restarting the client and give it a fresh look at everything. Another thing you could do is replan the system and load balance. In HA terms, it would mean something like take a hot backup of the master and reinit a client from scratch.
    If you are interested in getting a dedicated support person working on this concern, please let me know and we can move forward down that path. Just respond to the thread with your email address and I will get in contact with you so we can pursue that approach.
    thanks
    mike

  • I have LabView but I do not have the Calibration and Configuration Palette,and I could not download it, how can I download it or if i cannot,can I work with the NI-DAQ Calibration_1200?

    I have read in a tutorial for the board 1200 that I can calibrate it with the Calibration and Configuration Palette in LabVIEW, but I do not have them and I could not download it to access its libraries, so I can only download the NI-DAQ software,What's my best choice and if it is to download the palette with its libraries, how can download it with them?I'd appreciate your answers

    If you wish to use your 1200 device in LabVIEW, you must download and install NI-DAQ. When you install NI-DAQ, it will ask you if you would like to install support for LabVIEW. By installing this support, you will then have access to the DAQ pallette in LabVIEW. The DAQ pallette requires that you have NI-DAQ installed.
    For more information on installing and using your device, you can refer to the DAQ Quick Start Guide. You can download it from:
    http://digital.ni.com/manuals.nsf/14807683e3b2dd8f8625677b006643f0/0eca53fe80911b1f862568560068295d
    Regards,
    Erin

  • I Tunes downloads onto my PC but won't open. Can someone assist  with this dilema?

    I have downloaded I Tunes to my PC numerous times. The download goes fine. When I hit the icon to open I Tunes up, nothing happens. I have removed I Tunes from my system and reloaded, and still it won't open. Can anyone help with this dilema?

    Thanks for this mha007 - I can now open FF with a new profile. Can I copy my settings from the old profile or will this bring over the same problem, maybe a corrupt file. If it would bring the same problem, is there any way I can check which file is corrupt, apart from taking them over one by one?

  • Sharepoint list dataheet view error "Cannot connect to the server at this time. You can continue working with this list, but some data may not be available"

    I have a List which is having around 14000 items in it.while opening that list in datasheet view it is giving error .
    Below is a summary of the issue:
    After selecting datasheet view beow error occurs:
        "Cannot connect to the server at this time.  You can continue working with this list, but some data may not be available."
        "Unable to retrieve all data."
        The item counts displays say 100 out of 14000 items.
    Exporting List to excel is giving only 2000 records out of 14000 records.
    Other Observations   -  
    This is happening to only one list on the site .There are other lists in the site whose no. of records is equal to 8000 to 9000.They are working absolutely fine without any error.
    Also, If I am saving this list as a template and creating another list with it ,then it is working absolutely fine with 14000 records,so the issue does not seem to be related with no. of records as the template list is working fine.
    I have checked the Alternate access mapping setting ,its fine.
    It should not be related to lookup,datefield or any other column as the list created from it template is working fine with all these columns.
    I checked below links also ,but doesn't seem to work in my case.
    http://social.technet.microsoft.com/forums/en-US/sharepointadminprevious/thread/974b9168-f548-409b-a7f9-a79b9fdd4c50/
    http://social.technet.microsoft.com/Forums/en-US/smallbusinessserver/thread/87077dd8-a329-48e8-b42d-d0a8bf87b082
    http://social.msdn.microsoft.com/Forums/en-US/sharepointgeneral/thread/dc757598-f670-4229-9f8a-07656346b9b0

    I have spent two days to resolve this issue. Microsoft has released two KBs with reference to this issue...but are not appearing in search results at the top.
    I am sharing my finding.
    1. First install the
    KB2552989 (Hopefully you might have already installed it. The KB detetcts it and informs the user.)
    2. Then update registry by adding new key for data fetch timeout as mentioned inKB2553007
    These two steps resolved the issue in our environment. Hope it might help others as well.
    Pradip T. ------------- MCTS(SharePoint 2010/Web)|MCPD(Web Development) https://www.mcpvirtualbusinesscard.com/VBCServer/paddytakate/profile

  • I can't download from app store apps. if i try then open account and ask me shange payment type because there is a billing problem with a previous purchase. I download one game 0.99 and nothing more! help me. How can i contact with apple?

    I can't download from app store apps. if i try then open account and ask me shange payment type because there is a billing problem with a previous purchase. I download one game 0.99 and nothing more! help me. How can i contact with apple?

    Click here and ask the iTunes Store staff for assistance.
    (102938)

Maybe you are looking for

  • Album art on iPod Touch

    Help! I've downloaded Album art for every song on my iPod Touch - although the album art matches each song correctly in my iTunes library on my desktop, about 1/3 of the songs have the incorrect album art on my iPod. For example, a song by Chicago th

  • How to set different ringtones for contacts ?

    hi!, i got my iphone friday night and ive tried setting different ringtones for different people..but it doesnt work...my normal ringtone is disturbed..when my friends call..i want it to be different for each one of them..i changed it in the contacts

  • Payee field in F-48

    Hi In the developement system when I enter the alternate payee and permitted payee field in the vendor master and then go to transaction F-48. I can see the payee field. When I try the same in the quality the payee field does not populate in F-48. pl

  • IMac G5 (Ambient Light Sensor):Mac OS X cannot be instlled on this computer

    I have 3 iMac G5's identical specs. They will not install OS X 10.5, but they ran 10.4.11 just fine. Specs: iMac G5 PowerMac8,2 CPU Type: PowerPC G5 (3.0) CPU Speed: 1.8 GHz Memory: 1 GB 2x 512MB PC 3200U-30300 DVD+R (dual layer) 5x read - DVD±RW 5x

  • My mac book is corrupting every hard drive i put in it and format.

    My buddy gave me his Mac book pro 2011 to sell (Mac worked fine 100%, no issues), so my first plan was to reformat. I bought a brand new 10.6 Mac OS off Apple.com and went to reformat. Ended up failing half way, restarted computer and the hard drive