Javax.crypto.* issues

Does anyone have a link to where I could see the source code of classes in this package? I have already unzipped the java source code and cannot find the entire javax.crypto folder. Any suggestions? Thank you for your efforts.

Your second class is getting a Cipher with whatever the default mode/padding are for the various algorithms. The first is making the mode and padding requests explicit, and is failing on some of them.
That being said - in my environment (1.4.2, Win2K, unlimited-strength policy files in place) the only ones that fail are 8, 10, 11, 16, 18, and 19. Looks like the SunJCE only supports CBC when using PBE encryption.
I can't explain why your setup seems to be failing everything except ECB and OFB padding.
Grant

Similar Messages

  • Issue with javax.crypto.SecretFactory

    I am getting the following error in the following code:
    DESedeKeySpec spec = new DESedeKeySpec( baKey );
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstanc( "DESede" );
    Here is the error message:
    java.security.NoSuchAlgorithmException: Algorithm DESede not available
         at javax.crypto.SunJCE_b.a(DashoA6275)
         at javax.crypto.SecretKeyFactory.getInstance(DashoA6275)
    I will really appreciate any help.

    Looks like it has something to do with the jdk installed on my machine. I changed the location of jdk and I get the following error:
    javax.crypto.BadPaddingException: Given final block not properly padded
         at com.sun.crypto.provider.DESedeCipher.engineDoFinal(DashoA6275)
         at com.sun.crypto.provider.DESedeCipher.engineDoFinal(DashoA6275)
         at javax.crypto.Cipher.doFinal(DashoA6275)

  • Unable to Decrypt the data properly using javax.crypto class and SunJCE

    Hello all,
    I am not new to Java but new to this forums
    but and JCE and i wanted to write a program that Encrypts a file and also another program that decrypts it. As far Encryption is concerned i have been successful but When it comes to Decryption things aren't looking bright i have some or the other Problem with it. plz help me out .
    Here is the Code for my Programs
    Encryption
    Code:
    import java.io.*;
    import javax.crypto.*;
    import javax.crypto.spec.SecretKeySpec;
    import java.security.*;
    import javax.swing.*;
    class MyJCE
    public static void main(String args[])throws Exception
    Provider sunjce = new com.sun.crypto.provider.SunJCE();
    Security.addProvider(sunjce);
    JFileChooser jfc = new JFileChooser();
    int selection= jfc.showOpenDialog(null);
    if(selection==JFileChooser.APPROVE_OPTION)
    FileInputStream fis = new FileInputStream(jfc.getSelectedFile());
    System.out.println("Selected file " + jfc.getSelectedFile());
    try{
    KeyGenerator kg = KeyGenerator.getInstance("DESede");
    SecretKey key= kg.generateKey();
    byte[] mkey=key.getEncoded();
    System.out.println(key);
    SecretKeySpec skey = new SecretKeySpec(mkey, "DESede");
    Cipher cipher=Cipher.getInstance("DESede/ECB/NoPadding");
    cipher.init(Cipher.ENCRYPT_MODE,skey);
    byte[] data= new byte[fis.available()];
    //reading the file into data byte array
    byte[] result= cipher.update(data);
    byte[] enc= new byte [fis.read(result)];
    System.out.println("Encrypted =" + result);
    File fi= new File("/home/srikar/Encrypted");
    FileOutputStream fos= new FileOutputStream(fi);
    fos.write(enc);
    fos.close();
    byte[] encodedSpeckey = skey.getEncoded();
    FileOutputStream ks= new FileOutputStream("./key.txt");
    ks.write(encodedSpeckey);
    System.out.println("Key written to a file");
    }//try
    catch(Exception ex)
    ex.printStackTrace();
    }//catch
    }This Creates a Encrypted File. and a Encrypted key.txt
    Code:
    import java.io.*;
    import javax.crypto.*;
    import javax.crypto.spec.SecretKeySpec;
    import java.security.*;
    import javax.swing.*;
    class Decrypt
    public static void main(String[] args)
    try
    JFileChooser jfc = new JFileChooser();
    int selection= jfc.showOpenDialog(null);
    if(selection==JFileChooser.APPROVE_OPTION)
    FileInputStream fis = new FileInputStream(jfc.getSelectedFile());
    System.out.println("Selected file " + jfc.getSelectedFile());
    //Read from the Encrypted Data
    int ll= (int)jfc.getSelectedFile().length();
    byte[] buffer = new byte[ll];
    int bytesRead=fis.read(buffer);
    byte[] data= new byte[bytesRead];
    System.arraycopy(buffer,0,data,0,bytesRead);
    //Read the Cipher Settings
    FileInputStream rkey= new FileInputStream("./key.txt");
    bytesRead = rkey.read(buffer);
    byte[] encodedKeySpec=new byte[bytesRead];
    System.arraycopy(buffer,0,encodedKeySpec,0,bytesRead);
    //Recreate the Secret Symmetric Key
    SecretKeySpec skeySpec= new SecretKeySpec(encodedKeySpec,"DESede");
    //create the cipher for Decrypting
    Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");
    cipher.init(Cipher.DECRYPT_MODE,skeySpec);
    byte[] decrypted= cipher.update(data);
    FileOutputStream fos= new FileOutputStream("/home/srikar/Decrypted");
    fos.write(decrypted);
    }//if
    }//try
    catch(Exception e)
    e.printStackTrace();
    }//catch
    }//main
    }//classthis Decrypt.java is expected to decrypt the above encrypted file but this simply creates a plaintext file of the same size as the Encrypted file but its contents are unreadable.
    Or I endup with Exceptions like BadPadding or IllegalBlockSize Exception if i use any other Algorithm .
    Please help out
    thanx in advance

    Srikar2871 wrote:
    Well thanx for ur reply but
    As i said there are No issues with ENCRYPTION and am getting an Encrypted file exactly of the same size as that of the original file and NOT as null bytes and Even am able to get a Decrypted file of again the same size of the Encrypted File but this time that data inside is in unreadable format.I ran your code EXACTLY* as posted and the contents of the file when viewed in a Hex editor was
    00 00 00 00 00 00 00 00 00 00 00 00 00 00 00So unless you are running different code to what you have posted, your file will look the same.
    Cheers,
    Shane

  • AES -javax.crypto.BadPaddingException: Given final block notproperly padded

    I have an Encrypt Util class to encrypt and decrypt CLOB content in the database(Oracle). During encryption there is no error/exception thrown., But while decryption it throws the exception javax.crypto.BadPaddingException: Given final block notproperly padded.
    The error is thrown only for selected records, not for all. For most of them it works fine. I use 256 bit AES Encryption.The sequence of steps to generate and retrieve the key is as follows:
    (Generating and Storing the Key)
    Generate original Key Using JCE --> Then XOR it with a known String (Key) --> Write to a file in DB Server (Solaris 10) using a Stored Procedure.
    (Retrieving the Key)
    Read the key file using s Stored Procedure --> XOR it with known String(Key) --> Retrieve the original Key
    The decryption works fine for most of the records (70%) but failing 30% of the time. There is no exception in the way the encrypted content gets stored in the db
    The key is generated as a one time step in the application and stored in the file. It is retrieved and cached in the application once, everytime the appserver is restarted.
    Could someone pls. help?
    Attaching below (1) code snippet for generating the key and (2) The code snipped to retrieve the key (3) the class which does the encryption and decryption of data
    (1) code snippet for generating the key
    String xorRefKey = "*&^%$#@!AiMsKey!*&^%$#@!AiMsKey!";
    KeyGenerator kg = KeyGenerator.getInstance("AES");
                kg.init(256);
                String initialKey = new String (kg.generateKey().getEncoded());
             char[] refArr =  xorRefKey.toCharArray();
              char[] initKeyArr = initialKey.toCharArray();
                char[] finalKeyArr = new char[refArr.length];
                 for(int i=0;i<initKeyArr.length;i++){
                     finalKeyArr= (char)(initKeyArr[i] ^ refArr[i]);
    String finalKey = new String(finalKeyArr);----------------------
    (2) The code snipped to retrieve the keyString xorRefKey = "*&^%$#@!AiMsKey!*&^%$#@!AiMsKey!";
    char[] refArr = xorRefKey.toCharArray();
    //initialKey is the key read from the file using a db call
    char[] initKeyArr = initialKey.toCharArray();
    char[] finalKeyArr = new char[refArr.length];
    for(int i=0;i<initKeyArr.length;i++){
    finalKeyArr[i]= (char)(initKeyArr[i] ^ refArr[i]);
    String finalKey= new String(finalKeyArr);
    Class to encrypt/decrypt
    (3) EncryptUtil classpublic class EncryptUtil {
    private static SecretKeySpec skeySpec = null;
    private static final String encryptionAlgorithm = "AES";
    private static IGOLogger logger = IGOLogger.getInstance(IGOLogger.ENCRYPTION);
    private static final String UNICODE_FORMAT = "UTF8";
    private Cipher cipher = null;
    public EncryptUtil(String key){
    String lFuncName = "EncryptUtil :: EncryptUtil(): ";
    try{
    cipher = Cipher.getInstance(encryptionAlgorithm);
    skeySpec = new SecretKeySpec(key.getBytes(), encryptionAlgorithm);
    } catch (NoSuchAlgorithmException e) {
    logger.error(lFuncName + "No Such Algorithm Error while creating Cipher and KeySpec ",e);
    } catch (NoSuchPaddingException e) {
    logger.error(lFuncName + "No Such Padding Error while creating Cipher and KeySpec ",e);
    * Encrypts the data based on the key and algorithm
    * @param data
    * @return encrypted data
    public String encrypt(String data){
    String lFuncName = "EncryptUil :: encrypt(): ";
    byte[] encryptedData = null;
    String encryptedFinal = "";
    try{
    if(data!=null && data.length()>0){
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec,cipher.getParameters());
    encryptedData = (cipher.doFinal(data.getBytes(UNICODE_FORMAT)));
    encryptedFinal = new BASE64Encoder().encode(encryptedData);
    } catch (InvalidKeyException e) {
    logger.error(lFuncName + "Invalid Key Error while Encrypting Data ",e);
    } catch (BadPaddingException e) {
    logger.error(lFuncName + "Bad Padding Error while Encrypting Data ",e);
    } catch (IllegalBlockSizeException e) {
    logger.error(lFuncName + " Illegal Block Size Error while Encrypting Data ",e);
    } catch (InvalidAlgorithmParameterException e) {
    logger.error(lFuncName + " Invalid Alogirthm Parameter Error while Encrypting Data ",e);
    } catch (UnsupportedEncodingException e) {
    logger.error(lFuncName + " Unsupported Encoding Exception Error while Encrypting Data ",e);
    }catch(Exception e){
    logger.error(lFuncName + " Error while Encrypting Data ",e);
    return encryptedFinal;
    * Decrypts the encrypted data based on the key and algorithm
    * @param data
    * @return
    public String decrypt (String data){
    String lFuncName = "EncryptUil :: decrypt(): ";
    byte[] decrypted = null;
    byte[] decryptedFinal = null;
    String decryptedData = "";
    try{
    if(data!=null && data.length()>0){
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    decrypted = new BASE64Decoder().decodeBuffer(data);
    decryptedFinal = (cipher.doFinal(decrypted));
    decryptedData = this.bytes2String(decryptedFinal);
    } catch (InvalidKeyException e) {
    logger.error(lFuncName + "Invalid Key Error while Decrypting Data ",e);
    } catch (BadPaddingException e) {
    logger.error(lFuncName + "Bad Padding Error while Decrypting Data ",e);
    } catch (IllegalBlockSizeException e) {
    logger.error(lFuncName + " Illegal Block Size Error while Decrypting Data ",e);
    } catch (IOException e) {
    logger.error(lFuncName + " IO Exception while Decrypting Data ",e);
    }catch (Exception e){
    logger.error(lFuncName + " Error while Decrypting Data ",e);
    return decryptedData;
    private String bytes2String( byte[] bytes )
              StringBuffer stringBuffer = new StringBuffer();
              for (int i = 0; i < bytes.length; i++)
                   stringBuffer.append( (char) bytes[i] );
              return stringBuffer.toString();
    }The EncryptUtil is invoked as follows:EncryptUtil encryptUtil = new EncryptUtil("finalKey retrieved when application starts");
    encryptUtil.encrypt(unencryptedData);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    shannara wrote:
    thanks for your reply.
    I am sorry but I am not able to get you exactly. Every time I invoke the Utility class, I do a
    EncryptUtil eUtil = new EncryptUtil() Good. You seem to be using it in a thread safe manner since you create a new instance each time you need to use one.
    >
    and then invoke the decrypt() or encrypt() method, which gets the key from the cache (it is a read only object, so no problems of concurrent modification or any thing of that sort). And also these methods are called from a normal java class only, which inturn may be called from a jsp/servlet, but no scenarios of any concurrent access as such, so based on what you said, I am not able to figure out where exactly the thread safety could come as an issue.Each instance of a jsp or servlet can be being processed by many threads at the same time. Your statement above hints at a possible lack of understand on this point though I could be just reading it wrong. It indicates to me that your problem may be nothing to do with the encryption and everything to do with 'concurrent access' .
    Make sure you have no instance variables or class variables in your jsp(s) and servlet(s).
    Edit: The more I think about this the more I believe you have a thread safety problem in the code that reads the key. I would concentrate on that.
    Edited by: sabre150 on Dec 18, 2007 10:10 AM

  • Javax.crypto reference in NW Dev Studio

    Has anyone encountered and resolved the issue with trying to reference javax.crypto.* as an import with the Netweaver Development Studio? 
    i.e. Add a line like the following to your code:
    Cipher c;
    Then organise imports; and javax.cryto.cipher will be added but not found.
    Thanks,
    Matt

    Simple really - Just needed to add JCE.jar reference to project (wasn't automatically done like the others).  Oh well - now I can debug my provider problem.

  • Using javax.crypto in oracle 10g

    Hi,
    I have a java stored procedure for oracle 10g (running jdk1.4) that
    uses the javax.crypto package and the bouncy castle provider for RSA
    decryption. Here is a snippet of the code in the procedure:
    Security.addProvider(new
    org.bouncycastle.jce.provider.BouncyCastleProvider());
    Cipher rsaCipher = Cipher.getInstance("RSA");
    RSAPrivateKey key = (RSAPrivateKey)
    MSPrivKeytoJKey.getPrivateKey(aKey);
    rsaCipher.init(Cipher.DECRYPT_MODE, key);
    rsaCipher.doFinal(encryptedByteArray);
    This works fine on my own machine running jdk1.4. However, when I load
    my stored procedure into the database and run it, I get the following
    exception after the line
    Cipher rsaCipher = Cipher.getInstance("RSA");
    tries to execute:
    java.security.NoSuchAlgorithmException: Cannot find any provider
    supporting RSA
    I have tried the following (based on information gathered from various
    forums):
    - ran
    loadjava -u username/pass@DB -v bcprov-jdk14-137.jar
    - added the following line to java.security
    security.provider.4=org.bouncycastle.jce.provider.BouncyCastleProvider
    but i still get the same error.
    I am reaching out desperately to all you experts for help :)
    Pouria

    Hi,
    Unfortunately, the Java VM only supports the basic JDK functionalities; you could try the Metalink Note 356123.1 which should work using BC library but this note only addresses AES.
    Furthermore, you need the following two extra permissions:
    exec dbms_java.grant_permission('SCOTT', 'SYS:java.security.SecurityPermission','putProviderProperty.BC', '' );
    exec dbms_java.grant_permission( 'SCOTT', 'SYS:java.security.SecurityPermission','insertProvider.BC', '' );
    Oboviously SCOTT would be changed to whichever schema you are using.
    Kuassi http://db360.blogspot.com

  • Javax.crypto.BadPaddingException: Given final block not properly padded

    import java.security.*;
    import javax.crypto.*;
    public class Cryptographer
    private final String DEFAULT_KEY="1111111111111111";
    private String KEY;
    public Cryptographer(String key)
    if((key==null)||key.equals(""))
    this.KEY = DEFAULT_KEY;
    else
    this.KEY = key;
    public byte[] encrypt(String toEncrypt)
    if((toEncrypt==null)||(toEncrypt.trim().equals("")))
    return null;
    try
    return DESEncrypt(toEncrypt,KEY);
    catch(Exception e)
    e.printStackTrace();
    return null;
    public String decrypt(byte[] bytes)
    if(bytes==null)
    return null;
    try
    return DESDecrypt(bytes,KEY);
    catch(Exception e)
    e.printStackTrace();
    return null+"hi";
    public String ToMac(byte[] bytes,String key)
    if(bytes==null)
    return null;
    try
    return getMac(bytes,KEY);
    catch(Exception e)
    return null;
    private byte[] DESEncrypt(String toEncrypt, String key)
    throws Exception
    // create a binary key from the argument key (seed)
    SecureRandom sr = new SecureRandom(key.getBytes("UTF-8"));
    KeyGenerator kg = KeyGenerator.getInstance("DES");
    kg.init(56,sr);
    SecretKey sk = kg.generateKey();
    // do the encryption with that key
    Cipher cipher = Cipher.getInstance("DES");
    //DES/CFB8/NOPadding;DES/OFB32/PKCS5Padding;DESEDE/ECB/PKCS5Padding;DES/ECB/NOPadding==DES
    cipher.init(Cipher.ENCRYPT_MODE, sk);
    byte[] encrypted = cipher.doFinal(toEncrypt.getBytes("UTF-8"));
    return new sun.misc.BASE64Encoder().encode(encrypted).toUpperCase().getBytes();
    //return encrypted;
    private String DESDecrypt(byte[] toDecrypt, String key)
    throws Exception
    // create a binary key from the argument key (seed)
    SecureRandom sr = new SecureRandom(key.getBytes("UTF-8"));
    KeyGenerator kg = KeyGenerator.getInstance("DES");
    kg.init(56,sr);
    SecretKey sk = kg.generateKey();
    // do the decryption with that key
    Cipher cipher = Cipher.getInstance("DES");
    cipher.init(Cipher.DECRYPT_MODE, sk);
    byte[] decrypted = cipher.doFinal(toDecrypt);
    return new sun.misc.BASE64Encoder().encode(decrypted).toUpperCase();
    //return new String(decrypted,"UTF-8");
    //create mac String; byte[] to be maced
    private String getMac(byte[] bytes,String key)
    byte[] bmac =null;
    try
    // create a binary key from the argument key (seed)
    SecureRandom sr = new SecureRandom(key.getBytes());
    KeyGenerator kg = KeyGenerator.getInstance("DES");
    kg.init(56,sr);
    SecretKey sk = kg.generateKey();
    Mac mac = Mac.getInstance("HmacMD5");
    //HmacMD5;HmacSHA1;PBEWith<mac> e.g PBEWithHmacSHA1
    mac.init(sk);
    bmac = mac.doFinal(bytes);
    catch(Exception e)
    e.printStackTrace();
    return new String(bmac);
    public String byte2hex(byte[] b) //��������������
    String hs="";
    String stmp="";
    for (int n=0;n<b.length;n++)
    stmp=(java.lang.Integer.toHexString(b[n] & 0XFF));
    if (stmp.length()==1) hs=hs+"0"+stmp;
    else hs=hs+stmp;
    if (n<b.length-1) hs=hs+"";
    return hs.toUpperCase();
    public static void main(String args[])
    throws Exception
    String key = new String("1111111111111111");
    Cryptographer c = new Cryptographer(key); //use key to initialize the class
    String str = new String("4A6C98EAEF14EAB6");
    byte[] b = c.encrypt(str); //to encrypt data
    System.out.println(b.length);
    System.out.println("Encrypted data:"+new String(b)+":"+new String(c.byte2hex(b))); //println Encrypt data
    String st = c.decrypt(str.getBytes()); //to decrypt data
    System.out.println(st.getBytes().length);
    System.out.println(st.length());
    System.out.println("Decrypted data:"+st+":"+c.byte2hex(st.getBytes())); //println decrypt data
    please help me! thax

    One: Use the [ code ] tags. Please. It'll only help you get answers.
    Two: encrypt() is returning the getBytes() of the result of Base64'ing the ciphertext. Bad. The whole POINT to Base64 is to produce Strings from byte[]'s. Don't use Base64 to produce a byte[]. Change encrypt() to return the byte[] directly.
    Three: Given that encrypt() is returning the byte[] from the Base64 - decrypt() needs to be ready to UNDO that. It isn't. decrypt() assumes the byte[] it's getting is the ciphertext. That's not what you're giving to it. It's very, very unhappy.
    Four: your main() isn't even handing decrypt() the (bogus) return from encrypt(). Your main() is asking decrypt() to decrypt your plaintext. That trick never works...
    Five: your choice of variable names in your main() is...suboptimal. If you'd chosen names that reflected the purpose of the variable (things like, say, 'plaintext' and 'ciphertext'), some of this would have been obvious.
    Try the following:import java.security.SecureRandom;
    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import javax.crypto.Mac;
    import javax.crypto.SecretKey;
    public class Cryptographer {
        private final String DEFAULT_KEY = "1111111111111111";
        private String KEY;
        public Cryptographer(String key) {
            if ((key == null) || key.equals("")) {
                this.KEY = DEFAULT_KEY;
            } else {
                this.KEY = key;
        public byte[] encrypt(String toEncrypt) {
            if ((toEncrypt == null) || (toEncrypt.trim().equals("")))
                return null;
            try {
                return DESEncrypt(toEncrypt, KEY);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
        public String decrypt(byte[] bytes) {
            if (bytes == null)
                return null;
            try {
                return DESDecrypt(bytes, KEY);
            } catch (Exception e) {
                e.printStackTrace();
                return null +"hi";
        public String ToMac(byte[] bytes, String key) {
            if (bytes == null)
                return null;
            try {
                return getMac(bytes, KEY);
            } catch (Exception e) {
                return null;
        private byte[] DESEncrypt(String toEncrypt, String key) throws Exception {
            // create a binary key from the argument key (seed)
            SecureRandom sr = new SecureRandom(key.getBytes("UTF-8"));
            KeyGenerator kg = KeyGenerator.getInstance("DES");
            kg.init(56, sr);
            SecretKey sk = kg.generateKey();
            // do the encryption with that key
            Cipher cipher = Cipher.getInstance("DES");
            //DES/CFB8/NOPadding;DES/OFB32/PKCS5Padding;DESEDE/ECB/PKCS5Padding;DES/ECB/NOPadding==DES
            cipher.init(Cipher.ENCRYPT_MODE, sk);
            byte[] encrypted = cipher.doFinal(toEncrypt.getBytes("UTF-8"));
            return encrypted;
        private String DESDecrypt(byte[] toDecrypt, String key) throws Exception {
            // create a binary key from the argument key (seed)
            SecureRandom sr = new SecureRandom(key.getBytes("UTF-8"));
            KeyGenerator kg = KeyGenerator.getInstance("DES");
            kg.init(56, sr);
            SecretKey sk = kg.generateKey();
            // do the decryption with that key
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, sk);
            byte[] decrypted = cipher.doFinal(toDecrypt);
            return new String(decrypted,"UTF-8");
        //create mac String; byte[] to be maced
        private String getMac(byte[] bytes, String key) {
            byte[] bmac = null;
            try {
                // create a binary key from the argument key (seed)
                SecureRandom sr = new SecureRandom(key.getBytes());
                KeyGenerator kg = KeyGenerator.getInstance("DES");
                kg.init(56, sr);
                SecretKey sk = kg.generateKey();
                Mac mac = Mac.getInstance("HmacMD5");
                //HmacMD5;HmacSHA1;PBEWith<mac> e.g PBEWithHmacSHA1
                mac.init(sk);
                bmac = mac.doFinal(bytes);
            } catch (Exception e) {
                e.printStackTrace();
            return new String(bmac);
        public String byte2hex(byte[] b) //��������������
            String hs = "";
            String stmp = "";
            for (int n = 0; n < b.length; n++) {
                stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
                if (stmp.length() == 1)
                    hs = hs + "0" + stmp;
                else
                    hs = hs + stmp;
                if (n < b.length - 1)
                    hs = hs + "";
            return hs.toUpperCase();
        public static void main(String args[]) throws Exception {
            String key = new String("1111111111111111");
            Cryptographer c = new Cryptographer(key); //use key to initialize the class
            String str = new String("Hello world!");
            byte[] ciphertext = c.encrypt(str); //to encrypt data
            System.out.println(ciphertext.length);
            System.out.println("Encrypted data:"  + new String(c.byte2hex(ciphertext )));
            String plaintext = c.decrypt(ciphertext );  //to decrypt data
            System.out.println(plaintext.getBytes().length);
            System.out.println(plaintext.length());
            System.out.println("Decrypted data:" + plaintext ); //println decrypt data
    }And please, please, PLEASE use the [ code ] tags...
    Grant

  • Problem when using javax.crypto.KeyGenerator in netbeans

    This is my IDE information:
    Product Version: NetBeans IDE 6.0.1 (Build 200801291616)
    Java: 1.6.0_03; Java HotSpot(TM) Client VM 1.6.0_03-b05
    System: Windows XP version 5.1 running on x86; Cp1252; en_US (nb)
    I am trying to develop a Test jar file. I created some simple jar files and could upload it in mobile.
    Now I want to implement some encryption. For that I started writing codes. But when trying to import javax.crypto.KeyGenerator class, netbeans is showing "cannot find symbol" error. I can use javax.crypto.Cipher/BadPaddingException/IllegalBlockSizeException/NoSuchPaddingException/spec/ShortBuffrException only. If i try to use any other class of javax.crypto, i get an error.
    I am new to mobility.I downloaded netbean mobility package and Installed it.
    Please provide some help.. thank you....

    This is my IDE information:
    Product Version: NetBeans IDE 6.0.1 (Build 200801291616)
    Java: 1.6.0_03; Java HotSpot(TM) Client VM 1.6.0_03-b05
    System: Windows XP version 5.1 running on x86; Cp1252; en_US (nb)
    I am trying to develop a Test jar file. I created some simple jar files and could upload it in mobile.
    Now I want to implement some encryption. For that I started writing codes. But when trying to import javax.crypto.KeyGenerator class, netbeans is showing "cannot find symbol" error. I can use javax.crypto.Cipher/BadPaddingException/IllegalBlockSizeException/NoSuchPaddingException/spec/ShortBuffrException only. If i try to use any other class of javax.crypto, i get an error.
    I am new to mobility.I downloaded netbean mobility package and Installed it.
    Please provide some help.. thank you....

  • Import javax.crypto not found error

    Hi,
    I have just installed the JDK1.7 on a windows machine.
    Whenever I try to compile my module, I get an error on the import javax.crypto line. It tells me that it can't the javax\Crypto\Cipher.class.
    I have the jdk installed on d:\glassfish3 and am pointing the classpath to d:\glassfish3\jdk7 (also tried d:\glassfish3\jdk7\jre as well) with no luck.
    Any help would be greatly appreciated.
    Thanks,
    Drew Nathanson
    Technical Synergy, Inc.

    Thanks. Maybe I should explain a little better.
    I am using JBuilder 2006 to my IDE. This environment requires that you put in the path to the JRE/JDK.
    I have uninstalled and downloaded the jdk again and this time i'm getting a strange error:
    "test.java": cannot access javax.crypto.Cipher; bad class file: D:\Program Files\Java\jre7\lib\jce.jar\javax\crypto\Cipher.class, class file has wrong version 51.0, should be 49.0, Please remove or make sure it appears in the correct subdirectory of the classpath. at line 19, column 21
    Now this is strange because i'm using the right library.
    Is there something that I'm missing here?
    Again, thanks for your help.
    Drew Nathanson

  • Class javax.crypto.SecretKey not found in import.

    While compilation i am getting this error.
    Class javax.crypto.SecretKey not found in import.
    I am not able to figure it out . Please help me for that.
    Is it related to some classpath setting.

    This error is due to the c:\windows\system32\java.exe being first on the path instead of the d:\jdev9i\jdk\bin\java.exe being picked up.

  • Javax.crypto.* is not present in JDK 1.4 plz help

    Hi,
    Currently i am using jdk 1.4 and I am trying to compile the security applications which are using javax.crypto.* package.
    Hence it is giving error so can any one please help me how can I include this package into jdk 1.4 or is there any other alternative for it.
    Need help immediately.
    It would be apprciable if i get an immediate reply.
    Thanks in advance.

    What is a "marker" interface?
    Marker Interface pattern
    c2.com - Marker Interface
    experts.about.com - Marker Interfaces
    The Purpose of the Marker Interface
    Maximize your Design ROI with Marker Interfaces and JavaDoc

  • Javax.crypto.* problem in WLW

    Hi,
    I am trying to encrypt a String in WLW 8.1 SP2.
    The IDE is not recognizing javax.crypto.* package. When I use the same code and
    execute it with TextPad, it works just fine.
    FYI, the non-WLS JDK is 1.4.1_01-b01 and WLS uses 1.4.1_05.
    What do I need to do to be able to use javax.crypto.* packages in WebLogic? Any
    helpis greatly appreciated.
    Thanks, Eric

    I had to add it manually:(
    * Go to application properties (Tools Menu > Application Properties... Menu
    Item)
    * Under WebLogic Server look for Server classpath additions:
    * Click add jar
    * Navigate to jdk\jre\lib\jce.jar
    * Add the jar file
    "Eric J" <[email protected]> wrote in message
    news:404e34a9$[email protected]..
    >
    Hi,
    I am trying to encrypt a String in WLW 8.1 SP2.
    The IDE is not recognizing javax.crypto.* package. When I use the samecode and
    execute it with TextPad, it works just fine.
    FYI, the non-WLS JDK is 1.4.1_01-b01 and WLS uses 1.4.1_05.
    What do I need to do to be able to use javax.crypto.* packages inWebLogic? Any
    helpis greatly appreciated.
    Thanks, Eric

  • Javax.crypto missing in my webdynpro project

    Hello
    I am trying to develop application which uses DES crypto function.
    I have an example of code which should work but the problem is with the JCE crypto library it uses.
    In normal java project I can import javax.crypto but in my web dynpro DC component I simply can't.
    Is there any way to add this library?
    Thanks for any help.

    I found the solution myself and it was quiet simple.
    Just open the properties of the project and add external JAR to java build path. The library I was seeking is located in program files/java/jre.../lib and its the jce.jar.
    The other problem I am having with this is that when I try to build the development component, the jce.jar is removed from the build path and the previous error persists. It is strange because when I simply choose rebuild project and then deploy, everything works.

  • JMS SAF client cannot forward messages - Caused by: javax.crypto.BadPadding

    Hi,
    I seem to be struggling with a problem that I'm not sure if I can ever find a solution.
    I have a configured a local JMS client to forward my messages to a remote WLSB 9.2.
    The local client is running JDK 1_0_14 on a windows platform.
    The remote server is on IBM JRE on linux. Now I'm getting problems when the messages are forwarded by the local SAF client. The client does not seem to be able to decrypt the password I have in my SAFClient.xml. I have pretty much followed every line in the documentation of SAF client and has already revisited it a few times.
    It seems to be something to do with the ClientSAFEncrypt utility that I was advised to get the encrypted password which I have put in the XML File. Here is the exception. Any help will be greatly appreciated.
    All I know is it is something to do with encoding of the password, but I cannot get a clue what else.
    <Mar 25, 2008 12:28:40 PM PDT> <Info> <Store> <BEA-280050> <Persistent store "SAFSTORE0V" opened: directory="C:\depot\javaSrc\logging\stores\default" writePolicy="Direct-Write" blockSize=512 directIO=false driver="NIO">
    javax.naming.NamingException: Invalid password key to unlock the passwords in the configuration file [Root exception is weblogic.jms.common.JMSException: Invalid password key to unlock the passwords in the configuration file]
         at weblogic.jms.safclient.jndi.InitialContextFactoryImpl.getNamingException(InitialContextFactoryImpl.java:31)
         at weblogic.jms.safclient.jndi.InitialContextFactoryImpl.getInitialContext(InitialContextFactoryImpl.java:162)
         at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:667)
         at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:247)
         at javax.naming.InitialContext.init(InitialContext.java:223)
         at javax.naming.InitialContext.<init>(InitialContext.java:197)
         at com.netflix.messaging.ESBFactory.<init>(ESBFactory.java:103)
         at com.netflix.messaging.ESBFactory.getFactory(ESBFactory.java:45)
         at com.netflix.messaging.NFMessagingManager.getProducerHandle(NFMessagingManager.java:218)
         at com.netflix.messaging.NFMessagingManager.initProducers(NFMessagingManager.java:730)
         at com.netflix.messaging.NFMessagingManager.init(NFMessagingManager.java:863)
         at com.netflix.messaging.NFMessagingManager.start(NFMessagingManager.java:1461)
         at com.netflix.messaging.NFMessagingManager.start(NFMessagingManager.java:1628)
         at com.netflix.logging.messaging.MessageDestinationDispatcher.startMessagingManager(MessageDestinationDispatcher.java:164)
         at com.netflix.logging.messaging.MessageDestinationDispatcher.<init>(MessageDestinationDispatcher.java:25)
         at com.netflix.logging.NFMessageAppender.append(NFMessageAppender.java:72)
         at org.apache.log4j.AppenderSkeleton.doAppend(AppenderSkeleton.java:251)
         at org.apache.log4j.helpers.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:66)
         at org.apache.log4j.Category.callAppenders(Category.java:206)
         at org.apache.log4j.Category.forcedLog(Category.java:391)
         at org.apache.log4j.Category.log(Category.java:838)
         at com.netflix.logging.log4jAdapter.Log4jLoggingAdapter.log(Log4jLoggingAdapter.java:64)
         at com.netflix.logging.NFLogger.log(NFLogger.java:125)
         at com.netflix.logging.LogManager.info(LogManager.java:152)
         at com.netflix.logging.aggregator.Bucketer.init(Bucketer.java:92)
         at com.netflix.logging.aggregator.Bucketer.<init>(Bucketer.java:80)
         at com.netflix.logging.aggregator.TracerAggregator.<init>(TracerAggregator.java:29)
         at com.netflix.logging.aggregator.TracerAggregator.<clinit>(TracerAggregator.java:20)
         at com.netflix.logging.NFLogger.start(NFLogger.java:105)
         at com.netflix.logging.LogManager.registerLogger(LogManager.java:67)
         at com.netflix.logging.test.LoggingTest.sendDefault(LoggingTest.java:32)
         at com.netflix.logging.test.LoggingTest.main(LoggingTest.java:19)
    Caused by: weblogic.jms.common.JMSException: Invalid password key to unlock the passwords in the configuration file
         at weblogic.jms.safclient.admin.ConfigurationUtils.doRemoteContexts(ConfigurationUtils.java:475)
         at weblogic.jms.safclient.agent.AgentManager.<init>(AgentManager.java:54)
         at weblogic.jms.safclient.ClientSAFDelegate.open(ClientSAFDelegate.java:65)
         at weblogic.jms.safclient.ClientSAFImpl.open(ClientSAFImpl.java:62)
         at weblogic.jms.safclient.jndi.InitialContextFactoryImpl.getInitialContext(InitialContextFactoryImpl.java:160)
         ... 30 more
    Caused by: javax.crypto.BadPaddingException: Given final block not properly padded
         at com.sun.crypto.provider.SunJCE_h.b(DashoA12275)
         at com.sun.crypto.provider.SunJCE_h.b(DashoA12275)
         at com.sun.crypto.provider.SunJCE_af.b(DashoA12275)
         at com.sun.crypto.provider.PBEWithMD5AndDESCipher.engineDoFinal(DashoA12275)
         at javax.crypto.Cipher.doFinal(DashoA12275)
         at weblogic.jms.common.SecHelper.decryptString(SecHelper.java:140)
         at weblogic.jms.safclient.admin.ConfigurationUtils.doRemoteContexts(ConfigurationUtils.java:473)
         ... 34 more
    java.lang.IllegalStateException: Cannot create context: Invalid password key to unlock the passwords in the configuration file
         at com.netflix.messaging.ESBFactory.<init>(ESBFactory.java:106)
         at com.netflix.messaging.ESBFactory.getFactory(ESBFactory.java:45)
         at com.netflix.messaging.NFMessagingManager.getProducerHandle(NFMessagingManager.java:218)
         at com.netflix.messaging.NFMessagingManager.initProducers(NFMessagingManager.java:730)
         at com.netflix.messaging.NFMessagingManager.init(NFMessagingManager.java:863)
         at com.netflix.messaging.NFMessagingManager.start(NFMessagingManager.java:1461)
         at com.netflix.messaging.NFMessagingManager.start(NFMessagingManager.java:1628)
         at com.netflix.logging.messaging.MessageDestinationDispatcher.startMessagingManager(MessageDestinationDispatcher.java:164)
         at com.netflix.logging.messaging.MessageDestinationDispatcher.<init>(MessageDestinationDispatcher.java:25)
         at com.netflix.logging.NFMessageAppender.append(NFMessageAppender.java:72)
         at org.apache.log4j.AppenderSkeleton.doAppend(AppenderSkeleton.java:251)
         at org.apache.log4j.helpers.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:66)
         at org.apache.log4j.Category.callAppenders(Category.java:206)
         at org.apache.log4j.Category.forcedLog(Category.java:391)
         at org.apache.log4j.Category.log(Category.java:838)
         at com.netflix.logging.log4jAdapter.Log4jLoggingAdapter.log(Log4jLoggingAdapter.java:64)
         at com.netflix.logging.NFLogger.log(NFLogger.java:125)
         at com.netflix.logging.LogManager.info(LogManager.java:152)
         at com.netflix.logging.aggregator.Bucketer.init(Bucketer.java:92)
         at com.netflix.logging.aggregator.Bucketer.<init>(Bucketer.java:80)
         at com.netflix.logging.aggregator.TracerAggregator.<init>(TracerAggregator.java:29)
         at com.netflix.logging.aggregator.TracerAggregator.<clinit>(TracerAggregator.java:20)
         at com.netflix.logging.NFLogger.start(NFLogger.java:105)
         at com.netflix.logging.LogManager.registerLogger(LogManager.java:67)
         at com.netflix.logging.test.LoggingTest.sendDefault(LoggingTest.java:32)

    Hi,
    I seem to be struggling with a problem that I'm not sure if I can ever find a solution.
    I have a configured a local JMS client to forward my messages to a remote WLSB 9.2.
    The local client is running JDK 1_0_14 on a windows platform.
    The remote server is on IBM JRE on linux. Now I'm getting problems when the messages are forwarded by the local SAF client. The client does not seem to be able to decrypt the password I have in my SAFClient.xml. I have pretty much followed every line in the documentation of SAF client and has already revisited it a few times.
    It seems to be something to do with the ClientSAFEncrypt utility that I was advised to get the encrypted password which I have put in the XML File. Here is the exception. Any help will be greatly appreciated.
    All I know is it is something to do with encoding of the password, but I cannot get a clue what else.
    <Mar 25, 2008 12:28:40 PM PDT> <Info> <Store> <BEA-280050> <Persistent store "SAFSTORE0V" opened: directory="C:\depot\javaSrc\logging\stores\default" writePolicy="Direct-Write" blockSize=512 directIO=false driver="NIO">
    javax.naming.NamingException: Invalid password key to unlock the passwords in the configuration file [Root exception is weblogic.jms.common.JMSException: Invalid password key to unlock the passwords in the configuration file]
         at weblogic.jms.safclient.jndi.InitialContextFactoryImpl.getNamingException(InitialContextFactoryImpl.java:31)
         at weblogic.jms.safclient.jndi.InitialContextFactoryImpl.getInitialContext(InitialContextFactoryImpl.java:162)
         at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:667)
         at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:247)
         at javax.naming.InitialContext.init(InitialContext.java:223)
         at javax.naming.InitialContext.<init>(InitialContext.java:197)
         at com.netflix.messaging.ESBFactory.<init>(ESBFactory.java:103)
         at com.netflix.messaging.ESBFactory.getFactory(ESBFactory.java:45)
         at com.netflix.messaging.NFMessagingManager.getProducerHandle(NFMessagingManager.java:218)
         at com.netflix.messaging.NFMessagingManager.initProducers(NFMessagingManager.java:730)
         at com.netflix.messaging.NFMessagingManager.init(NFMessagingManager.java:863)
         at com.netflix.messaging.NFMessagingManager.start(NFMessagingManager.java:1461)
         at com.netflix.messaging.NFMessagingManager.start(NFMessagingManager.java:1628)
         at com.netflix.logging.messaging.MessageDestinationDispatcher.startMessagingManager(MessageDestinationDispatcher.java:164)
         at com.netflix.logging.messaging.MessageDestinationDispatcher.<init>(MessageDestinationDispatcher.java:25)
         at com.netflix.logging.NFMessageAppender.append(NFMessageAppender.java:72)
         at org.apache.log4j.AppenderSkeleton.doAppend(AppenderSkeleton.java:251)
         at org.apache.log4j.helpers.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:66)
         at org.apache.log4j.Category.callAppenders(Category.java:206)
         at org.apache.log4j.Category.forcedLog(Category.java:391)
         at org.apache.log4j.Category.log(Category.java:838)
         at com.netflix.logging.log4jAdapter.Log4jLoggingAdapter.log(Log4jLoggingAdapter.java:64)
         at com.netflix.logging.NFLogger.log(NFLogger.java:125)
         at com.netflix.logging.LogManager.info(LogManager.java:152)
         at com.netflix.logging.aggregator.Bucketer.init(Bucketer.java:92)
         at com.netflix.logging.aggregator.Bucketer.<init>(Bucketer.java:80)
         at com.netflix.logging.aggregator.TracerAggregator.<init>(TracerAggregator.java:29)
         at com.netflix.logging.aggregator.TracerAggregator.<clinit>(TracerAggregator.java:20)
         at com.netflix.logging.NFLogger.start(NFLogger.java:105)
         at com.netflix.logging.LogManager.registerLogger(LogManager.java:67)
         at com.netflix.logging.test.LoggingTest.sendDefault(LoggingTest.java:32)
         at com.netflix.logging.test.LoggingTest.main(LoggingTest.java:19)
    Caused by: weblogic.jms.common.JMSException: Invalid password key to unlock the passwords in the configuration file
         at weblogic.jms.safclient.admin.ConfigurationUtils.doRemoteContexts(ConfigurationUtils.java:475)
         at weblogic.jms.safclient.agent.AgentManager.<init>(AgentManager.java:54)
         at weblogic.jms.safclient.ClientSAFDelegate.open(ClientSAFDelegate.java:65)
         at weblogic.jms.safclient.ClientSAFImpl.open(ClientSAFImpl.java:62)
         at weblogic.jms.safclient.jndi.InitialContextFactoryImpl.getInitialContext(InitialContextFactoryImpl.java:160)
         ... 30 more
    Caused by: javax.crypto.BadPaddingException: Given final block not properly padded
         at com.sun.crypto.provider.SunJCE_h.b(DashoA12275)
         at com.sun.crypto.provider.SunJCE_h.b(DashoA12275)
         at com.sun.crypto.provider.SunJCE_af.b(DashoA12275)
         at com.sun.crypto.provider.PBEWithMD5AndDESCipher.engineDoFinal(DashoA12275)
         at javax.crypto.Cipher.doFinal(DashoA12275)
         at weblogic.jms.common.SecHelper.decryptString(SecHelper.java:140)
         at weblogic.jms.safclient.admin.ConfigurationUtils.doRemoteContexts(ConfigurationUtils.java:473)
         ... 34 more
    java.lang.IllegalStateException: Cannot create context: Invalid password key to unlock the passwords in the configuration file
         at com.netflix.messaging.ESBFactory.<init>(ESBFactory.java:106)
         at com.netflix.messaging.ESBFactory.getFactory(ESBFactory.java:45)
         at com.netflix.messaging.NFMessagingManager.getProducerHandle(NFMessagingManager.java:218)
         at com.netflix.messaging.NFMessagingManager.initProducers(NFMessagingManager.java:730)
         at com.netflix.messaging.NFMessagingManager.init(NFMessagingManager.java:863)
         at com.netflix.messaging.NFMessagingManager.start(NFMessagingManager.java:1461)
         at com.netflix.messaging.NFMessagingManager.start(NFMessagingManager.java:1628)
         at com.netflix.logging.messaging.MessageDestinationDispatcher.startMessagingManager(MessageDestinationDispatcher.java:164)
         at com.netflix.logging.messaging.MessageDestinationDispatcher.<init>(MessageDestinationDispatcher.java:25)
         at com.netflix.logging.NFMessageAppender.append(NFMessageAppender.java:72)
         at org.apache.log4j.AppenderSkeleton.doAppend(AppenderSkeleton.java:251)
         at org.apache.log4j.helpers.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:66)
         at org.apache.log4j.Category.callAppenders(Category.java:206)
         at org.apache.log4j.Category.forcedLog(Category.java:391)
         at org.apache.log4j.Category.log(Category.java:838)
         at com.netflix.logging.log4jAdapter.Log4jLoggingAdapter.log(Log4jLoggingAdapter.java:64)
         at com.netflix.logging.NFLogger.log(NFLogger.java:125)
         at com.netflix.logging.LogManager.info(LogManager.java:152)
         at com.netflix.logging.aggregator.Bucketer.init(Bucketer.java:92)
         at com.netflix.logging.aggregator.Bucketer.<init>(Bucketer.java:80)
         at com.netflix.logging.aggregator.TracerAggregator.<init>(TracerAggregator.java:29)
         at com.netflix.logging.aggregator.TracerAggregator.<clinit>(TracerAggregator.java:20)
         at com.netflix.logging.NFLogger.start(NFLogger.java:105)
         at com.netflix.logging.LogManager.registerLogger(LogManager.java:67)
         at com.netflix.logging.test.LoggingTest.sendDefault(LoggingTest.java:32)

  • AES with two keys javax.crypto.BadPaddingException

    Hello,
    I'am trying to encrypt / decrypt using AES, which performs correctly for one level encryption / decryption. However, when I am trying a two level encryption / decryption. I have this code:
    String message="This is just an example";
    byte[] raw="df5ea29924d39c3be8785734f13169c6".getBytes("ISO-8859-1");
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] encrypted = cipher.doFinal((args.length == 0 ? "This is just an example" : args[0]).getBytes());
    System.out.println("encrypted string: " + asHex(encrypted));
    raw="ef5ea29924d39c3be8785734f13169c7".getBytes("ISO-8859-1");
    skeySpec = new SecretKeySpec(raw, "AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] encrypteded = cipher.doFinal(encrypted);
    raw="df5ea29924d39c3be8785734f13169c6".getBytes("ISO-8859-1");
    skeySpec = new SecretKeySpec(raw, "AES");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    byte[] original1 = cipher.doFinal(encrypteded);
    raw="ef5ea29924d39c3be8785734f13169c7".getBytes("ISO-8859-1");
    skeySpec = new SecretKeySpec(raw, "AES");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    byte[] original2 = cipher.doFinal(original1);
    I get this exception:
    Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:811)
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:676)
    at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:317)
    at javax.crypto.Cipher.doFinal(Cipher.java:1813)
    Thank you!

    marya_a wrote:
    Thank you for you replay. Can you tell me if there is a symmetric and commutative cryptosystem. Since XOR commutes I would expect that any of the stream ciphers that generate a stream of pseudo random bits and XOR these with the cleartext to create the ciphertext will work. RC4 and block algorithms (AES, DES etc) using modes such as CFB spring to mind.
    Of course these should only be used with random session keys since using fixed keys (as you seem to have) is fundamentally insecure.
    I know that RSA is commutative, I'm pretty sure that this applies only if all stages use the same modulus.
    but I want it to be also symmetric.Edited by: sabre150 on Apr 13, 2010 9:41 AM

Maybe you are looking for