开发者

Android AES Encryption Zero Padding

开发者 https://www.devze.com 2023-03-24 01:57 出处:网络
I need to encrypt a file using AES, with a CBC block size of 16 bytes, and key of 256 bits. And the file needs to be zero padded to a multiple of 16 bytes. And after encrypting the file the amount of

I need to encrypt a file using AES, with a CBC block size of 16 bytes, and key of 256 bits. And the file needs to be zero padded to a multiple of 16 bytes. And after encrypting the file the amount of padded zeros needs to be appended to the end.

For example, if I have a file that is 9 bytes, 7 zero bytes will be appended. The 16 bytes will be encrypted and then the length of the read data, 9, will be appended to the end. So the total length should be 17 bytes with the last byte unencrypted.

I'm using the Cipher class, and I know to use "AES/CBC/" but I don't know if there is a padding method that describes what I want.

EDIT: The last byte should be how many bytes are real data in the last 16 开发者_如何学Gobyte padded cell.


Not sure if you already solved your problem, but I think the padding type you're looking for is ZeroBytePadding. This code works for me on the 2.3.3 simulator:

String stringKey = "60380131061660211660380426804995";
String message = "This is a secret message";
try {
    SecretKeySpec sks = new SecretKeySpec(stringKey.getBytes(),"AES");
    Cipher c = Cipher.getInstance("AES/ECB/ZeroBytePadding"); // Change to CBC and use appropriate IV
    c.init(Cipher.ENCRYPT_MODE, sks);
    c.update(message.getBytes());
    byte[] ciphertext = c.doFinal();
    Log.i("CE", new String(ciphertext));

    } catch (NoSuchAlgorithmException e) {
        Log.e("CE",e.getMessage());
    } catch (NoSuchPaddingException e) {
        Log.e("CE",e.getMessage());
    } catch (InvalidKeyException e) {
        Log.e("CE",e.getMessage());
    } catch (IllegalBlockSizeException e) {
        Log.e("CE",e.getMessage());
    } catch (BadPaddingException e) {
        Log.e("CE",e.getMessage());
}


You don't need to manually do anything as Android has all the libs you need (via JCE) to do this painlessly.

I posted some AES encryotion code I wrote for an Android app here: http://pocket-for-android.1047292.n5.nabble.com/Encryption-method-and-reading-the-Dropbox-backup-td4344194.html#a4454327

You might want to pay attention to the padding schemes which in my case was PKCS5Padding.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号