Question

Why hashing is required if i am using my own secret key ? i found that everywhere it is done as shown below

        key = myKey.getBytes("UTF-8");
        sha = MessageDigest.getInstance("SHA-1");
        key = sha.digest(key);
        key = Arrays.copyOf(key, 16);
        secretKey = new SecretKeySpec(key, "AES");

Can some one explain me what is the benefit of hashing here ?

Was it helpful?

Solution

because in your case AES requires a 128 bit key so to build it up it need 16 bytes. How to get those 16 bytes? The most common way is to hash your user password and grab the first 16 bytes of the hash. Doing this will ensure that the AES algorithm will always receive a proper 16 bytes key.

Thanks to the hashing algorithm even short passwords such as "123456" or "god" will be transformed to a fixed length 20 byte hash

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top