Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to encrypt data in BlackBerry using the AES 256 encryption method. The requirement is to encrypt with No Padding; "AES/ECB/NoPadding". I am passing a 16 byte array and the encrypted data returned is a hex value of length 32. I have tried the following but it is not producing the correct result. The returned value is different from the expected encrypted value; tested in Android. The results between Android and BlackBerry do not tally. I have used the following method:

public static String EncryptData(byte[] keyData, byte[] data) throws Exception {      
          String encryptedData = "";        
          AESKey key = new AESKey(keyData);
          NoCopyByteArrayOutputStream out = new NoCopyByteArrayOutputStream();
          AESEncryptorEngine engine = new AESEncryptorEngine(key);
          BlockEncryptor encryptor = new BlockEncryptor(engine, out);
          encryptor.write(data, 0, data.length);
          int finalLength = out.size();
          byte[] cbytes = new byte[finalLength];
          System.arraycopy(out.getByteArray(), 0, cbytes, 0, finalLength);
          encryptedData = getHexString(cbytes);
          return encryptedData;
      }

Can anyone please guide?

EDIT: Below is the equivalent Android code:

Dim Kg As KeyGenerator
    Dim c As Cipher
    c.Initialize("AES/ECB/NoPadding") ' just "DES" actually performs "DES/ECB/PKCS5Padding". 
    Kg.Initialize("DESede")
    Kg.KeyFromBytes(key)
    bytes = Kg.KeyToBytes
    msg_data = c.Encrypt(msg_data, Kg.key, False)
    Return Bconv.HexFromBytes(msg_data)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
140 views
Welcome To Ask or Share your Answers For Others

1 Answer

There's a mistake in your Basic4Android code. You initialize the cipher with AES:

c.Initialize("AES/ECB/NoPadding")

but then initialize the key generator with TripleDES:

Kg.Initialize("DESede")

According to this documentation, just change "DESede" to "AES":

Kg.Initialize("AES")

Also, I wouldn't recommend using AES with ECB and no padding. It's insecure, especially when it's just as easy to use CBC or CTR mode. See this wikipedia article for an example of how unsafe it really is.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...