Search code examples
javaarraysbyteaessecure-random

How to use SecureRandom output in a byte array properly?


I am trying generate a random key with SecureRandom, but I am facing issues when putting the output in a byte array. It doesn't recognize the output of the SecureRandom.

public static String byteToHex(byte[] hash) {

        StringBuilder sb = new StringBuilder(hash.length * 2);
           for(byte b: hash) {
                sb.append(String.format("%02x", b));
           }
        return sb.toString();
    }
    SecureRandom r = new SecureRandom();
            byte a[] = new byte[16]; 
            r.nextBytes(a);

I hardcode the output in a byte array:

byte[] k = {ac,1d,71,c8,96,bd,f7,d5,03,38,bc,46,a2,b4,f1,a8};

The error I get is:

Multiple markers at this line
    - a2 cannot be resolved to a variable
    - bd cannot be resolved to a variable
    - d5 cannot be resolved to a variable
    - b4 cannot be resolved to a variable
    - c8 cannot be resolved to a variable
    - f7 cannot be resolved to a variable
    - a8 cannot be resolved to a variable
    - f1 cannot be resolved to a variable
    - Type mismatch: cannot convert from double 
     to byte
    - ac cannot be resolved to a variable
    - bc cannot be resolved to a variable
    - Type mismatch: cannot convert from double 
     to byte

I want to use it as a key to encrypt a message with AES


Solution

  • The value you have got from an earlier execution of your snippet has been formatted in a way which is not valid Java code. It seems the numbers are written in hexadecimal notation. To use that in Java you have to prepend 0x to the numbers. These will then be interpreted as integers, therefore you have to cast them to bytes (which works as your numbers are small enough):

    byte[] = { (byte) 0xac, (byte) 0x1d, ... };