Decrypt problem

Hello!
I have problem decripting string if the string is long.
I use
<cfset session.algo = "DES">
<cfset session.key = GenerateSecretKey(session.algo)>
<cfset session.enco = "HEX">
I have tried and other but nothing works for me.
also i do the encrypt like this: #URLEncodedFormat(Encrypt(tmpnodeid,session.key,session.algo,session.enco))#
and i pass this value as url parameter, which btw sometimes is cut.
Then i decrypt it like this: #Decrypt(URLDecode(URL.name),session.key,session.algo,session.enco)#
Can anyone please help me?
Thank you in advance!
Kind regards!

Hi
i have only change to pass the string using url in this case.
the sttring look something like this:
73467_DFGSDFGFSDGSDFG_SDFGSDFGSDFGSD_SDF_DFGSDFGS
The url is the whole encrypted string, i have checked it now.
it is like this:
in some page have outputed many links with this the string encrypted in the url.
when click some of these strings, it redirects to the same page but it checks if the url is defined and if is defined shows diffrent portion of the code.
Only english letters are used in the strings.

Similar Messages

  • An Interesting RSA Decryption Problem

    Hi,
    Here is my function which does decryption:
    private void key_load (APDU apdu)
            byte [] apduBuffer = apdu.getBuffer();
             apdu.setIncomingAndReceive();
            cipherRSA2.init(PrivateKey, Cipher.MODE_DECRYPT);
         cipherRSA2.doFinal(apduBuffer, (short)ISO7816.OFFSET_CDATA, (short)64, apduBuffer, (short)ISO7816.OFFSET_CDATA);
            apdu.setOutgoingAndSend((short)5, (short)70);          
    }I generate RSA Key and get Public Key from my applet. I encrypt
    "13131313131313130000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
    data with another tool with public key of my applet. My applet can decrypt this data perfectly.
    And I encrypt
    "FAFAFAFAFAFAFAFA0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
    " data and send it to my applet to decrypt it however my applet cant decrypt it, it returns different data..
    What is wrong with my code? Help me plese :/
    Thanks in Advance,
    Best Regards

    I am not 100% sure about this but I think the problem is because the text you are encrypting in the second example when converted to a number is a negative number. Since RSA works by converting the key and text into large integers and performing a mathematical operation on them.
    You might be better off using something like PKCS#1 padding (EM = 0x00 || 0x02 || PS || 0x00 || M where PS are non-zero bytes and M is the message). If you use the appropriate cipher, the padding will be handled for you.
    Cheers,
    Shane

  • FileVault decryption problem fixed

    I had posted on April 30 that I could not decrypt my FileVault home folder. TechToolPro 4 and Disk Utility both reported problems, but offered no solutions. Today I got a DiskWarrior CD, and it immediately found the problems and fixed them. Easy as pie. Wanted to post this in case others have similar issues with FileVault.

    Well done, and thanks for the post back.

  • File Vault decryption problem

    Hi guys,
    I'm running 2013 2.6GHz i5 13' MBP on 10.9
    I have trouble unlocking my 2TB WD external drive.
    I have encrypted it with disk utilities when i formated it 4 months ago.
    Everything worked fine up to this moment.
    I cannot unlock it, but my pasword is 100% fine.
    It keeps on shacking on me like the password is wrong.
    I used terminal to unlock it, and it seemd like the passphrase was fine, but there is some sort of error.
    MacBook-Pro-Jan:~ JRK$ diskutil cs unlockVolume 105D836C-7502-43AF-A779-88A6A2D4039D
    Passphrase:
    Started CoreStorage operation
    Logical Volume successfully unlocked
    Logical Volume successfully attached as disk2
    Error: -69842: Couldn't mount disk
    I have tried to unlock it on other machine running 10.8 but it kept on disregarding my passcode.
    Is there a way I can have my data back?
    I tried to repir the disk with diskutil, but it didn't work out.
    Please help

    Why do you have to turn off file vault encryption? Log into the old machine. Boot the new machine in Target Disk Mode and connect it. Copy your files to the new machine. You may have to repair permissions when you are done, but it shouldn't be too bad. Don't try to copy directly into your home directory. Copy the files to a neutral place, then log into the new machine, and copy them to where they should go.
    But, before you do this, are you running file vault on your new machine? If so, stop now and turn that off. It sounds like your files are important. You don't want to trust them to FileVault.
    Filevault is a clever hack - no more. It got out of control and people started putting Music libraries and iMovie productions in it and it just can't handle that.
    Create an encrypted disk image on your new machine for your sensitive files. Copy all those files into that image. If the names of the files aren't sensitive, you can even create aliases to the files inside the disk image. Then, when you double-click on the alias, it will prompt you for a password, mount the disk image, and open the file.

  • Question regarding encryption and decryption

    Hi all,
    I am doing a authentication project. In which I do encryption and decryption (AES 128 bit) in two different methods. At the time of encryption (for eg a text file ), I store the key in dat file (key.dat). And at the time of decryption, I read the key.dat and extract the key and do the decryption. This works fine. No problem with that.
    But the problem is, that the client requires that
    "No encryption keys will be written to the hard drive."
    I have to store the key somewhere to decrypt the encrypted file. Right. Without storing the key, I cannot decrypt.
    The question is (though its a foolish question) with out storing the key, can i encrypt and decrypt (in two different methods) the text file ?
    Thank You.
    Regards,
    Jay

    Hi Grant,
    Thanks for the reply. ( I am the one whom you helped to solve the encryption and decryption problem using AES )
    I will give you an overview of my project. Its an Two Factor Authentication using an USB Flash Drive.
    Admin Side : ( currently developing this part )
    Through an CPP executable file ( writen by John Hyde USB By Example author), I retrive the Manufature ID, Product ID and Serial number of the USB Flash Drive from a text file which is generated when the executable file is executed.
    From my Java application, i retrive the Manufature ID, Product ID and Serial number.The admin (through an dialog box ) enters an usernam and password . All this information ( Manufature ID, Product ID, Serial number , username and password ) using AES 128 bit encryption i write these information to encrypted file in the USB Flash drive along with the the encryption key used at the time of decryption.
    User Side: ( not yet devleoped )
    When the user plugs in the USB Flash drive, an dialog box is shown where the user enters the username and password ( assigned earlier by the admin). This username and password is checked along with the Manufature ID, Product ID and Serial number encrypted earlier and stored in the USB Flash drive. If username password ,Manufature ID, Product ID and Serial number (retrieved again by exectuing the CPP excutable file ) are correct the user is granted access.
    Whats your suggestion reagrading of storing the encryption key? I have to store the key in the USB Flash drive along with the encrypted file. But then wont an intruder (for eg ) if he gets the key and decrypt the file ?
    Client has mentioned to use AES 128 Bit encryption.
    Thank You.
    Regards,
    Jay.

  • Socket Demo works for Bell but not Verizon?

    Why does the same Socked Demo (sample from RIM JDE 4.5.0) work perfectly for Bell Mobility Blackberry 8830 (World Edition) and does not work for identical Verizon device (throws “Unable to open connection”)? Here is the sample code:
     * SocketDemo.java
     * Copyright © 1998-2008 Research In Motion Ltd.
     * Note: For the sake of simplicity, this sample application may not leverage
     * resource bundles and resource strings.  However, it is STRONGLY recommended
     * that application developers make use of the localization features available
     * within the BlackBerry development platform to ensure a seamless application
     * experience across a variety of languages and geographies.  For more information
     * on localizing your application, please refer to the BlackBerry Java Development
     * Environment Development Guide associated with this release.
    package com.rim.samples.device.socketdemo;
    import net.rim.device.api.ui.component.*;
    import net.rim.device.api.ui.container.*;
    import net.rim.device.api.ui.*;
    import java.io.*;
    import javax.microedition.io.*;
    import net.rim.device.api.system.Characters;
    import net.rim.device.api.system.RadioInfo;
     * This sample enables client/server communication using a simple implementation
     * of TCP sockets. The client application allows the user to select direct TCP as
     * the connection method.  If direct TCP is not selected, a proxy TCP connection
     * is opened using the BlackBerry MDS Connection Service. The server application
     * can be found in com/rim/samples/server/socketdemo.
    class SocketDemo extends UiApplication
        // Constants ----------------------------------------------------------------------------------------------------------
        // Using a static doesn't cost a hashtable lookup for each use (faster),
        // but it does occupy storage for the life of the app.
        private static String URL;
        private static String HELLO = "Hello";
        private static String GOODBYE = "GoodbyeAndFarewell";
        // Members ------------------------------------------------------------------------------------------------------------
        private boolean _isRunning;
        private MenuItem _go = new MenuItem("Go" , 100, 10)
            public void run()
                // Don't do anything unless there is a host name in the _host field.
                if (_host.getText().length() > 0)
                    URL = "socket://" + _host.getText() + ":4444" + (_useDirectTcpField.getChecked() ? ";deviceside=true" : "");
                    synchronized(getLockObject())
                        if ( !_isRunning )
                            _isRunning = true;
                            new ConnectThread().start();
                else
                    Dialog.ask(Dialog.D_OK, "Please enter a valid host name" );
    we can send you the rest.

    I'm a dummy.  It wasn't an SAP hookup problem.  I was having a password decryption problem.

  • Problem in using socket streams with encryption and decryption

    Hi,
    I am developing a client/server program with encryption and decryption at both end. While sending a message from client it should be encrypted and at the receiving end(server) it should be decrypted and vice versa.
    But while doing so i got a problem if i use both encryption and decryption at both ends. But If i use only encryption at one (only outputstream) and decryption at other end(only inputstream) there is no problem.
    Here is client/server pair of programs in which i am encrypting the outputstream of the socket in client side and decrypting the inputstream of the socket in server side.
    serverSocketDemo.java
    import java.io.*;
    import java.net.*;
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.util.*;
    import java.util.zip.*;
    class serverSocketDemo
         public static void main(String args[])
              try
              {                    //server listening on port 2000
                   ServerSocket server=new ServerSocket(2000);
                   while (true)
                        Socket theConnection=server.accept();
                        System.out.println("Connecting from local address : "+theConnection.getLocalAddress());
                        System.out.println("Connection request from : "+theConnection.getInetAddress());
                        //Input starts from here
                        Reader in=new InputStreamReader(getNetInStream(theConnection.getInputStream()),"ASCII");
                        StringBuffer strbuf=new StringBuffer();
                        int c;
                        while (true)
                             c=in.read();
                             if(c=='\n' || c==-1)
                                  break;
                             strbuf.append((char)c);     
                        String str=strbuf.toString();
                        System.out.println("Message from Client : "+str);
                        in.close();               
                        theConnection.close();
              catch(BindException e)
                   System.out.println("The Port is in use or u have no privilage on this port");
              catch(ConnectException e)
                   System.out.println("Connection is refused at remote host because the host is busy or no process is listening on that port");
              catch(IOException e)
                   System.out.println("Connection disconnected");          
              catch(Exception e)
         public static BufferedInputStream getNetInStream(InputStream in) throws Exception
              // register the provider that implements the algorithm
              Provider sunJce = new com.sun.crypto.provider.SunJCE( );
              Security.addProvider(sunJce);
              // create a key
              byte[] desKeyDataDec = "This encryption can not be decrypted".getBytes();
              DESKeySpec desKeySpecDec = new DESKeySpec(desKeyDataDec);
              SecretKeyFactory keyFactoryDec = SecretKeyFactory.getInstance("DES");
              SecretKey desKeyDec = keyFactoryDec.generateSecret(desKeySpecDec);
              // use Data Encryption Standard
              Cipher desDec = Cipher.getInstance("DES");
              desDec.init(Cipher.DECRYPT_MODE, desKeyDec);
              CipherInputStream cin = new CipherInputStream(in, desDec);
              BufferedInputStream bin=new BufferedInputStream(new GZIPInputStream(cin));
              return bin;
    clientSocketDemo.java
    import java.io.*;
    import java.net.*;
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.util.*;
    import java.util.zip.*;
    class clientSocketDemo
         public static void main(String args[])
              try
                   Socket theConnection=new Socket("localhost",2000);
                   System.out.println("Connecting from local address : "+theConnection.getLocalAddress());
                   System.out.println("Connecting to : "+theConnection.getInetAddress());
                   //Output starts from here               
                   OutputStream out=getNetOutStream(theConnection.getOutputStream());
                   out.write("Please Welcome me\n".getBytes());
                   out.flush();
                   out.close();
                   theConnection.close();
              catch(BindException e)
                   System.out.println("The Port is in use or u have no privilage on this port");
              catch(ConnectException e)
                   System.out.println("Connection is refused at remote host because the host is busy or no process is listening on that port");
              catch(IOException e)
                   System.out.println("Connection disconnected");          
              catch(Exception e)
         public static OutputStream getNetOutStream(OutputStream out) throws Exception
              // register the provider that implements the algorithm
              Provider sunJce = new com.sun.crypto.provider.SunJCE( );
              Security.addProvider(sunJce);
              // create a key
              byte[] desKeyDataEnc = "This encryption can not be decrypted".getBytes();
              DESKeySpec desKeySpecEnc = new DESKeySpec(desKeyDataEnc);
              SecretKeyFactory keyFactoryEnc = SecretKeyFactory.getInstance("DES");
              SecretKey desKeyEnc = keyFactoryEnc.generateSecret(desKeySpecEnc);
              // use Data Encryption Standard
              Cipher desEnc = Cipher.getInstance("DES");
              desEnc.init(Cipher.ENCRYPT_MODE, desKeyEnc);
              CipherOutputStream cout = new CipherOutputStream(out, desEnc);
              OutputStream outstream=new BufferedOutputStream(new GZIPOutputStream(cout));
              return outstream;
    Here is client/server pair in which i use both encrypting outpustream and decrypting inputstream at both ends.
    serverSocketDemo.java
    import java.io.*;
    import java.net.*;
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.util.*;
    import java.util.zip.*;
    class serverSocketDemo
         private Cipher desEnc,desDec;
         serverSocketDemo()
              try
                   // register the provider that implements the algorithm
                   Provider sunJce = new com.sun.crypto.provider.SunJCE( );
                   Security.addProvider(sunJce);
                   // create a key
                   byte[] desKeyData = "This encryption can not be decrypted".getBytes();
                   DESKeySpec desKeySpec = new DESKeySpec(desKeyData);
                   SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
                   SecretKey desKey = keyFactory.generateSecret(desKeySpec);
                   desEnc = Cipher.getInstance("DES");
                   desEnc.init(Cipher.ENCRYPT_MODE, desKey);
                   desDec = Cipher.getInstance("DES");
                   desDec.init(Cipher.DECRYPT_MODE, desKey);               
              catch (javax.crypto.NoSuchPaddingException e)
                   System.out.println(e);          
              catch (java.security.NoSuchAlgorithmException e)
                   System.out.println(e);          
              catch (java.security.InvalidKeyException e)
                   System.out.println(e);          
              catch(Exception e)
                   System.out.println(e);
              startProcess();
         public void startProcess()
              try
                   ServerSocket server=new ServerSocket(2000);
                   while (true)
                        final Socket theConnection=server.accept();
                        System.out.println("Connecting from local address : "+theConnection.getLocalAddress());
                        System.out.println("Connection request from : "+theConnection.getInetAddress());
                        Thread input=new Thread()
                             public void run()
                                  try
                                       //Input starts from here
                                       Reader in=new InputStreamReader(new BufferedInputStream(new CipherInputStream(theConnection.getInputStream(), desDec)),"ASCII");
                                       StringBuffer strbuf=new StringBuffer();
                                       int c;
                                       while (true)
                                            c=in.read();
                                            if(c=='\n'|| c==-1)
                                                 break;
                                            strbuf.append((char)c);     
                                       String str=strbuf.toString();
                                       System.out.println("Message from Client : "+str);
                                  catch(Exception e)
                                       System.out.println("Error caught inside input Thread : "+e);
                        input.start();
                        Thread output=new Thread()
                             public void run()
                                  try
                                       //Output starts from here
                                       OutputStream out=new BufferedOutputStream(new CipherOutputStream(theConnection.getOutputStream(), desEnc));
                                       System.out.println("it will not be printed");
                                       out.write("You are Welcome\n".getBytes());
                                       out.flush();
                                  catch(Exception e)
                                       System.out.println("Error caught inside output Thread : "+e);
                        output.start();
                        try
                             output.join();
                             input.join();
                        catch(Exception e)
                        theConnection.close();
              catch(BindException e)
                   System.out.println("The Port is in use or u have no privilage on this port");
              catch(ConnectException e)
                   System.out.println("Connection is refused at remote host because the host is busy or no process is listening on that port");
              catch(IOException e)
                   System.out.println("Connection disconnected");          
              catch(Exception e)
         public static void main(String args[])
              serverSocketDemo server=new serverSocketDemo();          
    clientSocketDemo.java
    import java.io.*;
    import java.net.*;
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.util.*;
    import java.util.zip.*;
    class clientSocketDemo
         private Cipher desEnc,desDec;
         clientSocketDemo()
              try
                   // register the provider that implements the algorithm
                   Provider sunJce = new com.sun.crypto.provider.SunJCE( );
                   Security.addProvider(sunJce);
                   // create a key
                   byte[] desKeyData = "This encryption can not be decrypted".getBytes();
                   DESKeySpec desKeySpec = new DESKeySpec(desKeyData);
                   SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
                   SecretKey desKey = keyFactory.generateSecret(desKeySpec);
                   desEnc = Cipher.getInstance("DES");
                   desDec = Cipher.getInstance("DES");
                   desEnc.init(Cipher.ENCRYPT_MODE, desKey);
                   desDec.init(Cipher.DECRYPT_MODE, desKey);               
              catch (javax.crypto.NoSuchPaddingException e)
                   System.out.println(e);          
              catch (java.security.NoSuchAlgorithmException e)
                   System.out.println(e);          
              catch (java.security.InvalidKeyException e)
                   System.out.println(e);          
              catch(Exception e)
                   System.out.println(e);
              startProcess();
         public void startProcess()
              try
                   final Socket theConnection=new Socket("localhost",2000);
                   System.out.println("Connecting from local address : "+theConnection.getLocalAddress());
                   System.out.println("Connecting to : "+theConnection.getInetAddress());
                   Thread output=new Thread()
                        public void run()
                             try
                                  //Output starts from here               
                                  OutputStream out=new BufferedOutputStream(new CipherOutputStream(theConnection.getOutputStream(), desEnc));
                                  out.write("Please Welcome me\n".getBytes());
                                  out.flush();
                             catch(Exception e)
                                  System.out.println("Error caught inside output thread : "+e);
                   output.start();     
                   Thread input=new Thread()
                        public void run()
                             try
                                  //Input starts from here
                                  Reader in=new InputStreamReader(new BufferedInputStream(new CipherInputStream(theConnection.getInputStream(), desDec)),"ASCII");          
                                  System.out.println("it will not be printed");
                                  StringBuffer strbuf=new StringBuffer();
                                  int c;
                                  while (true)
                                       c=in.read();
                                       if(c=='\n' || c==-1)
                                            break;
                                       strbuf.append((char)c);     
                                  String str=strbuf.toString();
                                  System.out.println("Message from Server : "+str);
                             catch(Exception e)
                                  System.out.println("Error caught inside input Thread : "+e);
                   input.start();
                   try
                        output.join();
                        input.join();
                   catch(Exception e)
                   theConnection.close();
              catch(BindException e)
                   System.out.println("The Port is in use or u have no privilage on this port");
              catch(ConnectException e)
                   System.out.println("Connection is refused at remote host because the host is busy or no process is listening on that port");
              catch(IOException e)
                   System.out.println("Connection disconnected");          
              catch(Exception e)
         public static void main(String args[])
              clientSocketDemo client=new clientSocketDemo();     
    **** I know that the CInput tries to read some header stuff thats why i used two threads for input and output.
    Waiting for the reply.
    Thank you.

    Do not ever post your code unless requested to. It is very annoying.
    Try testing what key is being used. Just to test this out, build a copy of your program and loop the input and outputs together. Have them print the data stream onto the screen or a text file. Compare the 1st Output and the 2nd Output and the 1st Input with the 2nd Input and then do a static test of the chipher with sample data (same data which was outputted), then do another cipher test with the ciphertext created by the first test.
    Everything should match - if it does not then follow the steps below.
    Case 1: IO Loops do not match
    Case 2: IO Loops match, but ciphertext 1st run does not match loop
    Case 3: IO Loops match, 1st ciphertext 1st run matches, but 2nd run does not
    Case 4: IO Loops match, both chiphertext runs do not match anything
    Case 5: Ciphertext runs do not match eachother when decrypted correctly (outside of the test program)
    Problems associated with the cases above:
    Case 1: Private Key is changing on either side (likely the sender - output channel)
    Case 2: Public Key is changing on either side (likely the sender - output channel)
    Case 3: Private Key changed on receiver - input channel
    Case 4: PKI failure, causing private key and public key mismatch only after a good combination was used
    Case 5: Same as Case 4

  • Problem Decrypting a text file using OpenPGP

    I am new in java cryptography. We have a file from vendor which needs to be decrypted. I am using the code below which gives me error after the bolded comment line. Below the code are the error messages that I get.
    Can anyone give me any assistance in telling me what is the problem.
    Thank you,
    Ed
    package cryptix.openpgp.examples;
    import cryptix.message.EncryptedMessage;
    import cryptix.message.KeyBundleMessage;
    import cryptix.message.LiteralMessage;
    import cryptix.message.Message;
    import cryptix.message.MessageException;
    import cryptix.message.MessageFactory;
    import cryptix.message.NotEncryptedToParameterException;
    import cryptix.openpgp.PGPSignedMessage;
    import cryptix.pki.KeyBundle;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.security.NoSuchAlgorithmException;
    import java.security.UnrecoverableKeyException;
    import java.util.Collection;
    public class Decrypt {
    public static void main(String[] args) {
    java.security.Security.addProvider(
    new cryptix.jce.provider.CryptixCrypto() );
    java.security.Security.addProvider(
    new cryptix.openpgp.provider.CryptixOpenPGP() );
    KeyBundle bundle = null;
    MessageFactory mf = null;
    try {
    FileInputStream in = new FileInputStream("secretkey.asc");
    mf = MessageFactory.getInstance("OpenPGP");
    Collection msgs = mf.generateMessages(in);
    KeyBundleMessage kbm = (KeyBundleMessage)msgs.iterator().next();
    bundle = kbm.getKeyBundle();
    in.close();
    } catch (IOException ioe) {
    System.err.println("IOException... You did remember to run the "+
    "GenerateAndWriteKey example first, right?");
    ioe.printStackTrace();
    System.exit(-1);
    } catch (NoSuchAlgorithmException nsae) {
    System.err.println("Cannot find the OpenPGP MessageFactory. "+
    "This usually means that the Cryptix OpenPGP provider is not "+
    "installed correctly.");
    nsae.printStackTrace();
    System.exit(-1);
    } catch (MessageException me) {
    System.err.println("Reading keybundle failed.");
    me.printStackTrace();
    System.exit(-1);
    EncryptedMessage em = null;
    try {
    FileInputStream in = new FileInputStream("C:\\Java\\enc_dec\\pgptestin.pgp");
    Collection msgs = mf.generateMessages(in);
    em = (EncryptedMessage)msgs.iterator().next();
    in.close();
    } catch (IOException ioe) {
    System.err.println("IOException... You did remember to run the "+
    "Encrypt example first, right?");
    ioe.printStackTrace();
    System.exit(-1);
    } catch (MessageException me) {
    System.err.println("Reading message failed.");
    me.printStackTrace();
    System.exit(-1);
    try {
         // System.out.println(em);
          // if fails after the below statement
    Message msg = em.decrypt(bundle,"password".toCharArray());
    PGPSignedMessage pmsg = (PGPSignedMessage)msg;
    LiteralMessage lmsg = (LiteralMessage)pmsg.getContents();
    FileOutputStream out = new FileOutputStream("C:\\Java\\enc_dec\\pgptestout.txt");
    out.write(lmsg.getTextData().getBytes());
    out.close();
    } catch (NotEncryptedToParameterException netpe) {
    System.err.println("Not encrypted to this key.");
    netpe.printStackTrace();
    System.exit(-1);
    } catch (UnrecoverableKeyException uke) {
    System.err.println("Invalid passphrase.");
    uke.printStackTrace();
    System.exit(-1);
    } catch (MessageException me) {
    System.err.println("Decrypting message failed.");
    me.printStackTrace();
    System.exit(-1);
    } catch (IOException ioe) {
              System.err.println("Writing the decrypted message failed.");
              ioe.printStackTrace();
              System.exit(-1);
    Here are the error messages:
    Exception in thread "main" java.lang.RuntimeException: NYI
         at cryptix.jce.provider.elgamal.ElGamalCipher.engineGetParameters(ElGamalCipher.java:120)
         at javax.crypto.Cipher.a(DashoA12275)
         at javax.crypto.Cipher.init(DashoA12275)
         at javax.crypto.Cipher.init(DashoA12275)
         at cryptix.openpgp.algorithm.PGPElGamal.decrypt(PGPElGamal.java:612)
         at cryptix.openpgp.packet.PGPPublicKeyEncryptedSessionKeyPacket.decrypt(PGPPublicKeyEncryptedSessionKeyPacket.java:189)
         at cryptix.openpgp.provider.PGPEncryptedMessageImpl.decrypt(PGPEncryptedMessageImpl.java:186)
         at cryptix.openpgp.provider.PGPEncryptedMessageImpl.decrypt(PGPEncryptedMessageImpl.java:315)
         at cryptix.openpgp.examples.Decrypt.main(Decrypt.java:118)
    Message was edited by:
    eidasharif
    Message was edited by:
    eidasharif
    Message was edited by:
    eidasharif
    Message was edited by:
    eidasharif
    Message was edited by:
    eidasharif
    Message was edited by:
    eidasharif
    Message was edited by:
    eidasharif
    null

    You have to download and install something called "Unlimited strength jurisdiction policy files 5.0", is the solution por the NYI (Not Yet implemented) problem. It worked in my case (you can download the file from Sun, and read the readme to know how to install it)

  • Problem in decrypting the code

    I have written the following code for decryption
    String inputString = "5B5E0A35FBD295AB923D872BC1CBCF45307FACDA881978ACBE65C21FDF63658F61B48EE3C99BBDB0E51B9F1498289305526D82EA2D52D681993E3AD499F2887E82D35CC9CD9EF436B8A9E587CC3E2A50CABFAB39824632F7ECDCDFAE7AC0A7BEAD0767D83D3E3E0BFAAA3F053E5678901ABCDE1B8581310F6513D0547290F6C9E";
    String inputKey = "243fbde01df0684ed5b49f1035137225fcca9ba960e5e979e9cb8bee345f2f258678901acbd05c4f084c0373d3300432b186e03c56bd93bacb4ba634ad2b407b18f2985497eaa1e635152d7e9814ee469a94115109841758f67e61885d412dcc47efd670e156700e6df84dcadd41bc0588a8b4babcde54387d742e96308d66a1";
    String labelString = "0000000819";
    byte [] input = hexstringToByteArray(inputString);
    byte[] keyBytes = hexstringToByteArray(inputKey);
    byte[] label = padWithZeros(hexstringToByteArray(labelString));
    Security.addProvider(new BouncyCastleProvider());
    BigInteger privateKeyInt = new BigInteger(keyBytes);
    Cipher bcCipher = Cipher.getInstance("RSA/NONE/OAEPWithSHA1AndMGF1Padding", "BC");
    OAEPParameterSpec defaultOaepSpec = OAEPParameterSpec.DEFAULT;
    OAEPParameterSpec oaepSpec = new OAEPParameterSpec(defaultOaepSpec.getDigestAlgorithm(),
    defaultOaepSpec.getMGFAlgorithm(),
    defaultOaepSpec.getMGFParameters(),
    new PSource.PSpecified(label));
    java.security.KeyFactory keyFactory = java.security.KeyFactory.getInstance("RSA", "BC");
    java.security.Key bcPrivateKey = keyFactory.generatePrivate((new RSAPrivateKeySpec(privateKeyInt,new BigInteger("3"))));
    // SecureRandom = new SecureRandom()
    bcCipher.init(Cipher.DECRYPT_MODE, bcPrivateKey,oaepSpec);
    byte[] em = bcCipher.doFinal(input);
    System.out.println(byteArrayToHexString(em));
    Output :-
    Exception in thread "main" java.lang.IllegalArgumentException: unknown parameter type.
         at org.bouncycastle.jce.provider.JCERSACipher.engineInit(JCERSACipher.java:247)
         at javax.crypto.Cipher.init(DashoA13*..)
         at javax.crypto.Cipher.init(DashoA13*..)
         at PublicMain.main(PublicMain.java:44)
    I have to use OEAP padding
    pls help me solve this problem thanks in advance

    I have written this code for decryption and tried the earlier problem by resolving proper jar file
    String inputString = "5B5E0A35FBD295AB923D872BC1CBCF45307FACDA88598153052DC21FDF6365345678AEBCC99BBDB0E51B9F1498289305526D82EA2D52D681993E3AD499F2887E82D35CC9CD9EF436B8A9E587CC3E2A50CABFAB39824632F7ECDCDFAE7AC0A7BEAD0767D83D3E3E0BFAAA3F";
    /* private key*/String inputKey = "243fbde01df0684ed5b49f1035137225fcca9ba960e5e979e9cb8bee345f2f258344795904605c4f084c037456cabefc4186e03c56bd93bacb4ba634ad2b407b18f2985497eaa1e635152d7e9814ee469a94115109841758f67e61885d412dcc47efd670e156700e6df84dcadd41bc0588a8b4b19bb509409d742e96308d66a1";
    String labelString = "40156ca44f22db70b7f852eec9d57ce10000000913"; //Unencrypted header may change
    String publicKey = "9e4004e8ab15bad1ec47059b86a50f5f46334da008fded08b7fe300d1a14a8f926d8abcde13456786282335c03eee04559861043b8a1f7db4ee79f2a17a8aff278dee0ebc997a48668fb99ec6d901b3e5723318bbdc0586f05196b4603b36b2d8eb62b52395684b26d50bb6df19bc8b72bb7eec359a68651842e739e52cbc05027";
    byte [] input = hexstringToByteArray(inputString);
    byte[] keyBytes = hexstringToByteArray(inputKey);
    byte[] publicKeyBytes = hexstringToByteArray(publicKey);
    byte[] label = hexstringToByteArray(labelString);
    System.out.println(input.length);
    Security.addProvider(new BouncyCastleProvider());
    BigInteger privateKeyInt = new BigInteger(keyBytes);
    BigInteger publicKeyInt = new BigInteger(publicKeyBytes);
    Cipher bcCipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding", "BC");
    OAEPParameterSpec defaultOaepSpec = OAEPParameterSpec.DEFAULT;
    OAEPParameterSpec oaepSpec = new OAEPParameterSpec(defaultOaepSpec.getDigestAlgorithm(),
    defaultOaepSpec.getMGFAlgorithm(),
    defaultOaepSpec.getMGFParameters(),
    new PSource.PSpecified(label));
    java.security.KeyFactory keyFactory = java.security.KeyFactory.getInstance("RSA", "BC");
    java.security.Key bcPrivateKey = keyFactory.generatePrivate((new RSAPrivateKeySpec(publicKeyInt,privateKeyInt)));
    // SecureRandom = new SecureRandom()
    /* PrivateKey p = keyFactory.generatePrivate((new RSAPrivateKeySpec(publicKeyInt,privateKeyInt)));
    System.out.println(p.toString());*/
    bcCipher.init(Cipher.DECRYPT_MODE, bcPrivateKey,oaepSpec);
    /*RSAEngine rsa = new RSAEngine();
    OAEPEncoding a = new OAEPEncoding(rsa,new SHA1Digest(),label);
    rsa.init(false, (CipherParameters) p);
    byte[] output = a.decodeBlock(input, 0, input.length); */
    byte[] em = bcCipher.doFinal(input);
    System.out.println(byteArrayToHexString(em));
    But now it is giving the following exception :
    Exception in thread "main" org.bouncycastle.crypto.DataLengthException: input too large for RSA cipher.
         at org.bouncycastle.crypto.engines.RSACoreEngine.convertInput(Unknown Source)
         at org.bouncycastle.crypto.engines.RSABlindedEngine.processBlock(Unknown Source)
         at org.bouncycastle.crypto.encodings.OAEPEncoding.decodeBlock(Unknown Source)
         at org.bouncycastle.crypto.encodings.OAEPEncoding.processBlock(Unknown Source)
         at org.bouncycastle.jce.provider.JCERSACipher.engineDoFinal(Unknown Source)
         at javax.crypto.Cipher.doFinal(DashoA13*..)
         at PublicMain.main(PublicMain.java:55)
    Please help me correcting the input length
    Thanks in advance

  • Problem when decrypting an encrypted xml data with arabic data

    Hi all
    I have problem in decryption an encrypted Xml file. because my Xml file contains utf-8 characters, this problem occurs. after many proccess on Xml data the following code throws an Exception:
    try {
    // Works if the content is a single child element.
    byte [] a = decbit.getBytes("UTF-8");
    ByteArrayInputStream bais2 = new ByteArrayInputStream(a);
    Document decdoc = docBuilder.parse(bais2);
    Node decNode =
    encDoc.importNode(decdoc.getFirstChild(), true);
    edata.getParentNode().replaceChild(decNode,edata);
    }catch(org.xml.sax.SAXParseException spe) {
    //In case the content is plain text
    //or a group of child elements
    Text decText = encDoc.createTextNode(decbit);
    edata.getParentNode().replaceChild(decText,edata);
    decString = (getString((XmlDocument)encDoc));
    at the line with code "Document decdoc = docBuilder.parse(bais2); " an Exception occurs with message :
    org.xml.sax.SAXParseException: Illegal character at end of document, &#x3c;.
    whereas when I debug the project the filed "decbit", contains correct data. any way, in order to the exception, the control move to "catch" block and create a Text Node but the problem is the replaced data is like this:
    <id root="588588588" extension="" displayable="false" /><beneficiaryOf typeCode="BEN">
    <policyOrAccount classCode="COV" moodCode="EVN">
    <id xsi:type="II" root="855855855" extension="" displayable="false" />
    <author typeCode="AUT">
    <carrierRole classCode="UNDWRT">
    <id root="6548888888" extension="" displayable="false" />
    </carrierRole>
    </author>
    </policyOrAccount>
    </beneficiaryOf>
    as you can see, tha "<" characters are < and the ">" characters are >
    this really exhausted me, please help me out.
    thank you, any help will be appreciated
    regards
    Mohammad

    Hi Naveen,
    In sxmb_moni the content transmitted to the adapter(RFC)is as follows
    <?xml version="1.0" encoding="UTF-8" ?>
    - <ns:ZRFID_EQUIP xmlns:ns="urn:sap-com:document:sap:rfc:functions">
    - <RECORDS>
    - <item>
      <FLOC>f1-01-01</FLOC>
      <RFID_NO>I006</RFID_NO>
      </item>
    - <item>
      <FLOC>f1-01-02</FLOC>
      <RFID_NO>I002</RFID_NO>
      </item>
    - <item>
      <FLOC>f1-01-03</FLOC>
      <RFID_NO>I003</RFID_NO>
      </item>
    - <item>
      <FLOC>f1-01-04</FLOC>
      <RFID_NO>I004</RFID_NO>
      </item>
    - <item>
      <FLOC>f1-01-05</FLOC>
      <RFID_NO>I005</RFID_NO>
      </item>
    - <item>
      <FLOC>f1-01-06</FLOC>
      <RFID_NO>I001</RFID_NO>
      </item>
      </RECORDS>
      </ns:ZRFID_EQUIP>
    At r/3 side the field floc and rfid_no gets mapped to floc which is of char30
    eg floc=f1-01-01I006
       rfid_no=

  • Problem in encryption and decryption

    hello everyone..
    I'm a new bee in this forum.I don't know weather it is the right place to put my query or some other place.I saw in this forum people putting up their problems regarding the java development.So i came up with my problem.
    I'm working on a web application using jdk1.5,struts 1.1,apache tomcat5.5 and mysql5.2.For user registering and loging i'm using a encryption /decryption code to encrypt the password to the database and decrypt it back during userid and password verification in the code.The code of the encryption/decryption is as follows...
    import java.util.Random;
    public class Crypt
         String key = "uy67jwq98JWPOI99dj9021032amiet";
         public String strencrypt(String str)
              String result="";
              int i = 0, current = 0;
              Random r = new Random();
              current = r.nextInt(30);
              if(current<10)     result = "0";
              result = result + current;
              if(((key.charAt(current)+ "").hashCode() + str.length()) < 10)
                   result = result + "0";
              result = result + (char)((key.charAt(current)+ "").hashCode() + str.length());
              while(i<str.length())
                   result = result + ( (char)( ((str.charAt(i)+"").hashCode()) + ((key.charAt(current++)+"").hashCode()) ) );
                   if(current==key.length())     current=0;
                   i++;
              while(i<key.length())
                   result = result + ( (char) ((r.nextInt(30)) + ((key.charAt(current++)+"").hashCode())) );
                   if(current==key.length())     current=0;
                   i++;
              return result;
         public String strdecrypt(String str)
              int current=0, len = 0, i = 0, header = 3;
              String result="", slen = "";
              current = Integer.parseInt(str.substring(0,2));
              slen = "" + (str.charAt(2)+"").hashCode();
              len = (Integer.parseInt(slen)) - ((key.charAt(current)+"").hashCode());
              i = header;
              while(i<(header + len))
                   result = result + ( (char) ((str.charAt(i)+ "").hashCode() - ((key.charAt(current++)+"").hashCode())) );
                   if(current == key.length())
                   current=0;
                   i++;
              return result;
    But the problem that i'm facing is regarding the the database mysql5.2 is installed in two operating system ie windows xp and windows 2000 server.When i try to connect my web application to the windows xp installed database mysql5.2 and try creating a new user and then try to login ,the loging fails.Even i have found out the reason.The above pasted code couldn't decrypt properly.Heres what i get when i System.out.println(""); the data retrived from the database...I'm pasting it also...
    s retriving from db=16l&#9574;&#9616;&#8976;?��??7pmofv??A?l?rNCdhhLAK
    password coming from welcome.jsp=gtplpune
    c.strencrypt(password)=14A��&#9560;&#9555;&#8976;��?LH7}?te???HG&#8962;??QFUkPj]
    c.strdecrypt(s)=gtp&#9788;pu&#9788;&#9792;
    encryption mismatch
    see that teh password coming from welcome/jsp is gtplpune
    and the password after decryption comingh from database is gtp&#9788;pu&#9788;&#9792;....
    where u can see some letter such as l,n,e could not be decrypted or in some other format....So the code is unable to validate teh user.....
    But teh strange thing is that when i'm using the mysql5.2 installed in windows 2000 server everything seems to work fine.There no problem in encryption or decryption and everything works fine...So anyone of you have any idea what can be the raeson for it.And what can be the probable solution to it.I'm waiting for ur replies which i guess will help me out.
    Thank you
    sabyasachi

    It's a shame nobody above gave you the correct.
    answer.
    You shouldn't encrypt passwords and store them in a
    database at all..
    You should digest them and store the digests,
    and digest whatever the user enters in the password
    field and compare the digests.
    The way you have it now is a major security
    problem.
    Hey i didn't know this..I encrypted the password in base 64 format and then store it in mysql db..then i retrive it frm db in encrypted format and then decrypt it and then match it when the user logs in..well thanks for ur approach..i will now try using the digest as u mentioned..well i'm not aware of it so i need to study this first...

  • XML deserialize and decrypting encoding problem. Please help me

    This is my first topic here, so at first I'd like to say "Hi" everyone and apologise for my bad english ;)
    I have just finished my new application about signing/checking and encrypting/decrypting XML files. I use Apache XML Security packages to do this.
    Everything works fine, instead of one...
    I'm Polish and sometimes I have to encrypt or decrypt XML which includes polish letters like: '&#261;' , '&#281;', '&#322;' and some others... If I encrypt such file, it succeeds. The problem is when I try to decrypt such an encrypted file. I recieve an error like :
    "[Fatal Error] :2:7: An invalid XML character (Unicode: 0x19) was found in the element content o
    f the document.
    gov.mf.common.exceptions.SenderException: E_SENDER_DECRYPTION
    at gov.mf.common.xml.encryption.EncryptTool.decrypt(Unknown Source)
    at gov.mf.CERBER.TestCBR.main(Unknown Source)
    Caused by: org.apache.xml.security.encryption.XMLEncryptionException: An invalid XML character
    (Unicode: 0x19) was found in the element content of the document.
    Original Exception was org.xml.sax.SAXParseException: An invalid XML character (Unicode: 0x19)
    was found in the element content of the document.
    at org.apache.xml.security.encryption.XMLCipher$Serializer.deserialize(Unknown Source)
    at org.apache.xml.security.encryption.XMLCipher.decryptElement(Unknown Source)
    at org.apache.xml.security.encryption.XMLCipher.doFinal(Unknown Source)
    ... 2 more
    What's wrong? My XML document is UTF-8 encoded, with or without BOM. I wrote in in Notepad++ or any other editior which has UTF-8 encoding.
    I'm parsing my XML with DOM. There is an interesting line in an error above like: " at org.apache.xml.security.encryption.XMLCipher$Serializer.deserialize(Unknown Source)" , do you know that?
    Everything is fine when I try to encrypt/decrypt '�' or '&#324;', but things go wrong with '&#261;', '&#281;', '&#322;' and others... I also managed to encrypt and decrypt '&#322;' but unfortunately, after decryption '&#322;' turns into 'B'. It obviously an encoding problem, but how to fix it?
    I would be really thankfull if some of You guys would help me.
    Looking forward fo any answers.
    Matthew
    Message was edited by:
    matthew_pl

    Hi once again.
    I still don't havy any solution to my problem. I used Apache XML Security examples to encrypt/decrypt my XML document with Polish charaters but I also recieve the same error. What's wrong?
    Here is some code:
    ----- Parsing XML do Document ------
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
         //Bardzo wazna linijka - bless TEK ;)
         factory.setNamespaceAware(true);
         DocumentBuilder builder;
         builder = factory.newDocumentBuilder();
         File f = new File(Const.FILE_IN_PATH + File.separator + Const.FILE_IN);     
         org.w3c.dom.Document doc = builder.parse(f);
    ---------- Encrypting & Decrypting XML document (whole class) -------------
    import java.io.*;
    import java.security.*;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.DESedeKeySpec;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.apache.xml.security.keys.KeyInfo;
    import org.apache.xml.security.utils.EncryptionConstants;
    import org.apache.xml.security.encryption.XMLCipher;
    import org.apache.xml.security.encryption.EncryptedData;
    import org.apache.xml.security.encryption.EncryptedKey;
    public class EncryptTool
    private PublicKey publicKey;     
    private PrivateKey privateKey;
    static
    org.apache.xml.security.Init.init();
    public EncryptTool()
         publicKey = KeyStores.getCerberPublicKey();
         privateKey = KeyStores.getCerberPrivateKey();
    public Document encrypt(Document doc, String sufix)
    try
         byte[] passPhrase = "24 Bytes per DESede key!".getBytes("UTF-8");
         DESedeKeySpec keySpec = new DESedeKeySpec(passPhrase);
         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
         SecretKey secretKey = keyFactory.generateSecret(keySpec);
         XMLCipher keyCipher = XMLCipher.getInstance(XMLCipher.RSA_v1dot5);
         keyCipher.init(XMLCipher.WRAP_MODE, publicKey);
         EncryptedKey encryptedKey = keyCipher.encryptKey(doc, secretKey);
              Element elementToEncrypt = (Element) doc.getDocumentElement();
              System.out.println("Szyrfuj&#281;: " + elementToEncrypt.getTextContent());
              XMLCipher xmlCipher = XMLCipher.getInstance(XMLCipher.TRIPLEDES);
              xmlCipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
              EncryptedData encryptedDataElement = xmlCipher.getEncryptedData();
              KeyInfo keyInfo = new KeyInfo(doc);
              keyInfo.add(encryptedKey);
              encryptedDataElement.setKeyInfo(keyInfo);
              boolean encryptContentsOnly = true;
              xmlCipher.doFinal(doc, elementToEncrypt, encryptContentsOnly);
              // output the resulting document
              String [] parts = Const.FILE_IN.split("\\.");
              String saveAs = Const.FILE_OUT_PATH + File.separator + parts[0] + sufix + "." + parts[1];
              OutputStream os = new FileOutputStream(saveAs);
              XMLUtil.sameXMLtoFile(doc, os);
    } catch (Exception ex)
         throw new TestCBRException("E_CERBER_ENCRYPTION", ex);
    return doc;
    public void decrypt(Document doc, String sufix) throws SenderException
    try
              String namespaceURI = EncryptionConstants.EncryptionSpecNS;
         String localName = EncryptionConstants._TAG_ENCRYPTEDDATA;
         int ile = doc.getElementsByTagNameNS(namespaceURI, localName).getLength();
         if (ile == 0) throw new SenderException("E_SENDER_DECRYPTION_NEEDED");
         for(int i=0; i < ile; i++)
         Element encryptedDataElement = (Element) doc.getElementsByTagNameNS(namespaceURI, localName).item(0);
         XMLCipher xmlCipher = XMLCipher.getInstance();
         xmlCipher.init(XMLCipher.DECRYPT_MODE, null);
         xmlCipher.setKEK(privateKey);
         xmlCipher.doFinal(doc, encryptedDataElement);
                   String [] parts = Const.FILE_IN.split("\\.");
                   String saveAs = Const.FILE_OUT_PATH + parts[0] + sufix + "." + parts[1];
                   OutputStream os = new FileOutputStream(saveAs);
                        XMLUtil.saveXMLtoFile(doc, os);
    } catch (SenderException ex) {
         throw ex;
    } catch (Exception ex) {
         throw new SenderException("E_SENDER_DECRYPTION", ex);
    Please help me. I'm going into madness what's wrong with it...

  • Problem decrypting the encryptedKey at server side

    Hi,
    Just a bit of background about my environment and problem: I am using JBoss 4.2.3 and JBoss metro for my web services. I am trying to test my web service with security using SOAtest6.2. I also have a servlet based client for my web service. I have enfored WS-Security policy using WSIT. Now when i use servlet based client everything works perfectly ok, however when i use SOAtest6.2 using the same keystore and truststore (which i have used for servlet based client) it doesn't seem to be working. I am getting the following error at server side:
    ERROR [com.sun.xml.wss.logging.impl.opt.crypto] WSS1913: Key used to decrypt EncryptedKey cannot be null
    ERROR [com.sun.xml.wss.logging.impl.opt.crypto] WSS1927: Error occured while decrypting EncryptedKey
    I don't know where things are going wrong here.
    Not sure what other information i should provide at the moment, however i will provide any information as and when required.
    Thanks

    Are there any exceptions thrown??
    And where are you trying to run your application?

  • Problems Transcoding DVD TV Box Sets W/DVD Decrypter+Videora

    I'm having problems decrypting (with dvd decrypter) and/or transcoding (using videora) Battlestar Galactica.
    I realized that for at least two discs, only half of the episodes were converted. (ie for Disc 2, only the last two of four episodes were decrypted/transcoded).
    I haven't had any issues with the first full season of Lois & Clark though. The only difference is that I was on another computer using the same two programs and settings.
    Is this normal?

    Your question can best be answered at the software developers website:
    Videora Forum - http://www.pspvideo9.com/forums/index.php?c=8
    Also go here to learn how to handle episode discs.
    http://www.digitalfaq.com/dvdguides/dvdcopy/dvdshrink/dvdshrink.htm

  • What is the problem with  AES decryption here ?

    hi to all
    code here returns an exception and really i need to get encryption,decryption working properly
    i tried many more to fix this problem but still i cant solve it since decryption always make exception or wrong result
    here is the code :
    import java.io.UnsupportedEncodingException;
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.KeyGenerator;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;
    import javax.swing.JOptionPane;
    public class CryptoAES {
    static Cipher aesCipher ;
    static SecretKey aesKey;
    static String strCipherText ;
    public CryptoAES() {
    try {
    String dataToEncrypt ;
    String strDecryptedText;
    //Step 1. Generate an AES key
    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(128);
    byte[] loginId = "lord".getBytes();
    byte[] preSharedKey = "ACME0o12hi0qg28cime8rMET9qxl".getBytes();
    byte[] encodedKey = new byte[loginId.length + preSharedKey.length];
    System.arraycopy(loginId, 0, encodedKey, 0, loginId.length);
    System.arraycopy(preSharedKey, 0, encodedKey, loginId.length, preSharedKey.length);
    aesKey = new SecretKeySpec(encodedKey, "AES");
    //Step2. Create a Cipher
    aesCipher = Cipher.getInstance("AES");
    } catch (NoSuchPaddingException ex) {
    JOptionPane.showMessageDialog(null, ex.getMessage());
    } catch (NoSuchAlgorithmException ex) {
    JOptionPane.showMessageDialog(null, ex.getMessage());
    String AunEncrypt(String text) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException{
    //Step 3. Initialize the Cipher for Encryption
    aesCipher.init(Cipher.ENCRYPT_MODE,aesKey);
    //Step 4. Encrypt the Data
    byte[] byteDataToEncrypt = text.getBytes("UTF16");
    byte[] byteCipherText = aesCipher.doFinal(byteDataToEncrypt);
    // strCipherText = new BASE64Encoder().encode(byteCipherText);
    return new String(byteCipherText);
    String AunDecrypt(String encText) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException{ 
    aesCipher.init(Cipher.DECRYPT_MODE, aesKey);
    byte[] byteDecryptedText = aesCipher.doFinal(encText.getBytes("UTF16"));
    return new String(byteDecryptedText);
    public static void main(String args[]){
    try {
    String dataToEncrypt = "want to encrypt this text" ;
    CryptoAES c = new CryptoAES();
    System.out.println( "Encrypted Text : " + c.AunEncrypt(dataToEncrypt));
    System.out.println( "Decrypted Text : " + c.AunDecrypt(c.AunEncrypt(dataToEncrypt)));
    } catch (UnsupportedEncodingException ex) {
    Logger.getLogger(CryptoAES.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
    JOptionPane.showMessageDialog(null, ex.getMessage());
    } catch (IllegalBlockSizeException ex) {
    JOptionPane.showMessageDialog(null, ex.getMessage());
    } catch (BadPaddingException ex) {
    JOptionPane.showMessageDialog(null, ex.getMessage());
    thanks in advance

    forgive me i m new to the forums import java.io.UnsupportedEncodingException;
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.KeyGenerator;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;
    import javax.swing.JOptionPane;
    public class CryptoAES {
         static Cipher aesCipher ;
         static SecretKey aesKey;
         static String strCipherText ;
            public CryptoAES() {
            try {
                String dataToEncrypt ;
                String strDecryptedText;
                //Step 1. Generate an AES key
                KeyGenerator keyGen = KeyGenerator.getInstance("AES");
                keyGen.init(128);
                byte[] loginId = "lordor".getBytes();
                byte[] preSharedKey = "ACMko-E0iogc-ime8rM-ET9qxl".getBytes();
                byte[] encodedKey = new byte[loginId.length + preSharedKey.length];
                System.arraycopy(loginId, 0, encodedKey, 0, loginId.length);
                System.arraycopy(preSharedKey, 0, encodedKey, loginId.length, preSharedKey.length);
                aesKey = new SecretKeySpec(encodedKey, "AES");
                //Step2. Create a Cipher
                aesCipher = Cipher.getInstance("AES");
            } catch (NoSuchPaddingException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage());
            } catch (NoSuchAlgorithmException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage());
         String EncryptTxt(String text) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException{
            //Step 3. Initialize the Cipher for Encryption
            aesCipher.init(Cipher.ENCRYPT_MODE,aesKey);
            //Step 4. Encrypt the Data
            byte[] byteDataToEncrypt = text.getBytes();
            byte[] byteCipherText = aesCipher.doFinal(byteDataToEncrypt);
       //     strCipherText = new BASE64Encoder().encode(byteCipherText);
            return new String(byteCipherText);
        String DecryptTxt(String encText) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException{
            aesCipher.init(Cipher.DECRYPT_MODE, aesKey);
            byte[] byteDecryptedText = aesCipher.doFinal(encText.getBytes());
            return new String(byteDecryptedText);
        public static void main(String args[]){
            try {
                   String dataToEncrypt = "want to encrypt this want to encrypt this want to encrypt this  this want to encrypt this  this want to encrypt this  this want to encrypt this want to encrypt want to encrypt want to encrypt want to encryptwant to encryptwant to encryptwant to encryptwant to encryptwant to encryptwant to encryptwant to encryptwant to encryptwant to encryptwant to encryptwant to encryptwant to encryptwant to encrypt" ;
                   CryptoAES c = new CryptoAES();
                   System.out.println( "Encrypted Text : " + c.EncryptTxt(dataToEncrypt));
                   System.out.println( "Decrypted Text : " + c.DecryptTxt(c.EncryptTxt(dataToEncrypt)));
                } catch (UnsupportedEncodingException ex) {
                    JOptionPane.showMessageDialog(null, ex.getMessage()+ex.getStackTrace());
                } catch (InvalidKeyException ex) {
                    JOptionPane.showMessageDialog(null, ex.getMessage()+ex.getStackTrace());
                } catch (IllegalBlockSizeException ex) {
                    JOptionPane.showMessageDialog(null, ex.getMessage()+ex.getStackTrace());
                } catch (BadPaddingException ex) {
                    JOptionPane.showMessageDialog(null, ex.getMessage()+ex.getStackTrace());
    Edited by: mena.sam6 on Jun 1, 2009 6:35 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Maybe you are looking for

  • When are you applicable to get a replacement for an iphone 5?

    I got my iphone 5 about 7 months ago and I have a 1 year warranty on it. It's been a while and my phone has been starting to act up in ways of: The lock button not working unless pressed hard on the left side When i'm typing a message the screen tend

  • The no of character in alv top of page

    i have to display k: Share\MM_SCUBCode_PDAtxt_Upload\OUT-1090000017-200903171823 - LY 2.txt in the alv top of page but it is taking k: Share\MM_SCUBCode_PDAtxt_Upload\OUT-1090000017-200903171823. any idea how to do it please check my code form top_of

  • Create a new button in a sap-standard-view WD4A

    In webdynpro for ABAP I have changed the text on an existing button in a sap-standard-view using configuration (change application configuration/go to component configurator/implicit configuration and then on the view-component change the text) it wo

  • Saving zip code data with PHP - best practices

    I have built my client an application that analyzes uploaded zip codes for matches with a standard set of zips. These uploaded zips can be one at a time, or a copy/paste from an XLS file (just 5 digit ZIPs). They are now asking me to save these uploa

  • Sub-Project Creation using CSOM in project server 2013

    Hi All, We are able to create a project using CSOM,  we would like to create a sub project and template too, however we are unable to set the project type. am I missing anything? Any pointer will be helpful. Thanks in Advance, Ritesh Gade