AES Cipher on Javacard 2.1.1

Hy,
i've implemented the AES Cipher on Javacard 2.1.1.
If you are interested, you can download the code
from: http://java.ittoolbox.com/code/d.asp?d=2728&a=s
have fun
snoopy

Great start!
However your code require lot of improvements before it can be used for anything real. The fact that JavaCard does not have GC results in memory leak in your code for each process() method call. So, you should use "new" only in the constructor/init of the applet. Moreover, for such temporary bufers you should use transient arrays but still create them only once in init method. Keep in mind that javacard code no need to be thread safe, so it will not be called concurrently.

Similar Messages

  • KeyAgreement can't generate AES Cipher

    Hi,
    I tried to generate a SecretKey out of a completed Diffie-Hellamn KeyAgreement but it doesn't work.
    If I use keyAgreement.generate("DESede"); with J2SE 1.4.2 it functions properly, but if I use "AES" instead it throws a NoSuchAlgorithmException.
    Does anyone know how to use AES for Secret generation with a KeyAgreement?
    Thanks
    Surfaczer

    The diffie hellmen implementation must support the creation of AES
    keys. Just because a provider supports AES does not mean their DH
    implementation does and chances are that is what is wrong. Sun's
    DH impl explicitly checks the alg name and does a if / else if
    operation to create appropriate sized keys. AES supports variable
    size keys. So what should the alg name AES create? And now you
    see the crux of the problem. AES has several OIDs which define
    AES in various modes of operation and with various key sizes.
    Those might more accurately define the key size desired but there
    is a problem. Sun's if / else if doesn't really fit that model...
    So I will bet that they just haven't implemented it yet primarily
    because they need to define the algorithm names they will support.
    For example maybe AES-128 or aes128 or something like that... Of
    course it could just be an oversight as well. Someone would have
    to go back and modify their existing DH code to add AES support
    and maybe they forgot. Maybe you should post a bug report and see
    what they say!

  • Unwrap key using javacard

    How can I use a javacard to unwrap a key? At the moment I do the unwrapping in the offcard application, but for unwrapping the private key is needed (I have an aes-key wrapped with RSA). And the private key should not leave the javacard. So I send the wrapped bytes to the card. But I can't find in javavardx.crypto.Cipher something like UNWRAP_MODE.
    In my offcard application I used:
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING", "BC");
    cipher.init(Cipher.UNWRAP_MODE, privateKey);
    SecretKey key = (SecretKey)cipher.unwrap(wrappedKeyBytes, "AES", Cipher.SECRET_KEY); Susanne

    Unwrapping keys in Java Card is done via the keyEncryption parameter (check the methods in the security package which do key modification). Key encryption is optional, and e.g. JCOP products don't support it.
    The most convinient option is the transmission of key information via a GP secure channel. In case of the e.g. PUT KEY command the keys must be encrypted, independent of the the secure channel (authentication, C_MAC, C_ENC - the smart card OS decrypts it automatically and stores it in the CM key storage). You can encrypt any information via the CM encryption key (session key, don't forget the MAC) and use the GP API command to unwrap() the key. There is a drawback though: GP 2.1.1 supports only symmetric (3DES) encryption.
    If your requirement is key encryption with RSA you need to program it by yourself in the applet.

  • 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.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • 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.

  • AES Algorithm error when trying to encrypt using stored Java class.

    Dear All,
    We have a specific reuirement where in we cannot use DBMS_CRYPTO package to encrypt/decrypt data using AES Algorithm
    So I am trying to use a stored Java class and I am getting "AES algorithm not available".
    I am using Oracle 10gR2 standard edition.
    Below is my code
    1. Stored Java class
    2. Stored function to access the above Java class.
    3. Test anonymus PL/SQL to test above code.
    Please help me finding the problem why I am getting "AES algorithm not available" error when I call stored Java class in Oracle.?
    **** If I use "DES" algorithm, it works. Also the Java code works well if I execute it as normal Java class from Eclipse.
    I verified the java.security file in jre/lib/security and I see that there is provider entry for SunJCE.
    The jre version in Oracle is 1.4.2.
    I appreciate your help.
    Thanks,
    Priyanka
    Step1: Stored java class to encrypt and decrypt data
    CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED "EncryptUtil" AS
    import java.security.Key;
    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;
    public class EncryptUtil
         public static String encrypt(String inStr)
         String outStr = "Test data 123";
    try
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(128);
    SecretKey skey = kgen.generateKey();
    byte[] raw = skey.getEncoded();
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] encrypted =
    cipher.doFinal(inStr.getBytes());
    outStr =new String(encrypted);
    catch (Exception e)
         outStr = outStr + "exception thrown::" + e.getMessage();
    e.printStackTrace();
    return outStr;
    Step2: Stored function to access above stored java class.
    CREATE OR REPLACE FUNCTION SF_ENCRYPTUTIL(
    pKey1 VARCHAR2
    ) RETURN VARCHAR2 AS
    LANGUAGE JAVA NAME 'EncryptUtil.encrypt(java.lang.String ) return java.lang.String';
    Step3: Test encryption and descryption
    DECLARE
    outstr VARCHAR2(2000);
    BEGIN
    DBMS_OUTPUT.PUT_LINE('outstr-->' || SF_ENCRYPTUTIL('12345'));
    END;
    Below code example using DBMS_CRYPTO. This works, but we do not want to use this.
    declare
    l_in_val varchar2(2000) := 'Test data 123';
    l_mod number := dbms_crypto.ENCRYPT_AES128
    + dbms_crypto.CHAIN_CBC
    + dbms_crypto.PAD_PKCS5;
    l_enc raw (2000);
    l_enc_key raw (2000);
    l_dec raw (2000);
    begin
    l_enc := dbms_crypto.encrypt
    UTL_I18N.STRING_TO_RAW (l_in_val, 'AL32UTF8'),
    l_mod,
    HEXTORAW('156ae12300ccfbeb48e43aa016febb36'),
    HEXTORAW('001122230405060708090a0b0c0d0e0f')
    dbms_output.put_line ('Encrypted='||l_enc);
    end;
    Edited by: user5092433 on Sep 10, 2009 12:26 AM

    I guess I'd be a bit curious about why you can't use a DBMS_CRYPTO solution that provides identical output. It seems odd to want to have a procedure running inside Oracle and then dictate that it has to be Java and not PL/SQL...
    I verified the java.security file in jre/lib/security and I see that there is provider entry for SunJCE.
    The jre version in Oracle is 1.4.2.Which java.security file are you talking about? The JVM that is inside the Oracle database does not and can not use configuration files that are outside the database. I suspect when you talk about files and paths that you're looking at a JVM outside the database, which is not the JVM that your Java stored procedure would be using.
    Looking at the error, my assumption is that some JAR file needs to be loaded into the internal JVM in order for the AES algorithm to be available. But I'm unfortunately not familiar enough with these classes to say what that would be.
    Justin

  • How to know whether data is being AES crypted or not?

    Hi Forum,
    I used AES crypting with an initial vector and a SecretKey.
    The problem is , for backward compatibility I need to check if the data had been crypted or not?
    if not crypted I need to show them in plain readable format instead of decrypting them.
    below is my Encryption/Decryption class
    public class AesEncryption
        private  final String CRYPTO_ALGO_= "AES";
        Cipher aesCipher_;
    // Create an 16-byte initialization vector
        private final byte[] initialVector_ = new byte[]{
                                                        (byte)0x8E, 0x12, 0x39, (byte)0x9C,
                                                              0x07, 0x72, 0x6F, 0x5A,
                                                        (byte)0x8E, 0x12, 0x39,(byte)0x9C,
                                                              0x07, 0x72, 0x6F, 0x5A
        private final SecretKey key_ = new SecretKeySpec(initialVector_, CRYPTO_ALGO_);
        public AesEncryption()
             *  Create a Cipher by specifying the following parameters
             *     Algorithm name - here it is AES
            try
                 aesCipher_ = Cipher.getInstance(CRYPTO_ALGO_);
            catch (NoSuchAlgorithmException e)
                e.printStackTrace();
            catch (NoSuchPaddingException e)
                e.printStackTrace();
        public  String encryptPassword(String password)
            String strEncryptedText ="";
            try{
             *  Initialize the Cipher for Encryption with secret key
            aesCipher_.init(Cipher.ENCRYPT_MODE,key_);
             *   Encrypt the password
            byte[] byteDataToEncrypt = password.getBytes();
            byte[] byteCipherText = aesCipher_.doFinal(byteDataToEncrypt);
                   strEncryptedText = new BASE64Encoder().encode(byteCipherText);
            catch (InvalidKeyException e)
                 e.printStackTrace();
            catch (BadPaddingException e)
                 e.printStackTrace();
            catch (IllegalBlockSizeException e)
                 e.printStackTrace();
            return strEncryptedText;
        public String decryptPassword(String encryptedPassword)
            String strDecryptedText = "";
            try
                 * Decrypt the Data
                byte[] byteCipherText = new BASE64Decoder().decodeBuffer(encryptedPassword.trim());
                aesCipher_.init(Cipher.DECRYPT_MODE,key_,aesCipher_.getParameters());
                byte[] byteDecryptedText = aesCipher_.doFinal(byteCipherText);
                strDecryptedText = new String(byteDecryptedText);
            catch (InvalidKeyException invalidKey)
                 invalidKey.printStackTrace();
            catch (BadPaddingException badPadding)
                 badPadding.printStackTrace();
            catch (IllegalBlockSizeException illegalBlockSize)
                 illegalBlockSize.printStackTrace();
            catch (InvalidAlgorithmParameterException invalidParam)
                 invalidParam.printStackTrace();
            catch (IOException e)
                e.printStackTrace();
            return strDecryptedText;
    } I just want to have a method like boolean isAESEncrypted(String data){ ????  } in my class.
    Could anybody give a helping hand for the same?
    Many thanks in advance
    Edited by: jagabandhu on Sep 16, 2010 10:54 AM

    jagabandhu wrote:
    I do have a choice to store the encrypted data only in 'varchar' format so I have to encrypt and store the password without changing the column data type in the database!
    Again many thanks for 'Notes:' these are definitely helpful.
    sabre150 wrote:
    If you have a choice, then you should add a digest of the cleartext to the ciphertext. ...I fear if I use any MessageDigest , my password will be byte[] instead present String format.Not relevant since you Base64 encode the ciphertext you can also Base64 encode the digest!
    for e.g.
    [http://gmailassistant.sourceforge.net/src/org/freeshell/zs/common/Encryptor.java.html]
    Could you please further guide me if I am in the right track?I thought I had guided you! I have pointed out what I see as the flaws in your code and I think you should use the more normal approach of just using a randomly seeded Message Digest.
    >
    FYI : I do not need a serious encryption format as per the present requirement. :)That is not serious encryption since it has at least 3 major security flaws.
    >
    Edited by: jagabandhu on Sep 16, 2010 1:17 PM

  • 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.

  • AES encriptation

    Hi, first my english is bad.
    I have this code for AES enc/dec
    import java.security.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.io.*;
    * This program generates a AES key, retrieves its raw bytes, and
    * then reinstantiates a AES key from the key bytes.
    * The reinstantiated key is used to initialize a AES cipher for
    * encryption and decryption.
    public class AES {
    String palabra;
    byte[] par;
    SecretKeySpec skeySpec;
    //IvParameterSpec IvParameters;
    public AES(String mesagge){
    palabra="The Password";
    par=palabra.getBytes();
    skeySpec = new SecretKeySpec(par,"AES");
    byte[] cc=encripta(mesagge);
    String real=desencripta(cc);
    * Turns array of bytes into string
    * @param buf     Array of bytes to convert to hex string
    * @return     Generated hex string
    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 message="This is just an example";
    System.out.println(message);
    AES aes=new AES(message);
    public byte[] encripta(String mensage){
    try{
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] encrypted=cipher.doFinal(mensage.getBytes());
    System.out.println("encrypted string: " + asHex(encrypted));
    return encrypted;
    }catch(Exception e){
    e.printStackTrace();
    return null;
    public String desencripta(byte[] mensage){
    try{
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    byte[] original=cipher.doFinal(mensage);
    String originalString = new String(original);
    return originalString;
    }catch(Exception e){
    e.printStackTrace();
    return "";
    I have the following error
    java.security.InvalidKeyException: Invalid AES key length: 96
    at com.sun.crypto.provider.SunJCE_e.a(DashoA12275)
    at com.sun.crypto.provider.SunJCE_i.a(DashoA12275)
    at com.sun.crypto.provider.SunJCE_h.a(DashoA12275)
    at com.sun.crypto.provider.SunJCE_h.a(DashoA12275)
    at com.sun.crypto.provider.AESCipher.engineInit(DashoA12275)
    at javax.crypto.Cipher.a(DashoA12275)
    at javax.crypto.Cipher.a(DashoA12275)
    at javax.crypto.Cipher.init(DashoA12275)
    at javax.crypto.Cipher.init(DashoA12275)
    at com.archicentro.scav.encriptador.AES.encripta(AES.java:77)
    at com.archicentro.scav.encriptador.AES.<init>(AES.java:39)
    at com.archicentro.scav.encriptador.AES.main(AES.java:69)
    Can help me with this?

    you should know the key length for AES.that's where the mistake is.

  • Bug in Cipher ?

    I ve come across what I believe is a bug in the JRE. Posting to this forum to get input from someone else and double check I m not missing something before I submit a bug report.
    In a nutshell, if I pass a bytebuffer which has a position >0 to the method
    doFinal(clearBuffer, outBuffer); for the output buffer, the encryption gets corrupted every 4K bytes, for one full padding of 16 bytes. (encryption is correct for the first 4096 bytes)
    If I don t advance the position, the encryption works fine.
    package test;
    import java.nio.ByteBuffer;
    import java.util.Random;
    import javax.crypto.Cipher;
    import javax.crypto.spec.SecretKeySpec;
    public class EncryptionBug {
         // set this buffer to at least 4096 bytes for the bug to appear
         static int BUFFER_LENGTH = 4111;
         //set this offset to >0 for the bug to appear
         static int OUTPUT_OFFSET = 4;
         public static void main(String[] args) {
              byte[] encryptionKey = new byte[16];
              new Random().nextBytes(encryptionKey);
              Cipher cipherEncrypt;
              try {
                   SecretKeySpec skeySpec = new SecretKeySpec(encryptionKey, "AES");
                   cipherEncrypt = Cipher.getInstance("AES");
                   Cipher cipherDecrypt = Cipher.getInstance("AES");
                   cipherEncrypt.init(Cipher.ENCRYPT_MODE, skeySpec);
                   cipherDecrypt.init(Cipher.DECRYPT_MODE, skeySpec);
                   byte data[] = new byte[BUFFER_LENGTH];
                   new Random().nextBytes(data);
                   ByteBuffer outBuffer = ByteBuffer.allocateDirect(65536);
                   ByteBuffer clearBuffer = outBuffer.duplicate();
                   clearBuffer.put(data);
                   clearBuffer.flip();
                   outBuffer.position(OUTPUT_OFFSET);
                   int length = cipherEncrypt.doFinal(clearBuffer, outBuffer);
                   byte[] encryptedBuffer = new byte[length];
                   for (int i = 0; i < encryptedBuffer.length; i++) {
                        encryptedBuffer[i] = outBuffer.get(OUTPUT_OFFSET + i);
                   byte encryptedDirect[] = cipherEncrypt.doFinal(data);
                   for (int i = 0; i < encryptedBuffer.length; i++) {
                        if (encryptedDirect[i] != encryptedBuffer) {
                             System.out.println("********* corrupted index " + i + " "
                                       + encryptedBuffer[i] + " vs " + encryptedDirect[i]);
              } catch (Exception ex) {
                   ex.printStackTrace();

    Having looked at the Javadoc for duplicate() I seepublic abstract ByteBuffer duplicate()
        Creates a new byte buffer that shares this buffer's content.
        The content of the new buffer will be that of this buffer. Changes to this buffer's content will be visible in the new buffer, and vice versa; the two buffers' position, limit, and mark values will be independent.
        The new buffer's capacity, limit, position, and mark values will be identical to those of this buffer. The new buffer will be direct if, and only if, this buffer is direct, and it will be read-only if, and only if, this buffer is read-only.which indicates that the two buffers will have the same capacity and that they share the same backing array. This means that your outBuffer and your clearBuffer share the same byte array.
    Your cipher is reading from one buffer and writing to the other which means it is overwriting the original data! At best this seems dangerous.
    Based on this, I don't think you have found a bug in Cipher.

  • AES-256, BouncyCastle, Sun Crypto Providers, Default Padding

    Hi,
    The subject alsmost says it all, but in a nutshell, I would like to use BC for AES-256. I also wanted to compare the ciphered outputs from both BC and SUN to make sure everything was working ok (I have installed the Unlimited Strength Jurisdiction Policy Files 6 for the Sun JRE 6).
    I have noticed the following, when the data input is a multiple of 16, the ciphered data generated by both engines are the same (Sun = AES, BC = PaddedBufferedBlockCipher(AES Engine) + PKCS7Padding).
    However, when the data input is not of a multiple of 16 - the ciphered output is different.
    Hence my question: What is the default padding and mode used by the Sun JCE when doing a getInstance("AES") ?
    How to make sure that the ciphered data is the same for both engines, regardless of the data input length pls?
    Thx

    Hi,
    So what is the problem with using the BC provider?
    The problem with using the BC provider is that if you have a web started application, the lambda user should not worry about installing an extra set of files for the JRE. And that lambda user might not know at all how to install the policy file as well. (Note that this policy is only required on Windows - works fine on Mac). All of this for AES-256 should be transparent.
    Code for Sun JCE
    public String encryptToBase64(String data) throws Exception {
              Cipher cipher = Cipher.getInstance(aesCipher); // "AES"
             cipher.init(Cipher.ENCRYPT_MODE, secretKey);
             final byte[] newData = EncryptionUtils.getBytes(data);
             final byte[] edata = cipher.doFinal(newData);
             return Base64.encodeBase64String(edata);
    Code for BC Provider works fine (with policy) - same output
    Only difference comes from:
    Security.addProvider(new BouncyCastleProvider());and
    Cipher cipher = Cipher.getInstance(aesCipher, "BC");What I am just trying to do is to use the BC API directly - no provider - so that my AES-256 ciphered output is the same that the Sun and BC provider with policy installed.
    I managed to do it - but by padding manually the data myself so that it is a multiple of 16 in length (I would llike to avoid this):
    public String encryptToBase64(String data) throws Exception {
              final byte[] newData = EncryptionUtils.getBytes(data);
              return Base64.encodeBase64String(encode(newData));
    }     private byte[] encode(byte[] inputBytes) throws Exception {
             final BufferedBlockCipher cipher = getCipher(true);
             final byte[] outputBytes = new byte[cipher.getOutputSize(inputBytes.length)];
             int outputLen = cipher.processBytes(inputBytes, 0, inputBytes.length, outputBytes, 0);
             outputLen += cipher.doFinal(outputBytes, outputLen);
             final byte[] finalBytes = new byte[outputLen];
             System.arraycopy(outputBytes, 0, finalBytes, 0, outputLen);
             return finalBytes;
    private BufferedBlockCipher getCipher(final boolean forEncryption) {
              final BlockCipher aesEngine = new AESEngine();
              final BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(aesEngine, new PKCS7Padding());
             cipher.init(forEncryption, new KeyParameter(rawKey));
             return cipher;
    }with
    public class EncryptionUtils {
         public static final int DEFAULT_BLOCK_SIZE = 16;
         public static final String pad = "                ";
         public static byte[] getBytes(final String str) {
              if (str.length() == DEFAULT_BLOCK_SIZE) {
                   return str.getBytes();
              final int padding = 16 - str.length() % 16;
              final int newSize = str.length() + padding;
              return (str + pad).substring(0, newSize).getBytes();
    }Apologies if I was not clear.
    On top of that - if your code is deciphered on Android for ex, using BC makes sense as I think it is the provider for Android.
    thx

  • Programmatically determine AES max key size?

    On a JRE that does not have the JCE unlimited strength jurisdiction policy files installed, I find that attempting to create an AES Cipher with a key size larger than 128 bits will throw an InvalidKeyException. Is there a better way to determine whether or not larger AES key sizes are permitted? Relying on the InvalidKeyException seems fragile, as there are other things that can cause that exception to be thrown.

    [Cipher.getMaxAllowedKeyLength()|http://java.sun.com/javase/6/docs/api/javax/crypto/Cipher.html#getMaxAllowedKeyLength(java.lang.String)]

  • SunJCE, DH+AES

    Hi!
    I am trying to use SUN's default provider SunJCE to generate secret key out of DH key agreement. jdk version is 1.4.2.
    And I had ran into trouble of KeyAgreement not wanting to generate an AES key.
    java.security.NoSuchAlgorithmException: Unsupported secret key algorithm: AES
         at com.sun.crypto.provider.DHKeyAgreement.engineGenerateSecret(DashoA6275)
         at javax.crypto.KeyAgreement.generateSecret(DashoA6275)
         at Test.CryptoTests.main(CryptoTests.java:67)Do I understand right that there is no way to generate AES secret key out of SunJCE's v1.42 KeyAgreement?
    Of course I can use Blowfish or DESEDE, it's just that I prefer to use AES. I'd also prefer not to use third party providers' libraries.
    How stupid would be an idea to generate Blowfish key, convert it into a string form and use it as a password for a previously generated AES Cipher?

    How stupid would be an idea to generate Blowfish key,
    convert it into a string form and use it as a password
    for a previously generated AES Cipher?Ooooops. I've just discovered that there is no PBE + AES encryption in SunJCE. Looks like I'll have to settle with the Blowfish.

  • Can't get AES to work

    Hey all,
    I just registered here in an attempt to fix my problem... I've tried everything I can think of.
    My problem seems simple. I do this:
    SecretKeySpec keyspec = new SecretKeySpec(key, "AES");
    SecretKeyFactory factory = SecretKeyFactory.getInstance("AES");
    SecretKey secretkey = factory.generateSecret(keyspec);
    Cipher aes = Cipher.getInstance("AES");
    aes.init(Cipher.DECRYPT_MODE, secretkey);
    return aes.doFinal(data);
    And I get this:
    java.security.NoSuchAlgorithmException: Algorithm AES not available
    at javax.crypto.SunJCE_b.a(DashoA12275)
    at javax.crypto.SecretKeyFactory.getInstance(DashoA12275)
    at system.Decryptor.decrypt(Decryptor.java:78)
    at system.Decryptor.<init>(Decryptor.java:43)
    This is at the 'SecretKeyFactory.getInstance("AES");' line. When removed, the 'Cipher.getInstance("AES");' line complains about the same thing ("No support for AES").
    In order to remedy this problem I've tried the following:
    - Installing Java 1.4.2_09 (I had 1.4.2_05)
    - Installing Java 5.0 Update 4 and using that instead
    - Using the Bouncy Castle Provider
    - Using the Cryptix JCE Provider
    - Installing the unlimited strength policy files
    - Not using Eclipse
    - Forcing the SunJCE Provider (result in "no such algorithm: AES for provider SunJCE")
    - Using DES (same error messages, only for DES!)
    - Rebooting (I just didn't know anymore :P)
    Short from reinstalling Windows 2000 I can't think of anything else. I googled for two nights trying to find people with the same problem but it appears I'm pretty unique... none of the fixes I found worked. I'm pretty sure it must be something related to my set up, since by all means, it should work.
    Does anyone have any idea what I can do to fix it? Thanks in advance for any of your help!

    hi there,
    I just read your posts and apperently I have the same problem.
    I get an error message: "Algorithm AES not available"
    the thing is this: on my computer (XP) everything works fine! the encryption AES is working (I also able to decrypt)!!! but when I try the SAME code on a different computer (MS2003) it generates the error: "Algorithm AES not available"
    is there any file I should add so it will work?
    thanks for any help
    peter

  • Can firefox uses intel AES-NI for HTTPS sites?

    I would like to ask if current version of Firefox can used Intel AES-NI instruction to accelerate HTTPS performance? (if AES cipher is used of course)
    Or is there any quide to enable such feature? like compile with correct patched openssl library...
    If there's such option for Firefox how can I verify that it's turned on?
    Thanks a lot.

    This is the response I got back from Contentwatch/Netnanny......
    ''We do have an open bug regarding the incompatibility with FireFox 33. We ask that you use FireFox 32 until we get the issue resolved.
    https://ftp.mozilla.org/pub/mozilla.org/firefox/releases/32.0/win32/en-US/''
    I don't know how advisable it is to go back a release though.

Maybe you are looking for

  • Background report list download to excel

    I run an ALV hierarchical sequential report in background. Then when I download the report output ( thro SM37 ) to excel, the whole output of the report comes in one cell ( excel ). In other words the columns of the report will not appear in excel. f

  • Adding a blog to our Muse website via Business Catalyst?

    We want to add a blog to our company's website. Ideally, we'd add it at the subfolder level. Will we be able to do this on our Muse site that is hosted in Business Catalyst?

  • Treo 650?

    I am a fairly new PowerBook user, as well as fairly new to the real estate industry. I have had to deal with using Virtual PC to access my local MLS - I've gotten over it and it is working just fine. Now I am looking into purchasing a Treo 650 throug

  • How do i update my ios from 5.1.1 to 6.0

    how do I update ios 5.1.1 to 6.0

  • AVCHD Import into Imovie

    So here is my problem, and it a big one. I recorded some video with a sony camera that records AVCHD ( .mts ) So I imported into imovie first try everything was great! So i recored more and now i want to import the footage. Same camera Same computer