Java 256-bit AES Password-Based Encryption

后端 未结 9 1377
名媛妹妹
名媛妹妹 2020-11-21 05:22

I need to implement 256 bit AES encryption, but all the examples I have found online use a \"KeyGenerator\" to generate a 256 bit key, but I would like to use my own passkey

9条回答
  •  名媛妹妹
    2020-11-21 05:41

    Generating your own key from a byte array is easy:

    byte[] raw = ...; // 32 bytes in size for a 256 bit key
    Key skey = new javax.crypto.spec.SecretKeySpec(raw, "AES");
    

    But creating a 256-bit key isn't enough. If the key generator cannot generate 256-bit keys for you, then the Cipher class probably doesn't support AES 256-bit either. You say you have the unlimited jurisdiction patch installed, so the AES-256 cipher should be supported (but then 256-bit keys should be too, so this might be a configuration problem).

    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, skey);
    byte[] encrypted = cipher.doFinal(plainText.getBytes());
    

    A workaround for lack of AES-256 support is to take some freely available implementation of AES-256, and use it as a custom provider. This involves creating your own Provider subclass and using it with Cipher.getInstance(String, Provider). But this can be an involved process.

提交回复
热议问题