AES/ECB/NoPadding

Dear ALL,
I am having a problem AES algorithm
I'm using AES/ECB/NoPadding
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.jpos.iso.ISOUtil;
public class AesTest {
     static Provider p = new org.bouncycastle.jce.provider.BouncyCastleProvider();
     public static void main(String[] args) {
          Security.addProvider(p);
          try {
               byte aesKeyByte[] =  ISOUtil.hex2byte("EE5C261E5B0FF0E78CFF3D6D65DDB220");
               byte clearValue[] =  ISOUtil.hex2byte("7C096716F12BAE6B");
               SecretKey AESKey = new SecretKeySpec(aesKeyByte,"AES");
               byte enout[] = encrypt(AESKey, clearValue, p, "ECB", null);
               System.out.println("ENCR DATA : "+ISOUtil.hexString(enout));
               byte deout[] = decrypt(AESKey, enout, p, "ECB", null);
               System.out.println("DER DATA : "+ISOUtil.hexString(deout));
          } catch (Exception e) {
               e.printStackTrace();
     public static byte[] encrypt(SecretKey secretKey, byte[] clearBytes, Provider p,
               String mode, byte[] IV) throws Exception {
          if ("CBC".equals(mode)) {
               Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", p
                         .getName());
               cipher
                         .init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(
                                   IV));
               return cipher.doFinal(clearBytes);
          } else {
               Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding", p
                         .getName());
               cipher.init(Cipher.ENCRYPT_MODE, secretKey);
               return cipher.doFinal(clearBytes);
     public static byte[] decrypt(SecretKey secretKey, byte[] ciperBytes, Provider p,
               String mode, byte[] IV) throws Exception {
          if ("CBC".equals(mode)) {
               Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", p
                         .getName());
               cipher
                         .init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(
                                   IV));
               return cipher.doFinal(ciperBytes);
          } else {
               Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding", p
                         .getName());
               cipher.init(Cipher.DECRYPT_MODE, secretKey);
               return cipher.doFinal(ciperBytes);
}Error
javax.crypto.IllegalBlockSizeException: data not block size aligned
     at org.bouncycastle.jce.provider.JCEBlockCipher.engineDoFinal(Unknown Source)
     at javax.crypto.Cipher.doFinal(DashoA13*..)
     at AesTest.encrypt(AesTest.java:72)
     at AesTest.main(AesTest.java:41)
Regards
Edited by: EJP on 21/07/2011 15:45

But I'm using ECB mode. So my clear data has 8 byte block
When I use clear data = 7C096716F12BAE6B7C096716F12BAE6B (16 bytes, two 8 blocks), there is no any exception
But clear data = 7C096716F12BAE6B7C096716F12BAE6B7C096716F12BAE6B (3 8 blocks ) again getting same error
Note : I'm not facing this issue with DES algorithm.
Actually, I don't know length of my clear text, what I'm doing I will make 8 bytes blocks of clear text and used to encrypt it.
Example
Clear text = 1111 2 makes 1111 2000 0000 0005
Can you tell me how to encrypt this kind of data using AES with ECB mode ?
Regards

Similar Messages

  • Bad Padding Exception using AES/ECB/PKCS5Padding

    Hi, I need some help Tryng to crypt and decrypt a String using AES/ECB/PKCS5Padding
    I paste my code below
    Crypt
    Cipher cipher;
             byte[] pass=new byte[]{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}; // just for example
            SecretKeySpec key = new SecretKeySpec(pass, "AES");
            cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key);        
            byte[] utf8 = da_cifrare.getBytes("utf-8");
            byte[] enc = cipher.doFinal(utf8);
            String cifrata =new String (Base64.encodeBase64(enc));
            return cifrata;
    And on the other side Decrypt
    Cipher decipher;
               byte[] pass=new byte[]{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}; // just for example
               SecretKeySpec key = new SecretKeySpec(pass, "AES");
               decipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
               decipher.init(Cipher.DECRYPT_MODE, key); 
               byte[] buf =Base64.decodeBase64(da_decifrare.getBytes("utf-8"));
               byte[] recoveredBytes = decipher.doFinal(buf);
               String in_chiaro = new String (recoveredBytes,"utf-8");
               return (in_chiaro);I'm getting Bad padding exception when I try to Decrypt, any ideas ??

    Nothing obviously wrong but we have no view of your Base64 encoder and decoder. You should check
    a) that the bytes of your key are the same in both methods
    b) that the bytes resulting in your decrypt methodbyte[] buf =Base64.decodeBase64(da_decifrare.getBytes("utf-8"));are exactly the same as those created in the encrypt method using  byte[] enc = cipher.doFinal(utf8);
          Note - since Base64 consists of only ASCII characters you should use String cifrata =new String (Base64.encodeBase64(enc),"ASCII");and byte[] buf =Base64.decodeBase64(da_decifrare.getBytes("ASCII"));though this flaw should not be the cause of your exception.
    Edited by: sabre150 on Dec 15, 2009 12:32 PM

  • Trouble encrypting correctly with AES with a static key

    Hi. I'm trying to get JCE to work with the following example using AES in ECB mode (yes, ECB shouldn't be used, but it's what I'm supposed to use): given a clear text String represented by the bytes (in hex) 546578746F2070617261207465737465 and a key 6573736173656E686165686672616361, the program is supposed to provide the encrypted bytes A506A19333F306AC2C62CBE931963AE7. I used an online encryption service to check for myself if the above is true, and it is. However, I just can't get it to work right in Java:
    import javax.crypto.Cipher;
    import javax.crypto.spec.SecretKeySpec;
    public class AESTest {
        public static String asHex(byte buf[]) {
            StringBuffer strbuf = new StringBuffer(buf.length * 2);
         int i;
         for (i = 0; i < buf.length; i++) {
             if (((int) buf[i] & 0xff) < 0x10) {
                 strbuf.append("0");
                strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
            return strbuf.toString();
        public static void main(String[] args) throws Exception {
            String keyString = "Texto para teste";
         // 546578746F2070617261207465737465 (Hex)
         byte[] key = keyString.getBytes("UTF-8");
         System.out.println(asHex(key).toUpperCase());
         String clearText = "essasenhaehfraca";
         // ZXNzYXNlbmhhZWhmcmFjYQ== (Base64)
         // 6573736173656E686165686672616361 (Hex)
         byte[] clear = clearText.getBytes("UTF-8");
         System.out.println(asHex(clear).toUpperCase());
         SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
         // PKCS5Padding or NoPadding
         Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
         cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
         byte[] encrypted = cipher.doFinal(clear);
         System.out.println(asHex(encrypted).toUpperCase());
    }All examples I found generate a key instead of using a static one. Well, I need to use that specific key.
    What am I doing wrong? Thank you very much!
    Message was edited by:
    Magus

    \o/
    Lame me. I wasn't even going to re-check which was the text and which was the key. I guess I should keep that in mind while dealing with cryptography.
    Thanks a lot!!! :D

  • AES - output size

    Hi,
    I'm trying to encode a 128 bits data using AESCipher (with 128 bits key). the output I receive is 256 bits long. Is this suppose to be right? does anyone knows how can I get a 128 bits output?
    my sample code is:
    //create key
    Random rand = new Random()
    byte[] key = new byte[16];
    rand.nextBytes(key);
    SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
    //create cipher
    Cipher Ek = Cipher.getInstance("AES");
    Ek.init(Cipher.ENCRYPT_MODE, skeySpec);
    int outputSize = Ek.getOutputSize(16);                    // returns 32
    int blockSize   = Ek.getBlockSize();                          // returns 16
    byte[] data = new byte[16];
    rand.nextBytes(data);
    byte[] output = Ek.doFinal(data);                                 //returns 32 byte array

    You have specified Cipher.getInstance("AES") which by default gives you Cipher.getInstance("AES/ECB/PKCS5Padding").
    If the the data to encode is a multiple of the block size then PKCS5Padding adds a block of zeros. If you know for certain that you are always going to encrypt a multiple of the block size then you can specifiy Cipher.getInstance("AES/ECB/NoPadding").

  • AES output has always 32byte length

    Hello
    I have one question about decrypted data via AES. My code is following:
    byte [] key = Hex.decode("000102030405060708090A0B0C0D0E0F");   
    byte [] input = Hex.decode("000102030405060708090A0B0C0D0E0F");                               
    byte [] output = null;
    SecretKey secretKey = new SecretKeySpec(key, "AES");
    Cipher cipher = Cipher.getInstance("AES", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);
    output = cipher.doFinal(input);The input data have 16 byte length but I got always 32 byte large output. When I put only 15 byte input then I got 16 byte large output.
    Can anyone explain me why I have 32 bytes instead of 16bytes, because input is exactly 16 byte and I expect same size.
    Note,that first 16 bytes are equal as output in Crypto ++.
    What is
    Thanks
    I'm simulating example from Crypto ++ in which output is always 16 byte by 16 byte large input.

    By default you get PKCS5Padding so you will get 16 bytes of encrypted padding. Specify
    Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding", "BC");

  • How to use padding scheme FIPS81 in java plz help?

    Plz refer the below code using this code I m trying to decrypt XLS file using pass phrase.
    I m using the same pass phrase which was used @ the time of encryption.
    But the problem I m facing is that the file was encrypted in DOT NET_ using padding scheme FIPS81 and there impelmentation of FIPS81 is not available in JAVA so that it gives exception at the time of decryption which is given below
    Exception : javax.crypto.BadPaddingException: Given final block not properly padded
    I urgently need the solution of this problem so somebody plz help me to find the solution of this problem.....Ur reply would be appriciated.....!!
    The File is Encrypted using below mechanism
    ALGORITHM : AES
    MODE : ECB
    PADDING SCHEME : FIPS81
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    public class DecryptTest {
         public static void main(String[] s){
              String passPhrase = "passphrase";
              String encFileName = "encsample.xls";
              String decFileName = "decsample.xls";
              FileInputStream encFileIn = null;
              FileOutputStream decFileOut = null;
              File f = null;
              byte[] message;
              try {
                   f = new File(encFileName);
                   encFileIn = new FileInputStream(f);
                   decFileOut = new FileOutputStream(decFileName);
                   message = new byte[encFileIn.available()]; //Read the encrypted file in from disk
                   encFileIn.read(message);
                   SecretKeySpec spec = new SecretKeySpec(passwordToKey (passPhrase), "AES");
                   //decrypt it
                   Cipher c = Cipher.getInstance("AES/ECB/NoPadding");
                   c.init(Cipher.DECRYPT_MODE, spec);
                   System.out.println("Block Size is >-->" + c.getBlockSize());
                   String decryptedString = new String(c.doFinal(message));
                   System.out.println("Decrypted message: " + decryptedString);
                   //To write into another files
                   decFileOut.write(decryptedString.getBytes());
              }catch (Exception e) {
                   System.out.println(e);
              }finally {
                   try {
                        encFileIn.close();
                        decFileOut.close();     
                   } catch (IOException ioe) {
         }Is there any mechanism is available for FIPS81 or Is there any third party Provider available for it plz reply........????????

    I suggest you look in google http://www.google.co.uk/search?q=SWF+java

  • Cipher transformation that outputs non-padded plaintext final partial block

    I have written some Java code to read from and write to an existing data format that encrypts its data using a known symmetric key. It appears to be using the "AES/ECB/NoPadding" transformation / algorithm for all blocks, except for the final block, if the final block is a partial block. Any partial final block is just written out plaintext. When I use an "AES/ECB/NoPadding" Cipher in a CipherInputStream or a CipherOutputStream to read from or write to such a byte stream, respectively, everything works fine, except that any partial final block is omitted, as is expected from what I know of the behavior of "AES/ECB/NoPadding".
    (FYI, all of these questions relate to the Oracle JDK 7u2. For classes whose source is not included with this JDK, e.g., com.sun.crypto.provider.AESCipher, I looked at the source from the OpenJDK 7u2. I only looked at the default crypto provider included in the JDK, which I assume is the SunJCE, but I may be wrong.)
    1) Is there any other transformation that will properly decrypt / encrypt all the full blocks, but read / write, respectively, a partial final block as plaintext? (I assume not, but I also assume that it won't hurt to ask)
    2) Is there any way to obtain the buffered partial final block's data from Cipher? I can get the length of the leftover data from getOutputSize(0), but I haven't found a way to get the content. (I assume that this is done intentionally, to keep the Cipher-related classes as secure as possible)
    If I knew the length of the input, I could just determine the index of the end of the last full block, but I'd like this code to work with any arbitrary InputStream, and there's no way to know the length of an InputStream (without reading until you receive a -1, of course).
    I will probably wind up using a wrapping InputStream / OutputStream that always buffers the last partial block read from / written to it, respectively, until it's received a -1 from a read, or a flush call, respectively, but I wanted to avoid this if I could possibly use the crypto API more effectively.
    As an aside, I investigated exposing a partial final block's data by creating a wrapper class for one or more of the crypto classes. This appears difficult since many of these classes are final. Some other non-final crypto classes have final methods that use non-exposed private members, so those might be difficult, if not impossible, to wrap properly. The best plan that I devised is to create a CipherSpi subclass that wraps around a Cipher, and then use a Cipher subclass that wraps around both the wrapping CipherSpi subclass and the original Cipher. This appears convoluted, so I haven't yet thoroughly investigated its feasibility.
    I don't think that I can plug in a new mode or padding implementation to the existing SunJCE classes, since com.sun.crypto.provider.CipherCore seems to limit the potential implementations to those of which it is already aware.
    Please let me know if I've overlooked or misunderstood anything (this is the first time that I've used the crypto API).
    Thanks.

    Ross wrote:
    It's an existing data format from a huge company. I can't change it, so I cannot switch to CBC or any other mode that is not compatible with ECB for all but a partial final block. If the existing data format is not binary then you have another problem. Ciphertext is binary and storing binary in a 'char' or 'varchar' column is likely to corrupt the ciphertext and in order to reversibly convert it to ASCII or one of the other character encodings then you are going to have to encode it as Base64 (approx 33% inflation), Hex (100% inflation) or ASCII85 (approx 25% inflation).
    I'm just trying to read and write from it. I don't care about security, since the data is on my computer, and it's not sensitive data (at all; it's data about music files). I don't understand this. If it's not sensitive then why are you considering encrypting it? Seems to me to be a pointless requirement!
    I will never transmit the data anywhere, and, even if someone got hold of the data, I wouldn't care in the slightest.Again, why encrypt it then?
    >
    You're definitely right about it being a major security bug, though, so thanks for the recommendation. I just want a nice programmatic interface to read and write the data. I understand why the crypto API would want to make it difficult to obtain partial final block info, but was just wondering if there is any easy way to obtain it anyway. You could use one of the stream ciphers or one of the techniques that turns a block cipher into a stream cipher resulting in one byte per byte. To make it secure you will still need to use a random IV (or something similar) so there will still be an inflation. You can normally get away with just 8 bytes for the IV. The output is still binary bytes and will need to be encoded (Base64, Hex or ASCII85) if you are going to try to store it in a 'char' or 'varchar' which will result in further inflation.
    I just wrote the cyclic buffer & associated input & output streams, so I'll probably just use those since I probably won't be able to extricate the partial final block from the crypto classes.I don't understand this.
    Note - pretty much every time one encrypts data one ends up with ciphertext longer than the cleartext. This is fundamental to encryption and is nothing particularly to do with Java. One can often use compression of the original cleartext prior to encryption but this does not guarantee to result in smaller ciphertext than cleartext.
    Note 1 - it seems to me that all you are trying to do is obfuscate the data so why not just use a simple insecure substitution cipher? This way you end up with ciphertext of the same length as the cleartext and using the same character set so nothing in the database structure has to change.

  • Portability of encryption

    Hello,
    I have a Delphi application that is supposed to produce enrcypted files that will be decrypted with JCE code on a server. I have tried a couple of cryptology-components for Delphi but I can't seem to successfully decrypt them. No problems encrypting/decrypting within Delphi or Java but interoperability seems to be the problem even if I seem to have all hash/algorithm/mode/padding stuff matched.
    Is it usually problematic to en/decrypt between different implementations of the same algorithms? Anyone have any working combination figured out for the Delphi/Java combination?
    Thanks in advance,
    Nik

    Assuming no bugs, encryption algorithms don't care where they're being run or what language they're coded in. If you're having problems, there are two most likely sources of error.
    First, never accept the defaults for any encryption. Encryption requires more than just the algorithm name - there must also be a mode and a padding specified. A "full" spec is something like "AES/CBC/PKCS5Padding". If you just specify "AES," you're probably getting "AES/ECB/NoPadding". If that doesn't match the Delphi defaults - then nothing will work. Always fully specify your algorithm.
    The second most common problem involves transferring the ciphertext. If you're turning your ciphertext byte[] into a String (or its equivalent) ever - STOP THAT. Use Base64 to transfer ciphertext bytes as strings if you must. Ciphertext looks a lot like random noise - Strings have structure. Handing your ciphertext to a String constructor will turn it into junk.
    Beyond that, we'd need to see the code you're using to en/decrypt .
    Grant

  • Problem with RSA/AES and the wrapped Key

    Hallo!
    For a server-client communications, I would like to use a hybrid encryption.
    For this I create an object of a serializable class that contains several properties, including the data that are to be transferred from A to B (Object, encrypted by AES), and the AES key, but wrapped by RSA (byte []).
    My basic problem is, that if I send the wrapped key, I get at the destination another byte array and thus the key can not be decoded:
    java.security.InvalidKeyException: Invalid AES key length: 256 bytes
    When I look at the string representation of the byte array before sending and immediate after receiving, the byte arrays are diffrent. Why?
    Extract from the encrypt method:
    TransportObject obj = new TransportObject();
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        SecureRandom random = new SecureRandom();
        keygen.init(random);
        Key key = keygen.generateKey();
        Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");
        cipher.init(Cipher.WRAP_MODE, publicKey);
        byte[] wrappedKey = cipher.wrap(key);
    // Here I put the byte array in the object to be transmitted
        obj.setKey(wrappedKey);Extract from the decrypt method:
    / / Here I read the byte array from the received object
    byte[] wrappedKey = obj.getKey();
    Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");
    cipher.init(Cipher.UNWRAP_MODE, privateKey);
    Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);Here is the class that is serialized:
    import java.io.Serializable;
    public class TransportObject implements Serializable {
        private static final long serialVersionUID = 5044061539587999682L;
        private byte[] key;
        private String type;
        private byte[] data;
        public static final int STRING = 1;
        public static final int INT = 2;
        public static final int CHAR = 3;
        public TransportObject() {}
        public TransportObject(byte[] key, String type, byte[] data) {
            this.key = key;
            this.type = type;
            this.data = data;
        public byte[] getKey() {
            return key;
        public void setKey(byte[] key) {
            this.key = key;
    }Sending is done via:
    TransportObject obj = rsa.encrypt(objectToSend, keys.getPublicKey());
    ObjectOutputStream os =
        new ObjectOutputStream(socket.getOutputStream());
    os.writeObject(obj);
    os.flush();Receiving via
    ois = new ObjectInputStream(
        new BufferedInputStream(socket.getInputStream()));
    TransportObject obj = (TransportObject) ois.readObject();
    Object receivedObject = rsa.decrypt(obj, keys.getPrivateKey());Somehow, I hang down here.
    Do I overlook something? Do I have an error in reasoning?
    Thanks for any help!
    Best regards
    Sebastian Gohres
    Edited by: Spencer82 on Aug 7, 2010 9:06 AM
    Edited by: Spencer82 on Aug 7, 2010 9:08 AM

    Do I overlook something? Do I have an error in reasoning?I think at least 2.
    1. Don't do this. The general problem has been solved. The solution is called TLS, and Java provides a API called the JSSE for you to use.
    2.If you insist on rolling your own, don't specify NoPadding. Use PKCS1Padding. If you are going to use NoPadding, then you must provide your own padding scheme, which you have not.

  • Invalid stream header Exception - AES PBE with SealedObject

    I am trying to do an PBE encryption with AES algorithm and SunJCE provider, using the SealedObject class to encrypt/decrypt the data...
    And Im still getting the "invalid stream header" exception. Ive searched this forum, readed lots of posts, examples etc...
    Here is my code for encryption (i collected it from more classes, so hopefully I didnt forget anything...):
        //assume that INPUT_STREAM is the source of plaintext
        //and OUTPUT_STREAM is the stream to save the ciphertext data to
        char[] pass; //assume initialized password
        SecureRandom r = new SecureRandom();
        byte[] salt = new byte[20];
        r.nextBytes(salt);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec keySpec = new PBEKeySpec(pass, salt, 1536, 128);
        SecretKey pbKey = factory.generateSecret(keySpec);
        SecretKeySpec key = new SecretKeySpec(pbKey.getEncoded(), "AES");
        Cipher ciph = Cipher.getInstance("AES/CTR/NoPadding");
        ciph.init(Cipher.ENCRYPT_MODE, key);
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        int ch;
        while ((ch = INPUT_STREAM.read()) >= 0) {
          byteOut.write(ch);
        SealedObject sealed = new SealedObject(byteOut.toByteArray(), ciph);
        BufferedOutputStream bufOut = new BufferedOutputStream(OUTPUTSTREAM);
        ObjectOutputStream objOut = new ObjectOutputStream(bufOut);   
        objOut.writeObject(sealed);
        objOut.close();
      }And here is my code for decrypting:
        //assume that INPUT_STREAM is the source of ciphertext
        //and OUTPUT_STREAM is the stream to save the plaintext data to
        char[] pass; //assume initialized password
        SecureRandom r = new SecureRandom();
        byte[] salt = new byte[20];
        r.nextBytes(salt);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec keySpec = new PBEKeySpec(pass, salt, 1536, 128);
        SecretKey pbKey = factory.generateSecret(keySpec);
        SecretKeySpec key = new SecretKeySpec(pbKey.getEncoded(), "AES");
        BufferedInputStream bufIn = new BufferedInputStream(INPUT_STREAM);    //MARK #1
        ObjectInputStream objIn = new ObjectInputStream(bufIn);   
        SealedObject sealed = (SealedObject) objIn.readObject();   
        byte[] unsealed = (byte[]) sealed.getObject(key);          //MARK #2
        ByteArrayInputStream byteIn = new ByteArrayInputStream(unsealed);
        int ch;
        while ((ch = byteIn.read()) >= 0) {
          OUTPUT_STREAM.write(ch);
        OUTPUT_STREAM.close();Everytime I run it, it gives me this exception:
    Exception in thread "main" java.io.StreamCorruptedException: invalid stream header: B559ADBE
         at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:783)
         at java.io.ObjectInputStream.<init>(ObjectInputStream.java:280)
         at javax.crypto.SunJCE_i.<init>(DashoA13*..)
         at javax.crypto.SealedObject.unseal(DashoA13*..)
         at javax.crypto.SealedObject.getObject(DashoA13*..)
         at oopsifrovanie.engine.ItemToCrypt.decrypt(ItemToCrypt.java:91)  //MARKED AS #2
         at oopsifrovanie.Main.main(Main.java:37)    //The class with all code below MARK #1I've also found out that the hashCode of the generated "key" object in the decrypting routine is not the same as the hashCode of the "key" object in the ecrypting routine. Can this be a problem? I assume that maybe yes... but don't know what to do...
    When I delete the r.nextBytes(salt); from both routines, the hashCodes are the same, but that's not the thing I want to do...
    I think, that the source of problem can be this part of code (generating the key):
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec keySpec = new PBEKeySpec(pass, salt, 1536, 128);
        SecretKey pbKey = factory.generateSecret(keySpec);
        SecretKeySpec key = new SecretKeySpec(pbKey.getEncoded(), "AES");But I derived it from posts like: [http://forums.sun.com/thread.jspa?threadID=5307763] and [http://stackoverflow.com/questions/992019/java-256bit-aes-encryption] and they claimed it's working there...
    Is there anyone that can help me?
    Btw, I don't want to use any other providers like Bouncycastle etc. and I want to use PBE with AES and also SealedObject to store the parameters of encryption...

    Yes, it really uses only one Cipher object, but it does decoding in a little nonstandard (not often used) way, by using the SealedObject class and its getObject(Key key) method. You can check these links for documentation: [http://java.sun.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html#SealedObject] and [http://java.sun.com/javase/6/docs/api/javax/crypto/SealedObject.html] So the question is, why it doesn't work also with the AES routines, because it should.
    Btw, according to [http://java.sun.com/javase/6/docs/technotes/guides/security/SunProviders.html#SunJCEProvider] PBEWithSHA1AndDESede/CBC/PKCS5Padding is a valid JCE algorithm for the Cipher class.
    Firstly, I was generating the key for AES enc./decryption this way and it was working:
    char[] pass; //assume initialized password
    byte[] bpass = new byte[pass.length];
        for (int i = 0; i < pass.length; i++) {
          bpass[i] = (byte) pass;
    SecretKeySpec key = new SecretKeySpec(bpass, "AES");
    But I think, that it really wasn't secure, so I wanted to build a key from the password using the PBE.
    Maybe there's also a way how to do this part of my AES PBE algorithm: *KeySpec keySpec = new PBEKeySpec(pass, salt, 1536, 128);* manually (with my own algorithm), but I dont know how to do it and I'd like it to be really secure.
    Btw, thanks for your will to help.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How to decrypt AES using a key

    The example here will Generate the secret key specs first.
    http://java.sun.com/developer/technicalArticles/Security/AES/AES_v1.html
    I already have a Decrypt Key used in my server application. How can I use that key to decrypt the msg sent from server?

    Hi
    I wrote this code to check Java encryption with AES and a key. This worked fine for me. Please have a look.
    Encrypt and decrypt using the DES private key algorithm
    import java.security.*;
    import javax.crypto.*;
    import javax.crypto.spec.SecretKeySpec;
    import org.bouncycastle.jce.provider.BouncyCastleProvider;
    public class AESEncrypt {
        public static void main (String[] args) throws Exception {
            Security.addProvider(new BouncyCastleProvider());
            byte[] plainText = "LOGIN=2222=v2-0-b7=SMST=smst=ASI".getBytes("utf-8");
            // Get a DES private key
            System.out.println( "\nAES key" );
            String strKey = "75de8a33d3f18f1c29d86fa42b1894c7";
            byte[] keyBytes = hexToBytes(strKey);
            // skeyspec is the key to encrypt and decrypt
            SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, "AES");
            System.out.println("Key: " + asHex(key.getEncoded()));
            System.out.println( "Finish generating AES key" );
            // Creates the DES Cipher object (specifying the algorithm, mode, and padding).
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
            // Print the provider information
            System.out.println( "\n" + cipher.getProvider().getInfo() );
            System.out.println( "\nStart encryption" );
            // Initializes the Cipher object.
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            // Encrypt the plaintext using the public key
            byte[] cipherText = cipher.doFinal(plainText);
            System.out.println( "Finish encryption: cipherText: " + asHex(cipherText));
            System.out.println( "\nStart decryption" );
            // Initializes the Cipher object.
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            // Decrypt the ciphertext using the same key
            byte[] newPlainText = cipher.doFinal(cipherText);
            System.out.println( "Finish decryption: " );
            System.out.print( asHex(newPlainText) );
        public static String asHex (byte buf[]) {
          StringBuffer strbuf = new StringBuffer(buf.length * 2);
          int i;
          for (i = 0; i < buf.length; i++) {
           if (((int) buf[i] & 0xff) < 0x10)
             strbuf.append("0");
           strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
          return strbuf.toString();
        public static byte[] hexToBytes(char[] hex) {
            int length = hex.length / 2;
            byte[] raw = new byte[length];
            for (int i = 0; i < length; i++) {
                int high = Character.digit(hex[i * 2], 16);
                int low = Character.digit(hex[i * 2 + 1], 16);
                int value = (high << 4) | low;
                if (value > 127) value -= 256;
                raw[i] = (byte)value;
            return raw;
        public static byte[] hexToBytes(String hex) {
            return hexToBytes(hex.toCharArray());
    }

  • AES SecretKeyFactory not available

    Hi,
    I found that there is a bug in using SecretKeyFactory keyFactory with reference to http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7022467
    I tried implementing with KeySpec too,but found one or the other error.
    I'm posting here my code.Please help me out to decrypt.
    import javax.crypto.Cipher;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.SecretKeySpec;
    import org.apache.commons.codec.binary.Hex;
    public class DecryptTest {
         public static void main(String[] args) throws Exception {
              String keyStr = "6a6b663472346c38736873346569727538346234333534376635333962353666";
              String eid = "bf940165bcc3bca12321a5cc4c753220129337b48ad129d880f718d147a2cd1bfa79de92239ef1bc06c2f05886b0cd5d";
              String rid = "00028e7353d9c4eca480a57a1ca9ba9b";
              int keysize = 256;
              // decode the key string into bytes (using Apache Commons)
              byte[] keyBytes = Hex.decodeHex(keyStr.toCharArray());
              // create a representation of the key
              SecretKeySpec spec = new SecretKeySpec(keyBytes, "AES");
              // turn the key spec into a usable key
              SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("AES");
              SecretKey key = keyFactory.generateSecret(spec);
              // use a cipher to decrypt the eid
              Cipher cipher = Cipher.getInstance("AES");
              cipher.init(Cipher.DECRYPT_MODE, key);
              byte[] plainText = cipher.doFinal(Hex.decodeHex(eid.toCharArray())); // decode from Hex again
              String Eid = new String(plainText, "ASCII");
              System.out.println(Eid);
    }

    964782 wrote:
    well I'm new to this encryption...and the work around again gave the same error..
    import java.security.spec.KeySpec;
    import javax.crypto.Cipher;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.SecretKeySpec;
    import org.apache.commons.codec.binary.Hex;
    public class DecryptTest {
         public static void main(String[] args) throws Exception {
              String keyStr = "6a6b663472346c38736873346569727538346234333534376635333962353666";
              String eid = "bf940165bcc3bca12321a5cc4c753220129337b48ad129d880f718d147a2cd1bfa79de92239ef1bc06c2f05886b0cd5d";
              String rid = "00028e7353d9c4eca480a57a1ca9ba9b";
              int keysize = 256;
              // decode the key string into bytes (using Apache Commons)
              byte[] keyBytes = Hex.decodeHex(keyStr.toCharArray());
              // create a representation of the key
              SecretKey spec = new SecretKeySpec(keyBytes, "AES");
              // turn the key spec into a usable key
              SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("AES");
              SecretKey key = keyFactory.generateSecret((KeySpec) spec);
              // use a cipher to decrypt the eid
              Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
              cipher.init(Cipher.DECRYPT_MODE, key);
              byte[] plainText = cipher.doFinal(Hex.decodeHex(eid.toCharArray())); // decode from Hex again
              String Eid = new String(plainText, "ASCII");
              System.out.println(Eid);
    I obviously did not make is clear enough. You don't actually need a SecretKeyFactory; you just generate the key using
    SecretKey key = new SecretKeySpec(keyBytes, "AES");This way you don't need to use a SecretKeyFactory. Just use the above key to init() the Cipher.
    and also I didn't get you on " The ciphertext in your code was not generated using the key in your code."
    Thanks for your help!!If I apply the change I suggest I get
    javax.crypto.BadPaddingException: Given final block not properly paddedwhich implies either the key is wrong or the ciphertext was not generated using the key or the block mode was different or the padding was different. For any given key bytes I can use AES in the JCE to decrypt ciphertext generated using both the BouncyCastle lightweight API and the OpenSSl library so I'm pretty sure the decryption process is correct so I think that your encryption process did not use that key or a different block mode was used or a different padding was used. Since I don't know how you generated that ciphertext I can't be more specific.

  • Security comments, am I on track? Encryption using AES

    I have implemented a crypto, but I cant say that I fully understand every step and hence not how secure it is/isnt.
    One thing I noticed was if I generated keys with a length other than 128/192/256 I got Exception in thread "main" java.security.InvalidKeyException: Key length not 128/192/256 bits
    I also wonder about the ivBytes, should I generate them in some specific way?
    Any other comments are also very appreciated.
    I genereate a key like this    SecureRandom     random = new SecureRandom();
        javax.crypto.KeyGenerator generator = KeyGenerator.getInstance("AES", "BC");
        generator.init(256, random);
        Key encryptionKey = generator.generateKey();
    //Save to fileEncode like this
    byte[]        input = "SOME SECRET OF MINE".getBytes();
        //Read key from file
        byte[]          ivBytes = new byte[] {
          0x00, 0x00, 0x00, 0x01, 0x04, 0x05, 0x06, 0x07,
          0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 };
        Cipher          cipher = Cipher.getInstance("AES/CTS/NoPadding", "BC");
           cipher.init(Cipher.ENCRYPT_MODE, encryptionKey,
          new IvParameterSpec(ivBytes));
        byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
        int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
        ctLength += cipher.doFinal(cipherText, ctLength);
    //Save ciphertext to fileDecode like this
    byte[]          ivBytes = new byte[] {
          0x00, 0x00, 0x00, 0x01, 0x04, 0x05, 0x06, 0x07,
          0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 };
        //Read cipher from file
        //Read key from file
        Cipher          cipher = Cipher.getInstance("AES/CTS/NoPadding", "BC");
        cipher.init(Cipher.DECRYPT_MODE, decryptionKey,
          new IvParameterSpec(ivBytes));
        byte[] cipherBytes = Utils.fromHex(cipherText);
        byte[] plainText = new byte[cipher.getOutputSize(cipherBytes.length)];
        int ptLength = cipher.update(cipherBytes, 0, cipherBytes.length, plainText, 0);
        ptLength += cipher.doFinal(plainText, ptLength);
                                     System.out.println(ptLength);
        System.out.println("Hidden was:" + Utils.toString(plainText));

    No.
    I will repeat one of Tom Kytes' mantras here
    1 when you can do it in 1 SQL statement, you should do it in SQL
    2 When you can not do it in SQL, you should do it in PL/SQL
    3 When you can not do in in PL/SQL, you should do it in Java
    Which means: You should things non-procedurally as often as possible. Quite often people resort too early to 3GL strategies.
    update inside a loop raises a red flag, especially if there would have been a commit inside this loop. This means you are not only into slow-by-slow prtogramming, but also increases the possibility of ora-15555 errors.
    Sybrand Bakker
    Senior Oracle DBA

  • Equivalent code in JCE for the given C# AES code

    Can somebody give me the equivalent code in JCE for the given C# AES code below?
    (Ofcourse, I checked this topic
    http://forum.java.sun.com/thread.jspa?threadID=603209
    as well, but couldn't figure out much; I have
    little knowledge in this area; I've a job to figure out an equivalent code for
    this and use it in JSP.)
    Thanks,
    RK.
    byte[] bytesToEncrypt = ASCIIEncoding.ASCII.GetBytes(stringToEncrypt);
    //RijndaelManaged uses AES and defaults to CBC mode
    RijndaelManaged rij = new RijndaelManaged();
    rij.KeySize = 128;
    ICryptoTransform encryptor = rij.CreateEncryptor(
                     Convert.FromBase64String("7inEMafSQqaSANhMe92Gdw=="), initializationVectorBytes );
    byte[] encryptedBytes = encryptor.TransformFinalBlock(bytesToEncrypt, 0, bytesToEncrypt.Length);

    Hello...
    I've come up with this source, based on the examples given out there
    but, the ultimate output is will be an URL that'll be submitted as request.
    Looks like the data length is very high (as I get some error from the
    server, when I send the request url).
    Just wondering how do I make this code to do the same thing as given
    in the C# code above.
    Any help appreciated.
    Thanks,
    RK.
    private static String getEncryptedLogonData() throws Exception {
              String userDataToEncrypt = "Text";          
              return encrypt(userDataToEncrypt, getIV());;
         public static String encrypt(String text, byte[] iv) throws Exception {
              //Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
              Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
              //setup key
              byte[] keyBytes = new byte[16];
              int len = iv.length;
              if (len > keyBytes.length)
                   len = keyBytes.length;
              System.arraycopy(iv, 0, keyBytes, 0, len);
              SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
              //the below may make this less secure, hard code byte array the IV in
              // both java and .net clients
              IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
              cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
              byte[] results = cipher.doFinal(text.getBytes("UTF-8"));
              BASE64Encoder encoder = new BASE64Encoder();
              return encoder.encode(results);
         private static byte[] getIV() {
              byte[] iv = new byte[16];
              Random r = new Random();
              r.nextBytes(iv);
              return iv;
         }

  • AES encrypt and decrypt not the same

    I use aes to encrypt and decrypt a file. Why is the resulting file not the same as the input?
    package mybeans;
    import java.io.*;
    import java.sql.Blob;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.Hashtable;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    public class Encrypt {
         public static void main(String args[]) throws Exception {
              Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
              SecretKeySpec keySpec = new SecretKeySpec(
                        "05468345670abcde".getBytes(), "AES");
              IvParameterSpec ivSpec = new IvParameterSpec("f45gt7g83sd56210"
                        .getBytes());
              cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
              FileInputStream fis = new FileInputStream(new File("C:\\text.txt"));
              CipherInputStream cis = new CipherInputStream(fis, cipher);
              FileOutputStream fos = new FileOutputStream(new File(
                        "C:\\encrypted.txt"));
              byte[] b = new byte[8];
              int i;
              while ((i = cis.read(b)) != -1) {
                   fos.write(b, 0, i);
              fos.flush();
              fos.close();
    package mybeans;
    import java.io.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    public class Decrypt {
         public static void main(String args[]) throws Exception {
              Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
              SecretKeySpec keySpec = new SecretKeySpec(
                        "05468345670abcde".getBytes(), "AES");
              IvParameterSpec ivSpec = new IvParameterSpec("f45gt7g83sd56210"
                        .getBytes());
              cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
              FileInputStream fis = new FileInputStream(new File("C:\\encrypted.txt"));
              CipherInputStream cis = new CipherInputStream(fis, cipher);
              FileOutputStream fos = new FileOutputStream(new File(
                        "C:\\decrypted.txt"));
              byte[] b = new byte[8];
              int i;
              while ((i = cis.read(b)) != -1) {
                   fos.write(b, 0, i);
              fos.flush();
              fos.close();
              cis.close();
              fis.close();
    }Here is the data in the file:
    James,"smith",007
    mike,"smith",001
    the result is this:
    James,"smith",007
    mike,"smith",
    Edited by: iketurna on Jun 3, 2008 1:47 PM

    Thanks sabre!
    Very insightful.
    I used PKCS5Padding and the file has all of the data, but there are extra padding at the end of the second line
    Also,
    how would you store your key and iv?
    Currently I using this to create the iv and key:
    public class KeyClass {
    private SecretKeySpec keygeneration() {
    SecretKeySpec skeySpec=null;
    try {
      KeyGenerator kgen = KeyGenerator.getInstance("AES");
      kgen.init(128);
      SecretKey skey = kgen.generateKey();
      byte[] key = skey.getEncoded();
      skeySpec = new SecretKeySpec(key,"AES");
    }catch(Exception e) {
      System.out.println("error in keygen = "+e);
    return skeySpec;
    public void keyFile() {
    try{
    FileOutputStream fos=new FileOutputStream("c:\\keyFile.txt");
    DataOutputStream dos=new DataOutputStream(fos);
    SecretKeySpec skeySpec=keygeneration();
    byte[] key=skeySpec.getEncoded();
    BASE64Encoder base64 = new BASE64Encoder();
    String encodedString = base64.encodeBuffer(key);
    dos.write(encodedString.getBytes());
    }catch(Exception e1){
      System.out.println("error file write "+e1);
    public static void main(String args[]){
      KeyClass cKey = new KeyClass();
      cKey.keyFile();
    }Edited by: iketurna on Jun 5, 2008 7:29 AM

Maybe you are looking for