Note that there are some explanatory texts on larger screens.

plurals
  1. POCreating cipher key from random text on Android
    primarykey
    data
    text
    <p>I'm having a little problem. In my app I need to create a key for AES encryption from String written by a user, and I have no idea how to do it. For example: user writes: "abscde" and I need to some how change it to an AES key. Here is my code. It works but only with key provided in hex, like "000102030405060708090A0B0C0D0E0F".</p> <pre><code> public static String encrypt(String text, String key){ String mess="error"; try{ byte[] encodedText=text.getBytes(Charset.forName("UTF-8")); byte[] keyData=hexStringToByte(key); SecretKeySpec sKey=new SecretKeySpec(keyData, "AES"); Cipher encryptionCypher=Cipher.getInstance("AES/CBC/PKCS5Padding"); final int blocks=encryptionCypher.getBlockSize(); final byte[] ivData=new byte[blocks]; final SecureRandom rnd=new SecureRandom(); rnd.nextBytes(ivData); final IvParameterSpec iv=new IvParameterSpec(ivData); encryptionCypher.init(Cipher.ENCRYPT_MODE, sKey,iv); final byte[] encryptedMessage=encryptionCypher.doFinal(encodedText); final byte[] ivAndMessage=new byte[ivData.length+encryptedMessage.length]; System.arraycopy(ivData, 0, ivAndMessage, 0, blocks); System.arraycopy(encryptedMessage, 0, ivAndMessage, blocks, encryptedMessage.length); final String finalMessage=Base64.encodeToString(ivAndMessage, 0); mess=finalMessage; } catch (IllegalBlockSizeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (BadPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (InvalidAlgorithmParameterException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return mess; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload